16

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?

at.
  • 50,922
  • 104
  • 292
  • 461
  • sign_in doesn't authenticate a user it just signs the user in. Have a look at this issue https://github.com/plataformatec/devise/issues/1230 – Kirti Thorat Mar 18 '14 at 01:54

3 Answers3

12

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:

Community
  • 1
  • 1
Chuanpin Zhu
  • 2,226
  • 1
  • 21
  • 21
8

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.

Pierre Pretorius
  • 2,869
  • 22
  • 21
  • looks like `sign_in` doesn't update all the other fields for the `User` model I referenced above, so I'll have to do that manually or figure out some easy devise method to call. Otherwise you're right, devise uses `sign_in` internally. – at. Mar 17 '14 at 22:53
4

Long story short: Yes, sign_in @user does all the things that devise would normally do when a user signs in. It could be useful, for example, allowing an Administrator to sign in as one of their users.

How To: Sign in as another user if you are an admin

Guillermo Siliceo Trueba
  • 4,251
  • 5
  • 34
  • 47
opticon
  • 3,494
  • 5
  • 37
  • 61