Add authorization
This commit is contained in:
43
src/auth.ts
43
src/auth.ts
@@ -4,10 +4,25 @@ import { getToken } from "./tokens/token.service";
|
||||
import { Claim } from "./utils/claims";
|
||||
|
||||
export type AuthenticatedUser = {
|
||||
userId?: String;
|
||||
userId?: string;
|
||||
tenantId: string;
|
||||
claims: Array<Claim>;
|
||||
};
|
||||
|
||||
declare module "fastify" {
|
||||
export interface FastifyRequest {
|
||||
user: AuthenticatedUser;
|
||||
}
|
||||
|
||||
export interface FastifyInstance {
|
||||
authorize: (req: FastifyRequest, res: FastifyReply) => Promise<unknown>;
|
||||
}
|
||||
|
||||
export interface FastifyContextConfig {
|
||||
requiredClaims: Claim[];
|
||||
}
|
||||
}
|
||||
|
||||
export async function authHandler(req: FastifyRequest, res: FastifyReply) {
|
||||
if (!req.headers.authorization) return res.code(401).send();
|
||||
|
||||
@@ -21,6 +36,32 @@ export async function authHandler(req: FastifyRequest, res: FastifyReply) {
|
||||
if (!valid) return res.code(401).send({ error: "invalid token" });
|
||||
|
||||
req.user = {
|
||||
tenantId: tokenInDb.tenantId,
|
||||
claims: tokenInDb.claims as Array<Claim>,
|
||||
};
|
||||
}
|
||||
|
||||
export function hasValidClaims(
|
||||
user: AuthenticatedUser,
|
||||
requiredClaims: Claim[]
|
||||
): boolean {
|
||||
let isValid = true;
|
||||
|
||||
for (const claim of requiredClaims) {
|
||||
if (!user.claims.includes(claim)) {
|
||||
isValid = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return isValid;
|
||||
}
|
||||
|
||||
export async function authorize(req: FastifyRequest, res: FastifyReply) {
|
||||
const { requiredClaims } = req.routeOptions.config;
|
||||
const authUser = req.user;
|
||||
if (!hasValidClaims(authUser, requiredClaims))
|
||||
return res
|
||||
.code(401)
|
||||
.send({ error: "Missing permissions", params: requiredClaims });
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user