Initial commit

This commit is contained in:
2026-05-18 13:17:28 -04:00
committed by GitHub
commit 16fadfd529
91 changed files with 3321 additions and 0 deletions
View File
@@ -0,0 +1,33 @@
# this concern checks the token and finds the user
# if token is invalid or missing, we block the request
# usage: just add `before_action :authorize_request` in any controller you wanna protect
# I keep things simple, if you want to make it better it's you choice
module AuthorizeRequest
extend ActiveSupport::Concern
included do
before_action :authorize_request
end
private
def authorize_request
header = request.headers["Authorization"]
token = header.split(" ").last if header
begin
decoded = JsonWebToken.decode(token)
# check if token is blacklisted (logged out)
if BlacklistedToken.blacklisted?(decoded[:jti])
render json: { error: "Token has been revoked" }, status: :unauthorized
return
end
@current_user = User.find(decoded[:user_id])
rescue ActiveRecord::RecordNotFound, StandardError => e
render json: { error: "unauthorized: #{e.message}" }, status: :unauthorized
end
end
end
@@ -0,0 +1,29 @@
# this concern provides role-based authorization
# usage: add `before_action :require_admin` in controllers that need admin access
# or use `authorize_role!(:admin, :moderator)` to check multiple roles
module AuthorizeRole
extend ActiveSupport::Concern
private
# check if current user has any of the specified roles
def authorize_role!(*roles)
unless @current_user && roles.map(&:to_s).include?(@current_user.role)
render json: { error: "Forbidden: insufficient permissions" }, status: :forbidden
end
end
# helper methods for specific roles
def require_admin
authorize_role!(:admin)
end
def require_moderator
authorize_role!(:admin, :moderator)
end
def require_user
authorize_role!(:user, :moderator, :admin)
end
end