Skip to content

Instantly share code, notes, and snippets.

@artofhuman
Forked from adhrinae/authentication.rb
Created January 27, 2017 17:36
Show Gist options
  • Save artofhuman/a9f938911448ef20befe54bdff653b6a to your computer and use it in GitHub Desktop.
Save artofhuman/a9f938911448ef20befe54bdff653b6a 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