Added token authentication, organization module. Moved server bootstrapping code to server.ts file

This commit is contained in:
2024-12-19 21:49:54 +05:30
parent 970a972b11
commit 4b49c43a0c
16 changed files with 652 additions and 22 deletions

26
src/auth.ts Normal file
View File

@@ -0,0 +1,26 @@
import bcrypt from "bcrypt";
import { FastifyReply, FastifyRequest } from "fastify";
import { getToken } from "./tokens/token.service";
import { Claim } from "./utils/claims";
export type AuthenticatedUser = {
userId?: String;
claims: Array<Claim>;
};
export async function authHandler(req: FastifyRequest, res: FastifyReply) {
if (!req.headers.authorization) return res.code(401).send();
const [tokenId, token] = req.headers.authorization.split(" ")[1].split(".");
if (!tokenId || !token) return res.code(401).send({ error: "invalid token" });
const tokenInDb = await getToken(tokenId);
if (tokenInDb === null) return res.code(401).send({ error: "invalid token" });
const valid = await bcrypt.compare(token, tokenInDb.hash);
if (!valid) return res.code(401).send({ error: "invalid token" });
req.user = {
claims: tokenInDb.claims as Array<Claim>,
};
}