dry refactor

This commit is contained in:
Ramnique Singh 2025-08-06 12:13:14 +05:30
parent 6adf1e8e42
commit 97fad8633f
3 changed files with 9 additions and 35 deletions

View file

@ -13,21 +13,23 @@ import { Project } from "../lib/types/project_types";
import { USE_AUTH } from "../lib/feature_flags";
import { authorizeUserAction } from "./billing_actions";
import { Workflow } from "../lib/types/workflow_types";
import { container } from "@/di/container";
import { IProjectActionAuthorizationPolicy } from "@/src/application/policies/project-action-authorization.policy";
const KLAVIS_API_KEY = process.env.KLAVIS_API_KEY || '';
const projectActionAuthorizationPolicy = container.resolve<IProjectActionAuthorizationPolicy>('projectActionAuthorizationPolicy');
export async function projectAuthCheck(projectId: string) {
if (!USE_AUTH) {
return;
}
const user = await authCheck();
const membership = await projectMembersCollection.findOne({
projectId,
await projectActionAuthorizationPolicy.authorize({
caller: 'user',
userId: user._id,
projectId,
});
if (!membership) {
throw new Error('User not a member of project');
}
}
async function createBaseProject(

View file

@ -1,28 +0,0 @@
import { NextRequest } from "next/server";
import { apiKeysCollection, projectsCollection } from "../../lib/mongodb";
export async function authCheck(projectId: string, req: NextRequest, handler: () => Promise<Response>): Promise<Response> {
const authHeader = req.headers.get('Authorization');
if (!authHeader?.startsWith('Bearer ')) {
return Response.json({ error: "Authorization header must be a Bearer token" }, { status: 400 });
}
const key = authHeader.split(' ')[1];
if (!key) {
return Response.json({ error: "Missing API key in request" }, { status: 400 });
}
// check if api key is valid
// while also updating last used timestamp
const result = await apiKeysCollection.findOneAndUpdate(
{
projectId,
key,
},
{ $set: { lastUsedAt: new Date().toISOString() } }
);
if (!result) {
return Response.json({ error: "Invalid API key" }, { status: 403 });
}
return await handler();
}

View file

@ -1,9 +1,9 @@
import { IProjectMembersRepository } from "@/src/application/repositories/project-members.repository.interface";
import { db } from "@/app/lib/mongodb";
import { projectMembersCollection } from "@/app/lib/mongodb";
export class MongoDBProjectMembersRepository implements IProjectMembersRepository {
async checkMembership(projectId: string, userId: string): Promise<boolean> {
const membership = await db.collection('project_members').findOne({
const membership = await projectMembersCollection.findOne({
projectId,
userId,
});