Initial commit: Lageplan v1.0 - Next.js 15.5, React 19
This commit is contained in:
44
src/lib/tenant.ts
Normal file
44
src/lib/tenant.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import { prisma } from './db'
|
||||
import { UserPayload } from './auth'
|
||||
|
||||
/**
|
||||
* Get the tenantId filter for data queries.
|
||||
* - SERVER_ADMIN: no filter (sees everything)
|
||||
* - All others: filter by their tenantId
|
||||
*/
|
||||
export function getTenantFilter(user: UserPayload): Record<string, any> {
|
||||
if (user.role === 'SERVER_ADMIN') return {}
|
||||
if (!user.tenantId) return { ownerId: user.id } // no tenant → only own projects
|
||||
// Tenant user: see tenant projects + own legacy projects (tenantId=null)
|
||||
return {
|
||||
OR: [
|
||||
{ tenantId: user.tenantId },
|
||||
{ ownerId: user.id, tenantId: null },
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a user has access to a specific project.
|
||||
* Returns the project if access is granted, null otherwise.
|
||||
*/
|
||||
export async function getProjectWithTenantCheck(projectId: string, user: UserPayload) {
|
||||
const project = await (prisma as any).project.findUnique({
|
||||
where: { id: projectId },
|
||||
})
|
||||
if (!project) return null
|
||||
|
||||
// SERVER_ADMIN can access all projects
|
||||
if (user.role === 'SERVER_ADMIN') return project
|
||||
|
||||
// Projects without tenantId (legacy): allow if user is the owner
|
||||
if (!project.tenantId) {
|
||||
if (project.ownerId === user.id) return project
|
||||
return null
|
||||
}
|
||||
|
||||
// All others: must belong to same tenant
|
||||
if (project.tenantId !== user.tenantId) return null
|
||||
|
||||
return project
|
||||
}
|
||||
Reference in New Issue
Block a user