module Authpwn::ControllerInstanceMethods

Included in controllers that call authenticates_using_session.

Public Instance Methods

bounce_user(redirect_url = request.url) click to toggle source

Inform the user that their request is forbidden.

If a user is logged on, this renders the session/forbidden view with a HTTP 403 code.

If no user is logged in, the user is redirected to session/new, and the current request's URL is saved in flash.

# File lib/authpwn_rails/session.rb, line 84
def bounce_user(redirect_url = request.url)
  # NOTE: this is tested in CookieControllerTest
  respond_to do |format|
    format.html do
      @redirect_url = redirect_url
      if current_user
        render 'session/forbidden', layout: false, status: :forbidden
      else
        flash[:auth_redirect_url] = redirect_url
        render 'session/forbidden', layout: false, status: :forbidden
      end
    end
    format.json do
      message = current_user ? "You're not allowed to access that" :
                               'Please sign in'
      render json: { error: message }
    end
  end
end
set_session_current_user(user) click to toggle source

Sets up the session so that it will authenticate the given user.

# File lib/authpwn_rails/session.rb, line 41
def set_session_current_user(user)
  self.current_user = user
  # Try to reuse existing sessions.
  if session[:authpwn_suid]
    token = Tokens::SessionUid.with_code(session[:authpwn_suid]).first
    if token
      if token.user == user
        token.touch
        return user
      else
        token.destroy
      end
    end
  end
  if user
    session[:authpwn_suid] = Tokens::SessionUid.random_for(user,
        request.remote_ip, request.user_agent || 'N/A').suid
  else
    session.delete :authpwn_suid
  end
end

Private Instance Methods

authenticate_using_session() click to toggle source

The before_action that implements authenticates_using_session.

If your ApplicationController contains authenticates_using_session, you can opt out in individual controllers using skip_before_action.

skip_before_action :authenticate_using_session
# File lib/authpwn_rails/session.rb, line 69
def authenticate_using_session
  return if current_user
  session_uid = session[:authpwn_suid]
  user = session_uid && Tokens::SessionUid.authenticate(session_uid)
  self.current_user = user if user && !user.instance_of?(Symbol)
end