Search code examples
ruby-on-railshttp-redirectomniauth-google-oauth2

OmniAuthGoogleOAuth2 in Rails 4 redirect to original request url after successful login


As per docs I implemented the authentication. Here is my application_controller.rb

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
  helper_method :current_user
  before_action :auth_user

  def current_user
    @current_user ||= User.find(session[:user_id]) if session[:user_id]
  end

  private
  def auth_user
    current_user
    if @current_user.nil?
      flash[:notice] = "You need to be logged in to access this part of the site"
      redirect_to root_path(url: request.url)
    end
  end
end

And I am using this "Sign In" Link

<%= link_to "Sign in with Google", "/auth/google_oauth2?url=#{@url}", id: "sign_in" %>

The route: get 'auth/:provider/callback', to: 'user_sessions#create'

The controller:

class UserSessionsController < ApplicationController
  skip_before_filter :auth_user
  def create
    url = params[:url]
    auth = env["omniauth.auth"]
    if auth
      user = User.from_omniauth(auth)
      session[:user_id] = user.id
      flash[:notice] = "Login Sucessful!"
      redirect_to url
    else
      flash[:notice] = "error"
      redirect_to root_path
    end

  end

  def destroy
    session[:user_id] = nil
    redirect_to root_path
  end
end

Now when I without a valid session try to go to localhost:3000/privileged I get redirected to the root URL and the login link is this:

http://localhost:3000/auth/google_oauth2?url=http://localhost:3000/privileged

However when I click it, I get a successful login but then an error that I cannot redirect to nil. Why is the parameter dropped? Or is there a better way to redirect the user to the originally requested URL after a successful login in general?


Solution

  • It works when I changed the url parmaeter in the link to ?origin=... and in the controller I can then access it via url = request.env['omniauth.origin']. This makes the redirect_to url statement work