Module: Hanko::Rails::Authentication

Extended by:
ActiveSupport::Concern
Defined in:
lib/hanko/rails/authentication.rb

Overview

Controller concern that provides Hanko authentication helpers.

Include this module in your ApplicationController to gain access to session inspection methods and a before-action guard.

Examples:

Include in ApplicationController

class ApplicationController < ActionController::Base
  include Hanko::Rails::Authentication
  before_action :authenticate_hanko_user!
end

Instance Method Summary collapse

Instance Method Details

#authenticate_hanko_user!void

This method returns an undefined value.

Halts the request with an unauthorized response unless the user is authenticated.

For HTML requests, redirects to the root path with an alert. For JSON and other formats, responds with HTTP 401 Unauthorized.



58
59
60
61
62
63
64
65
66
# File 'lib/hanko/rails/authentication.rb', line 58

def authenticate_hanko_user!
  return if hanko_authenticated?

  respond_to do |format|
    format.html { redirect_to('/', alert: 'You must be logged in') }
    format.json { head(:unauthorized) }
    format.any { head(:unauthorized) }
  end
end

#current_hanko_userString?

Returns the current Hanko user identifier.

Returns:

  • (String, nil)

    the user ID, or nil if unauthenticated



48
49
50
# File 'lib/hanko/rails/authentication.rb', line 48

def current_hanko_user
  hanko_user_id
end

#hanko_authenticated?Boolean

Checks whether the current request has a valid Hanko session.

Returns:

  • (Boolean)

    true if authenticated, false otherwise



41
42
43
# File 'lib/hanko/rails/authentication.rb', line 41

def hanko_authenticated?
  !hanko_session.nil?
end

#hanko_sessionHash?

Returns the decoded Hanko session payload from the verified JWT.

Returns:

  • (Hash, nil)

    the decoded JWT claims, or nil if unauthenticated



27
28
29
# File 'lib/hanko/rails/authentication.rb', line 27

def hanko_session
  request.env['hanko.session']
end

#hanko_user_idString?

Returns the Hanko user ID (+sub+ claim) from the session.

Returns:

  • (String, nil)

    the user ID, or nil if unauthenticated



34
35
36
# File 'lib/hanko/rails/authentication.rb', line 34

def hanko_user_id
  hanko_session&.dig('sub')
end