hrms-edm/Services/server/src/utils/auth.ts

48 lines
1.4 KiB
TypeScript
Raw Normal View History

2023-11-17 09:03:31 +07:00
import * as express from "express";
import { createVerifier } from "fast-jwt";
import HttpError from "../interfaces/http-error";
import HttpStatusCode from "../interfaces/http-status";
if (!process.env.PUBLIC_KEY && !process.env.REALM_URL) {
throw new Error("Require public key or realm url.");
}
const jwtVerify = createVerifier({
key: async () => {
return `-----BEGIN PUBLIC KEY-----\n${process.env.PUBLIC_KEY}\n-----END PUBLIC KEY-----`;
},
});
2023-11-27 09:45:30 +07:00
export async function expressAuthentication(
2023-11-17 09:03:31 +07:00
request: express.Request,
securityName: string,
2023-11-24 13:49:08 +07:00
scopes?: string[],
2023-11-17 09:03:31 +07:00
) {
2023-11-27 09:45:30 +07:00
if (process.env.AUTH_BYPASS) return { preferred_username: "bypassed" };
2023-11-17 09:03:31 +07:00
2023-11-27 09:45:30 +07:00
if (securityName !== "bearerAuth") throw new Error("Unknown authentication method.");
2023-11-17 09:03:31 +07:00
2023-11-27 09:45:30 +07:00
const token = request.headers["authorization"]?.includes("Bearer ")
? request.headers["authorization"].split(" ")[1]
: null;
2023-11-17 09:03:31 +07:00
2023-11-27 09:45:30 +07:00
if (!token) throw new HttpError(HttpStatusCode.UNAUTHORIZED, "No token provided.");
2023-11-17 09:03:31 +07:00
2023-11-27 09:45:30 +07:00
const payload = await jwtVerify(token).catch((_) => null);
2023-11-17 09:03:31 +07:00
2023-11-27 09:45:30 +07:00
if (!payload) {
throw new HttpError(HttpStatusCode.UNAUTHORIZED, "Invalid token provided.");
}
2023-11-24 13:49:08 +07:00
2023-11-29 17:18:08 +07:00
if (
scopes &&
scopes.length > 0 &&
scopes.some((v) => !payload.resource_access[payload.azp].roles.includes(v))
) {
2023-11-27 09:45:30 +07:00
throw new HttpError(HttpStatusCode.FORBIDDEN, "You are not allowed to perform this action.");
}
return payload;
2023-11-17 09:03:31 +07:00
}