WIP on dev-moritz
This commit is contained in:
81
src/lib/middleware/authorization.ts
Normal file
81
src/lib/middleware/authorization.ts
Normal file
@@ -0,0 +1,81 @@
|
||||
import { decodeToken } from "#lib/auth/token.js";
|
||||
import { hashPassword } from "#lib/password.js";
|
||||
import { prisma } from "@ibcornelsen/database/server";
|
||||
import { APIError, TypesafeAPIContextWithRequest } from "astro-typesafe-api/server";
|
||||
|
||||
export async function authorizationMiddleware(input: any, context: TypesafeAPIContextWithRequest<any>) {
|
||||
const authorization: string | undefined = context.request.headers.get("Authorization");
|
||||
|
||||
if (!context.request.headers.has("Authorization") || !authorization) {
|
||||
throw new APIError({
|
||||
code: "BAD_REQUEST",
|
||||
message: "Request is missing an 'Authorization' header."
|
||||
})
|
||||
}
|
||||
|
||||
if (authorization.startsWith("Basic")) {
|
||||
const payload = btoa(authorization.split(" ")[1]).split(":");
|
||||
|
||||
if (payload.length !== 2) {
|
||||
throw new APIError({
|
||||
code: "BAD_REQUEST",
|
||||
message: "Malformed 'Authorization' header."
|
||||
})
|
||||
}
|
||||
|
||||
const [email, password] = payload;
|
||||
|
||||
const user = await prisma.benutzer.findUnique({
|
||||
where: {
|
||||
email
|
||||
}
|
||||
})
|
||||
|
||||
if (!user || user.passwort !== hashPassword(password)) {
|
||||
throw new APIError({
|
||||
code: "UNAUTHORIZED",
|
||||
message: "Unknown combination of email and password."
|
||||
})
|
||||
}
|
||||
|
||||
return user;
|
||||
} else if (authorization.startsWith("Bearer")) {
|
||||
const token = authorization.split(" ")[1]
|
||||
|
||||
if (!token) {
|
||||
throw new APIError({
|
||||
code: "BAD_REQUEST",
|
||||
message: "Malformed 'Authorization' header."
|
||||
})
|
||||
}
|
||||
|
||||
const payload = decodeToken(token)
|
||||
|
||||
if ((payload.exp || 0) < Date.now()) {
|
||||
throw new APIError({
|
||||
code: "UNAUTHORIZED",
|
||||
message: "Access Token has expired."
|
||||
})
|
||||
}
|
||||
|
||||
const user = await prisma.benutzer.findUnique({
|
||||
where: {
|
||||
uid: payload.uid
|
||||
}
|
||||
})
|
||||
|
||||
if (!user) {
|
||||
throw new APIError({
|
||||
code: "UNAUTHORIZED",
|
||||
message: "Invalid Bearer Token."
|
||||
})
|
||||
}
|
||||
|
||||
return user;
|
||||
}
|
||||
|
||||
throw new APIError({
|
||||
code: "BAD_REQUEST",
|
||||
message: "Invalid authorization method in 'Authorization' header."
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user