44 lines
1,023 B
Crystal
44 lines
1,023 B
Crystal
require "crystal-argon2"
|
|
require "jwt"
|
|
|
|
module MW
|
|
module Auth
|
|
extend self
|
|
|
|
BEARER = "Bearer "
|
|
|
|
def hash_password(password : String) : String
|
|
Argon2::Password.create(password)
|
|
end
|
|
|
|
def verify_password?(password : String, hash : String) : Bool
|
|
!!Argon2::Password.verify_password(password, hash)
|
|
rescue
|
|
false
|
|
end
|
|
|
|
private def create_jwt(data, expiration : Int) : String
|
|
payload = {
|
|
"data" => data.to_h,
|
|
"exp" => expiration,
|
|
}
|
|
|
|
JWT.encode(payload.to_h, ENV_REQUESTER["BACKEND_JWT_SECRET"], JWT::Algorithm::HS256)
|
|
end
|
|
|
|
def create_user_jwt(user_id : Int, expiration : Int = (Time.utc + Time::Span.new(days: 1)).to_unix) : String
|
|
create_jwt({user_id: user_id}, expiration)
|
|
end
|
|
|
|
def decode_jwt(jwt : String) : JSON::Any
|
|
JWT.decode(jwt, ENV_REQUESTER["BACKEND_JWT_SECRET"], JWT::Algorithm::HS256)[0]
|
|
end
|
|
|
|
def decode_jwt?(jwt : String) : JSON::Any?
|
|
decode_jwt(jwt)
|
|
rescue
|
|
nil
|
|
end
|
|
end
|
|
end
|