3
votes

I'm developing an app that utilizes devise for my user records and omniauth for records owned by the user, rather than using the typical omniauth + devise for user records. I'm trying to add devise's user authentication to the omniauth routes /auth/:provider so that non-registered visitors cannot access those routes and trigger the auth process for a specific provider.

I've been able to add authentication to the callbacks by using devise's authenticate_user! helper method in my Sessions controller, so I'm at least stopping non-registered visitors from being able to create records from the omniauth flow, but I'd like to have devise's user auth working in all phases of the omniauth flow.

Any ideas on how to add devise's user auth to the initial omniauth routes whether using something similar to my current solution or through my routes.rb file using devise's authenticate :user do?

3

3 Answers

1
votes

A solution for anyone reach here with the same question:

Do the Devise authentication in the request_phase. If you are using a strategy gem, e.g., omniauth-facebook, you can monkey patch that specific strategy in you initializer, for example, in config/initializers/omniauth.rb:

module FacebookExtension
  include Devise::Controllers::Helpers
  def request_phase
    # it might be 'admin_user_signed_in?' depends on what your user model is
    if user_signed_in? 
      super
    else
      # redirect to any path you think is suitable once devise authentication fail
      redirect Rails.application.routes.url_helpers.new_admin_user_session_path
    end 
  end  
end
OmniAuth::Strategies::Facebook.prepend FacebookExtension
0
votes

This solution worked for me. It essentially creates a new route that checks if a user is currently signed in and then redirects them to the authorize path for the requested provider.

routes.rb:

scope module: :authentication do
  devise_scope :user do
    # ...
    get 'users/auth/:provider/setup', to: 'omniauth_callbacks#before_request_phase'
  end
  # ...
end

omniauth_callbacks_controller.rb:

def before_request_phase
  authorize_path = send("user_#{params[:provider]}_omniauth_authorize_path".to_s)
  if current_user.present?
    redirect_to(authorize_path)
  else
    redirect_to login_path(return_to: authorize_path)
  end
end
-1
votes

Add the devise autheticate_user! in application controller. or use before filter to call it before omniauth authentication methods.