mentorenwahl/docker/backend/src/backend/api/auth.cr
Dominic Grimm 5bc10f8aaf
Some checks failed
continuous-integration/drone/push Build is failing
Added worker
2022-01-23 09:12:57 +01:00

46 lines
1.1 KiB
Crystal

require "crystal-argon2"
require "jwt"
module Backend
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, SAFE_ENV["BACKEND_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, SAFE_ENV["BACKEND_JWT_SECRET"], JWT::Algorithm::HS256)[0]
end
def decode_jwt?(jwt : String) : JSON::Any?
decode_jwt(jwt)
rescue
nil
end
end
end
end