Devise - How do I forbid certain users from signing in?
Ruby on-RailsDeviseRuby on-Rails Problem Overview
I am using Devise for authentication in my application.
How do I forbid certain users from signing in - kind of disable a user?
Ruby on-Rails Solutions
Solution 1 - Ruby on-Rails
Do it like this:
Create a column called is_active
for the User
model.
Then add the code below to the User
model:
class User < ActiveRecord::Base
#this method is called by devise to check for "active" state of the model
def active_for_authentication?
#remember to call the super
#then put our own check to determine "active" state using
#our own "is_active" column
super and self.is_active?
end
end
UPDATE
As Matt Huggins notes, the method is now called active_for_authentication?
(Documentation)
Solution 2 - Ruby on-Rails
Add a column to the User
model: allowed_to_log_in
.
Then add this to /app/models/user.rb
:
def active_for_authentication?
super and self.allowed_to_log_in?
end
If you want to inform the user with a custom message you can add this as well:
def inactive_message
"You are not allowed to log in."
end
I think that is quite important because the standard message from Devise says:
> "Your account is not activated yet."
That is confusing for users and the real reason is that you have "banned" them from logging in.
Solution 3 - Ruby on-Rails
You want to do authorization, not authentication. Devise only does authetication, though.
I.e. devise only tells you that a user is who he says he is.
You need something else to forbid him from using the site.
Authorization is a popular topic and there's a whole list of gems that can help you with it:
http://ruby-toolbox.com/categories/rails_authorization.html
Take your pick.
Solution 4 - Ruby on-Rails
Sounds like you may be interested in cancan