I would like to set a boolean flag upon user confirmation via Devise. Essentially I want to set the user as 'active'. However, Devise simply confirms the account and logs them in.
How can I create a callback of some sorts to update my user record to set that 'active' column to true upon confirmation?
Any help very appreciated!
Presuming that your authentication model is called User, you can do this:
class User < ActiveRecord::Base
def active?
super and (not self.confirmed_at.nil?)
end
end
With this, Devise will not login the user but will wait until the user confirms (the confirmed_at field will be non-NULL if a user has confirmed)
For your particular question, you're better off implementing your active? attribute as confirmed_at being nil, as suggested by Zabba.
But here is how to do what you're asking, since it may be helpful to people trying to set other values on the user after confirmation.
class Users::ConfirmationsController < Devise::ConfirmationsController
def show
# let Devise actually confirm the user
super
# if they're confirmed, it will also log them in
if current_user then
# and you can do whatever you want with their record
current_user.active = true
end
end
end
This is basically a comment on Turadg's Answer below. If you follow that suggestion (which I did) you will have a small problem when users attempt to use an invalid confirmation_token. You will get a "Missing template users/confirmations/new". What the Devise::ConfirmationsController is doing here is sending you to devise/confirmations/new to inform you the token is invalid and allow you to send another one.
Since I had already customized the Devise views, what I ended up doing to get around this minor issue is moving the devise/confirmations/new.html.haml file into the now expected location under user/confirmations/new.html.haml.
Related
I have functionality of inactive account in my application for handling this i override active_for_authentication? method as below
def active_for_authentication?
super && activated?
end
But In my application super admin can also directly login in to other user account, whether it is active or not active
bypass_sign_in(User.find(resource.id))
I used above method for by pass sign in, it allows me to directly sign in only for activated user, when i login for non activated user it goes in infinite loop .
Any solutions to over come this issue or don't run active_for_authentication? callback when bypass_sign_in?
When admin logs in to another user account you can store some additional data in session, that makes it clear that this is the super admin mode.
def login_as(another_user)
return unless current_user.super_admin?
session[:super_admin_mode] = true
bypass_sign_in(another_user)
end
Unfortunately, you can't access session in Rails models, but you can store needed session information in some per-request global variable that is available in models. The solution might be like this:
module SessionInfo
def self.super_user_mode?
!!Thread.current[:super_user_mode]
end
def self.super_user_mode=(value)
Thread.current[:super_user_mode] = value
end
end
In the ApplicationController:
class ApplicationController < ActionController::Base
before_filter :store_session_info
private
def store_session_info
SessionInfo.super_user_mode = session[:super_admin_mode]
end
end
In the model:
def active_for_authentication?
super && (activated? || SessionInfo.super_user_mode?)
end
Also, you should make sure that the :super_admin_mode flag is removed from session when the super user logs out. Maybe it happens automatically, I am not sure. Maybe you will need to do it manually overriding Devise::SessionsController#destroy method (see the example below)
def destroy
session[:super_admin_mode] = nil
super
end
Also read this for better understanding of how devise handles session Stop Devise from clearing session
I recently came across a similar issue where I needed to allow an Admin to sign in as regular Users who were not active in Devise. I came up with the following solution that doesn't involve using Thread.current (which after looking into further online it seems like using Thread.current could be a precarious solution to this problem).
You can create a subclass of User called ProxyUser that has the active_for_authentication? return true. Something like this:
class ProxyUser < User
# If you have a type column on User then uncomment this line below
# as you dont want to expect ProxyUser to have type 'ProxyUser'
#
# self.inheritance_column = :_type_disabled
devise :database_authenticatable
def active_for_authentication?
true
end
end
Then in the controller you want something like this:
proxy_user = ProxyUser.find(params[:user_id])
sign_in :proxy_user, proxy_user
Also in your routes you will need devise to expect ProxyUser so include:
devise_for :proxy_users
And finally when you sign this user out (assuming you can sign the user out in your controller code) make sure to tell devise the scope of the sign out, so you would do
sign_out :proxy_user
And then finally note that in your app you may be expecting current_user in different places (such as if you use CanCanCan for authorization) and now when you sign in as a proxy_user your app will return current_user as nil. Your app will instead have an object called current_proxy_user that will be your signed-in ProxyUser object. There are many ways to handle the issues resulting from your current_user returning nil in this case (including overwriting current_user in your application controller).
Actually I am using devise for login and registration and its working fine, it send a confirmation email which is really good. But I need to send confirmation email in specific cases. I am passing user type in URL and on behalf of that I want to set mail. I have two type of users, one will be confirm their account their self reset of the users can not confirm their account only admin can approve their accounts. I have override the create method
def create
super
if params[:type]=='xyz
#user.skip_confirmation_notification!
end
end
but it sends mail in both cases. Please tell where am wrong.
So according to devise confirmable module you can skip to send confirmation and email by following code.
def confirm_your_type_user_without_confirmation_email
# check your condition here and process the following
self.skip_confirmation!
self.confirm!
# condition may end here
end
Now lets call it on create hook.
class User < ActiveRecord::Base
after_create :confirm_your_type_user_without_confirmation_email
....
end
for more reference you may check this:
Devise Confirmable module
The solution should be something similar as I mentioned here above. And its best practice to avoid controller to handle these responsibilities, because its not something your controller should take. :)
I hope my answer will give you some way to solve your problems! Thanks!
If I've got a rails application and I'd like to add authentication to with Devise, how would I allow users who have a null password in the database to sign in without one?
I'm interested in hearing answers along the lines of the lifecycle and what files I'd have to author to get it done.
Step 1: Allow the record to be saved.
Step 2: Sign in the record
To allow the record to be saved, you'll want to do validations yourself. I describe here how to do custom validations: http://jessewolgamott.com/blog/2011/12/08/the-one-where-devise-validations-are-customized/ .... In your case, you'll want to remove the password validations.
To sign in the record, you'll need to have a custom sign in path. You can override the devise sessions controller, but this could do the trick:
class SessionsController < ApplicationController
def create
user = User.find_by_email!(params[:session][:email])
sign_in user
redirect_to root_path
end
end
It turns out, Devise is built on Warden. This means that I only have to create my own custom Warden strategy:
https://github.com/hassox/warden/wiki/Strategies
I am using Devise for authentication in my application.
How do I forbid certain users from signing in - kind of disable a user?
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)
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.
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.
Sounds like you may be interested in cancan
https://github.com/ryanb/cancan
http://railscasts.com/episodes/192-authorization-with-cancan
I would like to manually create new Users, without forcing them to verify their email address.
The idea is to allow existing users to automatically add their friends without requiring their registration. It makes sense for the business case I'm working to solve.
How can this be achieved with Devise?
The skip_confirmation! method is available to any confirmable model.
#user = User.new params[:user]
#user.skip_confirmation! # Sets confirmed_at to Time.now, activating the account
#user.save
The user account will be activated though. If you don't want that, continue reading.
Devise uses conditional callbacks to generate the confirmation token and send the email. The callbacks will be called only if confirmation_required? returns true. Redefine it on your model:
def confirmation_required?
false
end
However, this will make the active_for_authentication? method always return true because it takes whether or not confirmation is required into account. We have to redefine that as well:
def active_for_authentication?
confirmed? || confirmation_period_valid?
end
This way, the account will stay inactive and no confirmation email will be sent. You will have to manually activate the user by calling confirm! on the record or just setting confirmed_at to any date.
It's quite a hack, but it should work.
For reference: confirmable.rb
I just want to add for future reference that since Devise 2.2 there is now a skip_confirmation_notification! method available as well which basically does everything from Matheus' post without redefining the methods in the model.