mentorenwahl/backend/src/backend/api/auth.cr
Dominic Grimm 50379148bc
Some checks failed
continuous-integration/drone/push Build is failing
Update codebase
2022-10-31 09:47:26 +01:00

83 lines
2.2 KiB
Crystal

# Mentorenwahl: A fullstack application for assigning mentors to students based on their whishes.
# Copyright (C) 2022 Dominic Grimm
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
require "jwt"
require "json"
module Backend
module Api
# Authorization and authentication utilities
module Auth
extend self
# Bearer token header
BEARER = "Bearer "
# JWT token
struct Token
include JSON::Serializable
getter iss : String
getter iat : Int64
getter exp : Int64
getter jti : String
getter context : Context
def initialize(
@iss : String,
@iat : Int64,
@exp : Int64,
@jti : String,
@context : Context
)
end
def encode : String
JWT.encode(self, Backend.config.api.jwt_secret, JWT::Algorithm::HS256)
end
def self.from_hash(token : Hash(String, JSON::Any)) : self
self.new(
iss: token["iss"].as_s,
iat: token["iat"].as_i64,
exp: token["exp"].as_i64,
jti: token["jti"].as_s,
context: Context.from_hash(token["context"].as_h)
)
end
def self.decode(jwt : String) : self
self.from_hash(JWT.decode(jwt, Backend.config.api.jwt_secret, JWT::Algorithm::HS256)[0].as_h)
end
end
# JWT token context data
struct Context
include JSON::Serializable
getter user : Int32
def initialize(@user : Int32)
end
def self.from_hash(data : Hash(String, JSON::Any))
self.new(user: data["user"].as_i)
end
end
end
end
end