Added token authentication, organization module. Moved server bootstrapping code to server.ts file
This commit is contained in:
26
src/auth.ts
Normal file
26
src/auth.ts
Normal 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>,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user