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

@@ -2,28 +2,24 @@ import { FastifyRequest, FastifyReply } from "fastify";
import { CreateOrgInput } from "./organization.schema";
import { createOrg, getOrg } from "./organization.service";
export async function createOrgHandler(
req: FastifyRequest<{ Body: CreateOrgInput }>,
res: FastifyReply
) {
const input = req.body;
export async function createOrgHandler(req: FastifyRequest, res: FastifyReply) {
const input = req.body as CreateOrgInput;
try {
const org = await createOrg(input);
const authUser = req.user;
const org = await createOrg(input, authUser.tenantId);
return res.code(201).send(org);
} catch (err) {
return err;
}
}
export async function getOrgHandler(
req: FastifyRequest<{ Params: { orgId: string } }>,
res: FastifyReply
) {
const { orgId } = req.params;
export async function getOrgHandler(req: FastifyRequest, res: FastifyReply) {
const { orgId } = req.params as { orgId: string };
try {
const org = await getOrg(orgId);
const authUser = req.user;
const org = await getOrg(orgId, authUser.tenantId);
if (org === null)
return res.code(404).send({ error: "resource not found" });

View File

@@ -12,6 +12,8 @@ export default function organizationRoutes(fastify: FastifyInstance) {
201: $org("createOrgResponse"),
},
},
config: { requiredClaims: ["org:write"] },
preHandler: [fastify.authorize],
},
createOrgHandler
);
@@ -27,6 +29,7 @@ export default function organizationRoutes(fastify: FastifyInstance) {
},
},
},
config: { requiredClaims: ["org:read"] },
},
getOrgHandler
);

View File

@@ -5,7 +5,10 @@ import { z } from "zod";
export const orgModel = mongoose.model(
"organization",
new mongoose.Schema({
tenantId: String,
tenantId: {
type: String,
required: true,
},
pid: {
type: String,
unique: true,
@@ -13,7 +16,6 @@ export const orgModel = mongoose.model(
name: String,
domain: {
type: String,
unique: true,
},
avatar: String,
type: String,

View File

@@ -1,9 +1,9 @@
import { generateId } from "../utils/id";
import { CreateOrgInput, orgModel } from "./organization.schema";
export async function createOrg(input: CreateOrgInput) {
export async function createOrg(input: CreateOrgInput, tenantId: string) {
const org = await orgModel.create({
tenantId: "abc",
tenantId: tenantId,
pid: generateId(),
createdAt: new Date(),
...input,
@@ -12,6 +12,8 @@ export async function createOrg(input: CreateOrgInput) {
return org;
}
export async function getOrg(orgId: string) {
return await orgModel.findOne({ pid: orgId });
export async function getOrg(orgId: string, tenantId: string) {
return await orgModel.findOne({
$and: [{ tenantId: tenantId }, { pid: orgId }],
});
}