Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically sign in a user through Devise in Rails

I need to have a custom mechanism for signing in using Devise with Rails 4. So I found the sign_in method in Devise's test helpers section of their documentation:

sign_in @user          # sign_in(resource)

But is that the proper way to sign someone in from the web? In particular, will it do all the things Devise does when a user signs in, like recording the date/time stamps, IP addresses, sign in counts, etc? Or is this just for testing purposes?

like image 558
at. Avatar asked Mar 17 '14 20:03

at.


People also ask

How do you check if a user is signed in rails?

If you want to check whether user is signed for every action in the application, you have to put the filter in the application controller. You can do this for a specific controller also. Save this answer.

What does Devise gem do?

Devise is the cornerstone gem for Ruby on Rails authentication. With Devise, creating a User that can log in and out of your application is so simple because Devise takes care of all the controllers necessary for user creation ( users_controller ) and for user sessions ( users_sessions_controller ).


2 Answers

Devise offers a bunch of helpers, two of which are these:

sign_in(resource_or_scope, *args)
sign_in_and_redirect(resource_or_scope, *args)

You can use these from any controller.

If using sign_in already works for you but leaves the user on a blank page, check your logfile to see if there is a redirect going on, and where it redirects to. Or just make the redirect explicit by using the second of the helpers above.

References:

  • https://stackoverflow.com/a/8123646/2034097
like image 74
Chuanpin Zhu Avatar answered Nov 13 '22 18:11

Chuanpin Zhu


It is the proper and standard way to programatically sign a user in. Looking at the devise login code sessions#create you can see they use this method as well.

like image 8
Pierre Pretorius Avatar answered Nov 13 '22 16:11

Pierre Pretorius