简体   繁体   中英

Show a page only if user is signed in? Ruby/Devise

I'm building an app with rails and for user authentication I'm using Devise.

I wanna know how to restrict access to certain pages unless the user is signed in. I'm guessing I have to change the code on my specific page Controller, but I'm not sure how.

Also, if a non authenticated user wants to access the page, how can I restrict it?

Thanks a lot!

You could do something on the page like this:

<% if user_signed_in? %>
  <div> show content here </div>
<%else %>
  <p>Please Sign Up or Sign In to view the content.</p>

  <h2><%= link_to "Sign up", new_user_registration_path%>

<% end %>

Hope it helps!

Or setup a before_action inside the controller:

before_action :authenticate_user!

The official documentation has details

You should do it inside of your controller, you can use:

before_filter :authenticate_user! 

right after this line:

class YourController < ApplicationController

You can also narrow it down to specific controller actions, so let's say you want to restrict access to specifically the Create and Destroy actions, you can do:

before_filter :authenticate_user!, only: [:create, :destroy]

which allows them to still freely access your other actions. Hope that helps!

There are several ways to do this.

One thing you can do is use devise´s authenticate_user! method in a before_action . I would recommend this because what it does is redirect the user to the sign_in page if there are not authenticated.

If you want to do a custom redirection, you can use your controller. Doing something like

def show
    @user = User.find(params[:id])
    redirect_to root_path unless @user == current_user #if you don't care who the user is I recommend to use user_signed_id? method
end

You could also restrict the content at the view level using that same if statement, but I wouldn't recommend that because it can have a negative impact on your app's UX.

Check out Devise documentation.

Also there is a good gem that would help you take care of authentication issues, but unfortunately it cannot help you to see if the User is signed in. Anyways, maybe it could be helpful to you so I will leave it here. It's name is CanCan

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM