-
Notifications
You must be signed in to change notification settings - Fork 5.5k
How To: Redirect with locale after authentication failure
maxcal edited this page Sep 5, 2014
·
2 revisions
Set your locale & Make your default_url_options a class method in your ApplicationController
def set_locale
I18n.locale = params[:locale]
end
def self.default_url_options(options={})
options.merge({ :locale => I18n.locale })
end
gurix provided the following solution in response to issue #272
First we need a controller inside the locale scope that sets us the current locale in the session.
routes.rb
:
Rails.application.routes.draw do
# We need to define devise_for just omniauth_callbacks:uth_callbacks otherwise it does not work with scoped locales
# see https://github.com/plataformatec/devise/issues/2813
devise_for :users, skip: [:session, :password, :registration, :confirmation], controllers: { omniauth_callbacks: 'omniauth_callbacks' }
scope '(:locale)' do
# We define here a route inside the locale thats just saves the current locale in the session
get 'omniauth/:provider' => 'omniauth#localized', as: :localized_omniauth
devise_for :users, skip: :omniauth_callbacks, controllers: { passwords: 'passwords', registrations: 'registrations' }
end
end
omniauth_controller.rb
:
class OmniauthController < ApplicationController
def localized
# Just save the current locale in the session and redirect to the unscoped path as before
session[:omniauth_login_locale] = I18n.locale
redirect_to user_omniauth_authorize_path(params[:provider])
end
end
Now we can force the locle inside the omniauth_callbacks_controller.rb
:
class OmniauthCallbacksController < Devise::OmniauthCallbacksController
def twitter
handle_redirect('devise.twitter_uid', 'Twitter')
end
def facebook
handle_redirect('devise.facebook_data', 'Facebook')
end
private
def handle_redirect(_session_variable, kind)
# here we force the locale to the session locale so it siwtches to the correct locale
I18n.locale = session[:omniauth_login_locale] || I18n.default_locale
sign_in_and_redirect user, event: :authentication
set_flash_message(:notice, :success, kind: kind) if is_navigational_format?
end
def user
User.find_for_oauth(env['omniauth.auth'], current_user)
end
end
That's all, every time you login via link_to t('.sign_up_with_twitter'), localized_omniauth_path(:twitter)
, or whatever, it forces the intended locale.