Skip to content

Instantly share code, notes, and snippets.

@adhrinae
Last active March 18, 2022 09:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save adhrinae/c9554cfa277604cdfe99e81f41940feb to your computer and use it in GitHub Desktop.
Save adhrinae/c9554cfa277604cdfe99e81f41940feb to your computer and use it in GitHub Desktop.
Hanami User Authentication with session
# web/controllers/authentication.rb
module Web
module Authentication
module Skip
def authenticate!
end
end
def self.included(action)
action.class_eval do
before :authenticate!
expose :current_user
end
end
private
def authenticate!
unauthorized! unless authenticated?
end
def authenticated?
!current_user.nil? && !session_expired?
end
def session_expired?
# in case :expire_after would be nil, convert into Integer
Time.now.to_i > session[:expire_after].to_i
end
def current_user
@current_user ||= UserRepository.new.find(session[:user_id])
end
def unauthorized!
session[:user_id] = nil
flash[:error] = 'Auth error, Please Log in again.'
self.status = 401
redirect_to routes.login_path
end
end
end
# web/controllers/session/create.rb
module Web::Controllers::Sessions
class Create
include Web::Action
include Web::Authentication::Skip
params do
required(:sessions).schema do
required(:login_id).filled(:str?)
required(:login_pw).filled(:str?)
end
end
def call(params)
unauthorized! unless params.valid?
login_id = params[:sessions][:login_id]
login_pw = params[:sessions][:login_pw]
credential = LoginCredentialRepository.new.
by_id_and_type(login_id, LoginCredentialType::User)
if credential && credential.valid_password?(login_pw)
user = credential.target
set_session(user)
redirect_to '/asp/main'
else
unauthorized!
end
end
private
def unauthorized!
flash[:error] = 'Failed to Auth, Please check you username or password.'
self.status = 401
end
def set_session(asp_user)
session[:user_id] = user.id
session[:expire_after] = Time.now + (3600 * 3) # expire after 3 hours
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment