简体   繁体   中英

sign_in_and_redirect with omniauth-facebook to specific language

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!

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

我认为您必须将omniauth配置提取到yaml文件,并在回调链接的末尾插入“#{i18n.locale}”。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM