Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use both Devise and Doorkeeper gems?

I am building a web app (with an API too) that is using Devise gem for authentication and I also use Doorkeeper gem for authentication for the API part.

Problem is now that when I go to the URL for receiving the Oauth2 code (and login) I am redirected to the web app and not the client callback URL.

What I need to do is redirect to the web app when signing in normally and to the callback URL when using Oauth.

How can I do this? I am overwriting the Devise sessions controller but I do not know what to put into it.

This is my code:

def new
    session[:return_to] = params[:return_to] if params[:return_to]
    resource = build_resource
    clean_up_passwords(resource)
  end

  def create
    resource = warden.authenticate!(auth_options)
    sign_in(resource_name, resource)
    if session[:return_to]
      redirect_to session[:return_to]
      session[:return_to] = nil
    else
      respond_with resource, :location => after_sign_in_path_for(resource)
    end
  end

Problem is that Devise seems to ignore my redirect logic.

Please advice further.

like image 892
Jonathan Clark Avatar asked Jan 24 '13 15:01

Jonathan Clark


1 Answers

This worked for me, in ApplicationController (that Devise's controllers inherit from):

def store_location
  # store last url as long as it isn't a /users path
  session[:previous_url] = request.fullpath unless request.fullpath =~ /\/users/
end

def after_sign_in_path_for(_resource)
  session[:previous_url] || root_path
end

And in the Doorkeeper initializer:

resource_owner_authenticator do
  if user_signed_in?
    current_user
  else
    session[:previous_url] = request.fullpath unless request.fullpath =~ /\/users/
    redirect_to(new_user_session_path)
  end

end

The idea is to remember the path you came from in a session cookie and then let Devise redirect there when it calls its own after_sign_in_path_for callback.

Documentation pointed out the resource_return_to session key, but this worked for me so I didn't examine anymore.

like image 122
zmilojko Avatar answered Oct 05 '22 09:10

zmilojko