问题
I wish to know how to create an admin role in devise gem and how to make pages that just if you are logged as admin you could access, otherwise you get a 404 page.
回答1:
There is a simplistic way of doing this that I will share with you.
Create a migration that adds a boolean to your devise user:
rails g migration AddsAdminColumnToUsers
def change
add_column :users, :admin, :boolean, default: false, null: false
end
This will map back to your model and create a user.admin?
method.
For the page access I would create a method within ApplicationController
or better yet a controller concern called AuthenticateAdmin
.
Within either, create a method called authenticate_admin!
.
def authenticate_admin!
authenticate_user!
redirect_to :somewhere, status: :forbidden unless current_user.admin?
end
P.S. if within ApplicationController
also make sure this is a protected
method
Then for each of your controllers or actions you need to restrict:
before_action :authenticate_admin!, only: [:action] # `only` part if applicable
You want to be sending a forbidden
here.
The reason is beyond the scope of this question, but essentially Not Found
is different than not being authorized to do something.
In HTTP status codes, there is an Unauthenticated
, but in this case we are authenticated, the person is just forbidden to access the page (i.e. unauthorized).
This case calls for HTTP status 403 Forbidden.
来源:https://stackoverflow.com/questions/40794650/devise-add-admin-role