Rails 3.2. Hi. Currently out app has an authentication system implemented that we did and we are going to migrate to devise. I am at wits end here trying to get the devise log in to work. Somehow I have drilled down the problem to the part where Devise actually creates a user session.
def create
self.resource = warden.authenticate!(auth_options)
set_flash_message(:notice, :signed_in) if is_flashing_format?
sign_in(resource_name, resource)
yield resource if block_given?
respond_with resource, location: after_sign_in_path_for(resource)
end
Routes (I have changed the devise controller and literally just pasted the Devise controller code to debug it with pry):
devise_for :users, controllers: { sessions: "sessions" }
The problem here is that warden is not even hitting the database with an authenticate. It just returns nil. I checked my other, simpler application and authenticate's behavior scans the database, regardless if email/password is correct. How do I get Warden/Devise for that matter to actually do a select statement to check the database out?
(If there is anything I can paste to help you guys I'll paste it)
In case it may help someone else: I was running into this very same problem. The source of the trouble turned out to be that I had a custom app/views/sessions/new.html.erb view that was not copied from devise.
See https://github.com/plataformatec/devise/issues/3700 for more information.
Try look in console the authentication keys of your devise model:
(your_model).authentication_keys
If result is different respect keys you need (i.e email), just add explicity in your model:
:authentication_keys => [:email]
I resolved in this way. Hope this help
Bye
Related
I have just started working on a Rails 4 (4.2.3) app where I use Devise for user authentication. I want users to be able to play around with the app before signing upp by creating a test project and be signed in as a guest user. When the user signs up (or in) I want to assign the test project to the new current user.
I have been following this guide from Platformatec: https://github.com/plataformatec/devise/wiki/How-To:-Create-a-guest-user
Creating the guest user works, but when signing up or in with an active guest user session I get the following error:
Filter chain halted as :require_no_authentication rendered or redirected
If I clear my session it works. The method that manages my guest user looks like this:
def current_or_guest_user
if current_user
if session[:guest_user_id] && session[:guest_user_id] != current_user.id
logging_in
guest_user(with_retry = false).try(:destroy)
session[:guest_user_id] = nil
end
current_user
else
guest_user
end
end
As mentioned, creating guest users seems to work just fine. But this logic never happens:
# should delete the guest user and clear the session.
if current_user
if session[:guest_user_id] && session[:guest_user_id] != current_user.id
logging_in
guest_user(with_retry = false).try(:destroy)
session[:guest_user_id] = nil
end
current_user
I'm pretty sure that my guest user session is conflicting with my new user and causes this Devise error (since the guest user never gets deleted on sign up):
Filter chain halted as :require_no_authentication rendered or redirected
The rest of my guest user logic looks more or less exactly like this linked guide: https://github.com/plataformatec/devise/wiki/How-To:-Create-a-guest-user. I also added the code from the Authentication paragraph / example: https://github.com/plataformatec/devise/wiki/How-To:-Create-a-guest-user#authentication-this-may-interfere-with-the-current_user-helper.
Any ideas on what I'm missing, and how I can get my current_or_guest_user to delete the guest user on signup and signing when using Devise?
Update
This is how my routes look currently:
devise_for :users, controllers: { sessions: "users/sessions", registrations: "users/registrations" }
root :to => 'public#index'
resources :apps
get 'users/show', to: "users#show"
get 'users', to: "users#index"
post 'guests/receive_guest', to: "guests#receive_guest"
Update 2
The guide have the following statement:
When (and if) the user registers or logs in, we delete the guest user
and clear the session variable.
It doesn't explain much how and where to do it. I'm guessing I have to call current_or_guest_user somewhere again. But I'm not sure where since I'm not that familiar with Devise.
Update 3
To make it a bit more clear. This is the steps I want to achieve.
User creates a test project.
Upon creation of the test project a guest user and session gets created. The guest user should get deleted once the session ends or #3.
If the guest user signs up, he /she should get logged in and the test project should get assigned to the new real user.
The guest user should get deleted.
The above answer lacks of explanation, the loggin_in method is not being called because you have not defined your callback
In your ApplicationController you need to define and then set the callback like so:
define_callbacks :logging_in_user
set_callback :logging_in_user, :before, :transfer_guest_user_actions_to_current_user
def transfer_guest_user_actions_to_current_user
# todo
end
Have you tried to use devise-guests gem? it implements out of the box this functionality, instead of do it from scratch...
Check this example controller that is implementing guest login. Hope it helps.
I think the issue is caused by the guest_user warden strategy referenced in the guide.
Since Devise checks for a valid warden session before logging in, it causes a redirect and a flash message to appear:
if authenticated && resource = warden.user(resource_name)
flash[:alert] = I18n.t("devise.failure.already_authenticated")
redirect_to after_sign_in_path_for(resource)
end
So if you do not strictly need that authenticate! method to work on the guest user, you can simply deactivate that strategy and it should work.
Thanks for your answers skahlert and SsouLlesS. Skipping the warden strategy did help and defining callbacks seems like a clean approach. Beside that I had some other issues.
One was that my custom Devise controllers never got called. Created another question for that: Rails 4 - devise_for not using custom controllers. The solution was that I used the wrong url in my modal signup form. My form now looks like this:
= form_for(resource, as: resource_name, url: user_registration_path do |f|
Then I did as skahlert suggested and removed the warden strategy from my app.
Once my custom devise Users::RegistrationsController < Devise::RegistrationsController controller got called I decided to override the create action. It's not completely tested, but it looks like this:
# POST /resource
def create
# Delete guest user and reset session.
new_user_from_guest = guest_user
guest_user(with_retry = false).try(:destroy)
session[:guest_user_id] = nil
build_resource(sign_up_params)
resource.save
yield resource if block_given?
if resource.persisted?
if resource.active_for_authentication?
set_flash_message :notice, :signed_up if is_flashing_format?
sign_up(resource_name, resource)
# Assign the guest users app to the new current user.
new_user_from_guest.apps.each do |app|
app.user_id = current_user.id
app.save!
end
respond_with resource, location: after_sign_up_path_for(resource)
else
set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_flashing_format?
expire_data_after_sign_in!
respond_with resource, location: after_inactive_sign_up_path_for(resource)
end
else
# Reset test user if signup fails, I have not tested this part yet.
guest_user
guest_user.apps << new_user_from_guest.apps
guest_user.save!
clean_up_passwords resource
set_minimum_password_length
respond_with resource
end
end
Everything seems to work now. Could do some refactoring and possibly try the callback approach that SsouLlesS suggested in his answer.
Rails: 4.0.0,
Devise: 3.0.0rc
Devise seems not to add error messages to models at all, delegating that to validations. That's fine generally. But in the case of the SessionsController, would it make sense to add the errors to the model so that you can use field_with_errors or some such functionality and say 'email is required' if the user does not put their email in.
The snippet below is where I think I would have to modify Devise to get it to add errors to the model.
class Users::SessionsController < Devise::SessionsController
# POST /resource/sign_in
def create
self.resource = warden.authenticate!(auth_options)
debugger
set_flash_message(:notice, :signed_in) if is_navigational_format?
sign_in(resource_name, resource)
respond_with resource, :location => after_sign_in_path_for(resource)
end
end
Does anyone have any recommendations on what to do? Is it even a good idea to add errors to the model on sign in via something like the following? error.add(:model, "error message")
It just seems that if I use the default flash[:notice] message, then I miss out on being able to attach the error messages to specific fields, which is my aim.
Your concept is right with any other controllers except SessionsController.
Such vague information is desired for signing in activity. If an user inputted wrong information, he can only see "Invalid email or password" or something similar but not precise error.
The reason is to reduce the chance of brute signing trials.
I'm using Devise to handle authentication in a Rails app, and I'm using permanent_records to soft delete users. The default scope for my User model is the undeleted users. If a user deletes (deactivates) his account, I want him to be able to reactivate his account by logging in, similar to the way Facebook does it. Problem is, since Devise doesn't know to look for deleted users, no account is found. I thought about overriding the sessions#create method
def create
self.resource = warden.authenticate!(auth_options)
set_flash_message(:notice, :signed_in) if is_navigational_format?
sign_in(resource_name, resource)
respond_with resource, :location => after_sign_in_path_for(resource)
end
But since this is handled by Warden, it seems I'm out of luck. I'm afraid that if I start digging too deep I'm going to start breaking things.
Any ideas?
Thanks!
You need:
Overwrite find_for_authentication method in User model to allow finding for any users https://github.com/plataformatec/devise/blob/master/lib/devise/models/authenticatable.rb#L229
Redefine after_database_authentication method in your model to remove deleted flag here https://github.com/plataformatec/devise/blob/master/lib/devise/models/database_authenticatable.rb#L98
That is all, I believe. No need to touch controller actions.
this works with the paranoia gem:
class << self
def find_for_authentication(conditions)
User.unscoped do
user = super(conditions)
user.restore!(recursive: true) if user.deleted?
user
end
end
end
I am using devise and i am trying to update extra fields has user log in. So in order for me to be able to update my user.longitude i had to create in new controller who is acting has the rails controller sessions. Here the code I have
class MysessionsController < Devise::SessionsController
def create
self.resource = warden.authenticate!(auth_options)
set_flash_message(:notice, :signed_in) if is_navigational_format?
sign_in(resource_name, resource)
self.resource.longitude = params[:longitude]
self.resource.update_attributes(params[:longitude])
respond_with resource, :location => after_sign_in_path_for(resource)
end
end
I know it doesn't follow restfull and it doesnt work but i need to be able to update my user field and i am not sure how to do, this doesn't give me anything wrong, but it doesn't also modify it properly. Thank for any help
Your line:
self.resource.update_attributes(params[:longitude])
Might return false if the record is invalid and silently fail. Check that out first.
Second, you might want to take a look into alias_method_chain instead of copying the content of the create action of your inherited controller.
Otherwise, this is to update a record after a user logged in. You should save the longitude AFTER he signs in. Wherever you redirect the user after he signs in, let the following call handle the longitude update. Easy way could be to store the longitude in session if it needs to survive.
Is there anyone experience with Rails Devise plugin? Coz in my project, when the user typed username and password, I have to check in another table whether the user is active. There are two tables, first one is the user and the other one role_membership in role_membership table there's a column named active_status. I have to check whether the active_status = 1 otherwise the user cannot log in to the system. Anyone here knows how to configure the Devise plugin to check the value in another tables. I found some tutorials, but all of 'em mentioning about checking in a field in same table.
Thanks
modify your User model to include two additional methods
active_for_authentication?
inactive_message
see http://pivotallabs.com/users/carl/blog/articles/1619-standup-3-21-2011-deactivating-users-in-devise (NOTE: it is based on an older version of devise, below code should work)
class User
# check to see if a user is active or not and deny login if not
def active_for_authentication?
super && your_custom_logic
end
# flash message for the inactive users
def inactive_message
"Sorry, this account has been deactivated."
end
end
replace your_custom_logic with your specific code for determining if user is active or not
additional link: http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Authenticatable/
My best idea is to override devise session#create method.
In order to do it:
#app/controllers/sessions_controller.rb
class SessionsController < Devise::SessionsController
def create
resource = warden.authenticate!(auth_options)
#resource.is_active? should be implemented by you
if resource.is_active?
set_flash_message(:notice, :signed_in) if is_navigational_format?
sign_in(resource_name, resource)
respond_with resource, :location => after_sign_in_path_for(resource)
else
#put here your inactive user response
end
end
end
and in routes.rb
devise_for :users, :controllers => {:sessions => "sessions" }