mentorenwahl/docker/api/src/api/auth.cr
Dominic Grimm a9fc6a43b1
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
Renamed backend to api
2022-01-20 21:17:24 +01:00

44 lines
1,017 B
Crystal

require "crystal-argon2"
require "jwt"
module API
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["API_JWT_SECRET"], JWT::Algorithm::HS256)
end
def create_user_jwt(user_id : Int, expiration : Int = (Time.utc + Time::Span.new(hours: 6)).to_unix) : String
create_jwt({user_id: user_id}, expiration)
end
def decode_jwt(jwt : String) : JSON::Any
JWT.decode(jwt, ENV_REQUESTER["API_JWT_SECRET"], JWT::Algorithm::HS256)[0]
end
def decode_jwt?(jwt : String) : JSON::Any?
decode_jwt(jwt)
rescue
nil
end
end
end