For my Users Controller, I'd like to always load in the user as the @user instance variable. This is done by loading in the user from an external authorization link with a callback.
Here is a minimal example:
class UsersController < ApplicationController
before_action :authorize_user
skip_before_action(:authorize_user, { :only => [:auth_callback] })
# this is my before action meant to load in the @user instance variable
def authorize_user
# if user is not stored in session, get authorization from external link
if !session.key?(:user_hash)
redirect_to(external_auth_link)
# otherwise, loads user from hash
else
user_hash = session[:user_hash]
@user = get_user_from_hash(user_hash)
end
end
# this is the callback from the external authorization link
def auth_callback
user = get_user_from_callback()
session[:user_hash] = user.to_hash
# the line in question
# should I redirect here or what?
end
def page1
# some page using the @user instance variable
render({:template => "users/page1.html.erb"})
end
def page2
# another page using the @user instance variable
render({:template => "users/page2.html.erb"})
end
end
When calling page1 or page2, I'd like the before_action to properly load in the @user instance variable, then return to the appropriate method.
Currently, the before_action works fine when user_hash is already stored in session.
However, when user_hash is not saved in session, it redirects the the external authorization, then goes to the callback, then doesn't know where to go after. It wants me to redirect or render something. How could I get it to redirect to the action (page1 or page2) that was originally called?
Ex: If I call page1 when user_hash is not stored in session it will go to:
- authorize_user
- The external authorization
- auth_callback
- page1
I've tried to remove the code unrelated to this issue, but let me know if anything else would be helpful. Thanks for any suggestions.