| 1 | import { and, eq, sql } from 'drizzle-orm' |
| 2 | import { db } |
| 3 | import { |
| 4 | members, |
| 5 | organizations, |
| 6 | projectClientAssignments, |
| 7 | projectMemberAssignments, |
| 8 | projects, |
| 9 | } from '@/server/db/schema' |
| 10 | |
| 11 | const ORG_ACCESS_CACHE_KEY = ' |
| 12 | const PROJECT_ACCESS_CACHE_KEY = ' |
| 13 | |
| 14 | const checkProjectAccess = async |
| 15 | organizationId: string, |
| 16 | projectId: string, |
| 17 | currentUserId: string |
| 18 | ) => { |
| 19 | // Verify org exists and project belongs to it in one query |
| 20 | const [project] |
| 21 | .select({ id: |
| 22 | .from(projects) |
| 23 | .innerJoin(organizations, |
| 24 | .where( |
| 25 | and( |
| 26 | eq(projects.id |
| 27 | eq(projects.organizationId |
| 28 | ) |
| 29 | ) |
| 30 | |
| 31 | if (!project) |
| 32 | return { success: |
| 33 | } |
| 34 | |
| 35 | // Get the member record for the current user in this org |
| 36 | const [member] |
| 37 | .select({ id: |
| 38 | .from(members) |
| 39 | .where( |
| 40 | and( |
| 41 | eq(members.organizationId |
| 42 | eq(members.userId |
| 43 | ) |
| 44 | ) |
| 45 | |
| 46 | if (!member) |
| 47 | return { |
| 48 | success: false, |
| 49 | error: 'User is not a member of this organization', |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | // Admins and owners have access to all projects |
| 54 | if (member.role |
| 55 | return { success: |
| 56 | } |
| 57 | |
| 58 | // Check if user is assigned as a project member or client in a single query |
| 59 | const [assignment] |
| 60 | .select({ found: |
| 61 | .from(projectMemberAssignments) |
| 62 | .where( |
| 63 | and( |
| 64 | eq(projectMemberAssignments.projectId |
| 65 | eq(projectMemberAssignments.memberId |
| 66 | ) |
| 67 | ) |
| 68 | .union( |
| 69 | db |
| 70 | .select({ found: |
| 71 | .from(projectClientAssignments) |
| 72 | .where( |
| 73 | and( |
| 74 | eq(projectClientAssignments.projectId |
| 75 | eq(projectClientAssignments.memberId |
| 76 | ) |
| 77 | ) |
| 78 | ) |
| 79 | .limit(1) |
| 80 | |
| 81 | if (assignment) { |
| 82 | return { success: |
| 83 | } |
| 84 | |
| 85 | return { |
| 86 | success: false, |
| 87 | error: 'User does not have access to project', |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | export const authService = |
| 92 | checkProjectAccess, |
| 93 | ORG_ACCESS_CACHE_KEY, |
| 94 | PROJECT_ACCESS_CACHE_KEY, |
| 95 | } |