sign_in_and_redirect with omniauth-facebook to specific language

倾然丶 夕夏残阳落幕 提交于 2021-01-29 05:43:01

问题


I'm using omniauth-facebook gem with rails 3.2 and devise 2.0.

I have a website with 2 languages, english and spanish.

http://localhost:3000/en http://localhost:3000/es

The gem works fine for english users because in omniauth_callbacks_controller.rb the redirect go to http://localhost:3000/en

This is my omniauth_callbacks_controller.rb for facebook:

def facebook
    @user = User.find_for_facebook_oauth(request.env["omniauth.auth"], current_user)
    if @user.persisted?
      flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => "Facebook"
      sign_in_and_redirect @user, :event => :authentication
    else
      session["devise.facebook_data"] = request.env["omniauth.auth"]
      redirect_to new_user_registration_url
    end
  end

Then problem is for spanish users. that if they use http://localhost:3000/es the redirect from callback go to http://localhost:3000/en

I want that redirect from callback go to specific language that is using that user.

How can I do it?

Thank you!


回答1:


I had similar issue, and did not find a way to change the callback url, but I could set the locale in the method when the callback happens.

The original url (which has the orignal correct locale) is in stored in request.env['omniauth.origin']

So in facebook method pick the locale from the original url, where it is in similar way the two letters after the domain part.

I added in the beginning of the facebook method:

I18n.locale = exctract_locale_from_url(request.env['omniauth.origin']) if request.env['omniauth.origin']

Where the exctract_locale_from_url is a horrible looking regexp :)

def exctract_locale_from_url(url)
  url[/^([^\/]*\/\/)?[^\/]+\/(\w{2})(\/.*)?/,2]
end



回答2:


I think you must extract your omniauth config to yaml file and insert "#{i18n.locale}" to the end of callback link.



来源:https://stackoverflow.com/questions/10227136/sign-in-and-redirect-with-omniauth-facebook-to-specific-language

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!