mirror of
https://github.com/ryankazokas/turbovault-app.git
synced 2026-04-16 21:02:52 +00:00
67 lines
1.6 KiB
Ruby
67 lines
1.6 KiB
Ruby
module Authentication
|
|
extend ActiveSupport::Concern
|
|
|
|
included do
|
|
before_action :set_current_user
|
|
helper_method :current_user, :user_signed_in?
|
|
end
|
|
|
|
private
|
|
|
|
def current_user
|
|
@current_user ||= User.find_by(id: session[:user_id]) if session[:user_id]
|
|
end
|
|
|
|
def user_signed_in?
|
|
current_user.present?
|
|
end
|
|
|
|
def require_authentication
|
|
unless user_signed_in?
|
|
redirect_to login_path, alert: "You must be signed in to access this page."
|
|
end
|
|
end
|
|
|
|
def require_no_authentication
|
|
if user_signed_in?
|
|
redirect_to root_path, notice: "You are already signed in."
|
|
end
|
|
end
|
|
|
|
def sign_in(user)
|
|
reset_session
|
|
session[:user_id] = user.id
|
|
set_rls_user_id(user.id)
|
|
end
|
|
|
|
def sign_out
|
|
reset_session
|
|
@current_user = nil
|
|
clear_rls_user_id
|
|
end
|
|
|
|
def set_current_user
|
|
if current_user
|
|
set_rls_user_id(current_user.id)
|
|
else
|
|
clear_rls_user_id
|
|
end
|
|
end
|
|
|
|
def set_rls_user_id(user_id)
|
|
return unless ActiveRecord::Base.connection.adapter_name == "PostgreSQL"
|
|
ActiveRecord::Base.connection.execute("SET LOCAL app.current_user_id = #{ActiveRecord::Base.connection.quote(user_id)}")
|
|
rescue ActiveRecord::StatementInvalid => e
|
|
Rails.logger.warn("Failed to set RLS user_id: #{e.message}")
|
|
nil
|
|
end
|
|
|
|
def clear_rls_user_id
|
|
return unless ActiveRecord::Base.connection.adapter_name == "PostgreSQL"
|
|
ActiveRecord::Base.connection.execute("RESET app.current_user_id")
|
|
rescue ActiveRecord::StatementInvalid => e
|
|
Rails.logger.warn("Failed to clear RLS user_id: #{e.message}")
|
|
nil
|
|
end
|
|
end
|