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,29 +3,26 @@ import { createUser, getUser } from "./user.service";
import { CreateUserInput } from "./user.schema";
export async function createUserHandler(
req: FastifyRequest<{
Body: CreateUserInput;
}>,
req: FastifyRequest,
res: FastifyReply
) {
const body = req.body;
const body = req.body as CreateUserInput;
try {
const user = await createUser(body);
const authUser = req.user;
const user = await createUser(body, authUser.tenantId);
return res.code(201).send(user);
} catch (err) {
return err;
}
}
export async function getUserHandler(
req: FastifyRequest<{ Params: { userId: string } }>,
res: FastifyReply
) {
const { userId } = req.params;
export async function getUserHandler(req: FastifyRequest, res: FastifyReply) {
const { userId } = req.params as { userId: string };
try {
const user = await getUser(userId);
const authUser = req.user;
const user = await getUser(userId, authUser.tenantId);
if (user == null)
return res.code(404).send({ error: "resource not found" });

View File

@@ -12,6 +12,8 @@ export default async function userRoutes(fastify: FastifyInstance) {
201: $user("createUserResponse"),
},
},
config: { requiredClaims: ["user:write"] },
preHandler: [fastify.authorize],
},
createUserHandler
);
@@ -24,6 +26,8 @@ export default async function userRoutes(fastify: FastifyInstance) {
200: $user("createUserResponse"),
},
},
config: { requiredClaims: ["user:read"] },
preHandler: [fastify.authorize],
},
getUserHandler
);

View File

@@ -5,16 +5,21 @@ import { z } from "zod";
export const userModel = mongoose.model(
"user",
new mongoose.Schema({
tenantId: String,
tenantId: {
type: String,
required: true,
},
pid: {
type: String,
unique: true,
required: true,
},
firstName: String,
lastName: String,
email: {
type: String,
unique: true,
required: true,
},
avatar: String,
status: String,

View File

@@ -1,9 +1,9 @@
import { generateId } from "../utils/id";
import { CreateUserInput, userModel } from "./user.schema";
export async function createUser(input: CreateUserInput) {
export async function createUser(input: CreateUserInput, tenantId: string) {
const user = await userModel.create({
tenantId: "abc",
tenantId: tenantId,
pid: generateId(),
createdAt: new Date(),
...input,
@@ -12,7 +12,9 @@ export async function createUser(input: CreateUserInput) {
return user;
}
export async function getUser(userId: string) {
const user = await userModel.findOne({ pid: userId });
export async function getUser(userId: string, tenantId: string) {
const user = await userModel.findOne({
$and: [{ tenantId: tenantId }, { pid: userId }],
});
return user;
}