Add authorization

This commit is contained in:
2024-12-20 13:17:53 +05:30
parent 4b49c43a0c
commit a584fc91b5
16 changed files with 112 additions and 58 deletions

View File

@@ -3,24 +3,22 @@ import { CreateTokenInput } from "./token.schema";
import { createToken, getToken } from "./token.service";
export async function createTokenHandler(
req: FastifyRequest<{ Body: CreateTokenInput }>,
req: FastifyRequest,
res: FastifyReply
) {
const input = req.body;
const input = req.body as CreateTokenInput;
try {
const result = await createToken(input);
const authUser = req.user;
const result = await createToken(input, authUser.tenantId);
return res.code(201).send(result);
} catch (err) {
return err;
}
}
export async function getTokenHandler(
req: FastifyRequest<{ Params: { tokenId: string } }>,
res: FastifyReply
) {
const { tokenId } = req.params;
export async function getTokenHandler(req: FastifyRequest, res: FastifyReply) {
const { tokenId } = req.params as { tokenId: string };
try {
const token = await getToken(tokenId);

View File

@@ -12,13 +12,19 @@ export async function tokenRoutes(fastify: FastifyInstance) {
201: $token("createTokenResponse"),
},
},
config: { requiredClaims: ["token:write"] },
preHandler: [fastify.authorize],
},
createTokenHandler
);
fastify.get(
"/:tokenId",
{ schema: { response: { 200: $token("getTokenResponse") } } },
{
schema: { response: { 200: $token("getTokenResponse") } },
config: { requiredClaims: ["token:read"] },
preHandler: [fastify.authorize],
},
getTokenHandler
);
}

View File

@@ -1,12 +1,14 @@
import { buildJsonSchemas } from "fastify-zod";
import mongoose from "mongoose";
import { z } from "zod";
import { Claim } from "../utils/claims";
export const tokenModel = mongoose.model(
"token",
new mongoose.Schema({
tenantId: String,
tenantId: {
type: String,
required: true,
},
pid: {
type: String,
unique: true,

View File

@@ -2,12 +2,13 @@ import bcrypt from "bcrypt";
import { generateId, generateToken } from "../utils/id";
import { CreateTokenInput, tokenModel } from "./token.schema";
export async function createToken(input: CreateTokenInput) {
export async function createToken(input: CreateTokenInput, tenantId: string) {
const tokenId = generateId();
const newToken = await generateToken();
const tokenHash = await bcrypt.hash(newToken, 10);
const tokenInDb = await tokenModel.create({
tenantId: tenantId,
pid: tokenId,
hash: tokenHash,
createdAt: new Date(),