Rails route namespaced in omniauth

2019-03-11 10:24发布

问题:

I have this in routes.rb:

namespace :api do
  namespace :v1 do
    ...
    devise_for :users, constraints: { format: :json },
      :controllers => { :omniauth_callbacks => "auths" }
    ...
  end
end

And produces among others, these routes:

new_api_v1_user_confirmation GET        /api/v1/users/confirmation/new(.:format)          api/v1/confirmations#new {:format=>:json}
                             GET        /api/v1/users/confirmation(.:format)              api/v1/confirmations#show {:format=>:json}
api_v1_user_omniauth_authorize            /users/auth/:provider(.:format)                   auths#passthru {:provider=>/facebook|twitter|linkedin/, :format=>:json}
api_v1_user_omniauth_callback            /users/auth/:action/callback(.:format)            auths#(?-mix:facebook|twitter|linkedin) {:format=>:json}

How could a get last two routes namespaced, something like:

/api/v1/auth/:provider(.:format)
/api/v1/auth/:provider/callback(.:format)

回答1:

Guess I should convert my comments into an answer:

For our app we are doing the pure json api thing, with backbone/marionette. To get oAuth working with devise - I removed it from devise. :) Removed the omniauthable property I had set up and removed the omniauth settings from my initializers/devise.rb. Then reading on the omniauth page I implemented it by itself.

My api lives under "/api/v1"

  1. Created the initializers/omniauth.rb file listing my providers and keys. For each provider I also gave it a :path_prefix=>"/api/v1/auth" property.
  2. Create a callback controller within my api called api/v1/oauth_controller.rb This was properly namespaced with modules and contains my callback path from the services.
  3. Updated my routes to setup the callback route for omni. See here: gist.github.com/DaveSanders/5835642
  4. Within OAuthController.create I consumed the details from the provider and go through the basic flow of "does the social network user exist and have a mapped account?" if so, log them in via devise's user.sign_in? If not, create the user and then sign them in.
  5. Redirect back to my app, which then boots up backbone again, which can then go get the logged in user details and use them as needed.

Your implementation may vary, but the way I handle my oAuth accounts is put them in their own tables (Twitters, Facebooks, etc) and then link them into my devise user. This way I can have multiple accounts associated and the user can log in with any of them.

Also, be sure to set your twitter/facebook callback to something like:

http://127.0.0.1:3000/api/v1/auth/twitter/callback

to match your route in dev.

Hope this helps others. If I forgot a step or you get lost, please ask.