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.
-
It helps to provide any attempts you've made with code examples. The solution to this is actually quite simple (as someone elucidated in the answer), but the lack of any code or demonstration of an attempt lead to down votes – MageeWorld Nov 24 '16 at 23:46
-
This question was downvoted because of the obvious absence of research, not the lack of code examples. – fbelanger Nov 25 '16 at 22:26
-
Possible duplicate of [Creating an admin user in Devise on Rails beta 3](https://stackoverflow.com/questions/2708417/creating-an-admin-user-in-devise-on-rails-beta-3) – AMIC MING Nov 02 '17 at 17:37
-
https://github.com/heartcombo/devise/wiki/How-To:-Add-an-Admin-Role – thisismydesign Feb 16 '21 at 16:04
1 Answers
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.

- 3,522
- 1
- 17
- 32