Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Authenticate Devise User Before Accessing Omniauth Routes

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?

like image 979
Mikael Kessler Avatar asked Jul 19 '26 13:07

Mikael Kessler


1 Answers

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
like image 150
Gret Avatar answered Jul 22 '26 03:07

Gret



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!