How to call devise sign_in and sign_out methods of

2020-03-01 06:56发布

问题:

I have a Ruby on Rails 3.0.7 application and my user authentication with devisebut and I have an alternative sign up and sign in methods, I allow my users to sign up using their Facebook account then I save that login info in my users table the same one that devise uses to register and login users.

Steps

  1. ✔ User click on the Facebook button.
  2. ✔ I save his info (name and email extracted from Koala) I give the user a generic password.
  3. ☐ Login this new user with devise.
  4. ✔ Redirect to my main controller.

I'm just missing the 3rd step because I want to keep using the current_user helper and the user_signed_in? helper too.

So how do I tell devise to sign in this user automatically from my other controller?

I saw something like that on this question Devise: Have multiple controllers handle user sessions and it logs my user in but leads me to an blank page...

回答1:

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.

EDIT

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.



回答2:

Include Devise helpers in your controller and all the normal devise methods, e.g. sign_in or sign_out would automatically be available there.

class TestController < RocketPants::Base
  include Devise::Controllers::Helpers

Fortunately, if your controller extends ApplicationController, Devise includes these helpers as convenience methods automatically.

But, the RockePants repo explains a specific case where the controller doesn't extend ApplicationController, and thus this explicit include Devise::Controllers::Helpers is required https://github.com/filtersquad/rocket_pants/issues/7

Also, the official Devise docs are helpful to find other methods you will be able to use by including helpers http://rubydoc.info/github/plataformatec/devise/master/Devise/Controllers/Helpers