开发者

OmniAuth dynamic callback url to authenticate particular objects instead of current_user

开发者 https://www.devze.com 2023-02-21 15:55 出处:网络
Say I have the models User and Project. Users and projects are HABTM-associated. My setup is actually a bit more complicated than this, but I think for the purposes of my question this will do.

Say I have the models User and Project. Users and projects are HABTM-associated. My setup is actually a bit more complicated than this, but I think for the purposes of my question this will do.

Now, I want to use omniauth to开发者_JS百科 authenticate a particular project with Twitter, Facebook, what have you. I've figured out how to define my omniauth path_prefix, but I don't know how I could pass in a variable like so: config.path_prefix = 'projects/:project_id/auth', much less make a custom callback url like project/:project_id/auth/twitter/callback.


This will break in production. In development you can get away with a session variable. But in production you need to have the callback url contain your project_id as it could be 2 or more register with different auth_project_id's and then you have no way of knowing which one is called afterwards (the callback is asynchronous).

https://github.com/mkdynamic/omniauth-facebook#custom-callback-urlpath

something like config.path_prefix = "projects/#{@project.id}/auth" might work. I'm testing a similar situation right now.


For posterity's sake, I solved it this way:

I added an auth method to my projects controller, which set a session variable session[:auth_project_id] and then redirectes to auth/ + params[:provider].

In my callback controller authentications, I got my project with @project = Project.find(session[:auth_project_id]), created the authentication, and then session[:auth_project_id] = nil to unset the session variable.


I have done similar thing with devise omniauthable, You can pas any parameter with link. like

<%= link_to "Add twitter Account",  user_omniauth_authorize_path(:twitter, params:  { project_id: @project.id     }) %>

Then in your callback controller

before_action :set_project, only: [:twitter]

def set_project
  @project = Project.find(request.env['omniauth.params']['project_id'])
end

Note: Do NOT use request.env['omniauth.auth']

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号