mentorenwahl/backend/src/backend/api/auth.cr
Dominic Grimm 860ae7ed5e
All checks were successful
continuous-integration/drone/push Build is passing
Rewrite frontend in rust with yew
2022-11-04 21:23:36 +01:00

87 lines
2.3 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"
require "uuid"
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 vrs : String
getter iat : Int64
getter exp : Int64
getter jti : UUID
getter context : Context
def initialize(
@iss : String,
@vrs : String,
@iat : Int64,
@exp : Int64,
@jti : UUID,
@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,
vrs: token["vrs"].as_s,
iat: token["iat"].as_i64,
exp: token["exp"].as_i64,
jti: UUID.new(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