Spaces:
Sleeping
Sleeping
Download src/lib/api.ts from shahzaib24681012/teamsync: direct link, hf CLI and curl.
- Browser
- Download file 5.93 kB
-
https://huggingface.co/spaces/shahzaib24681012/teamsync/resolve/main/src/lib/api.ts
- Command line
-
hf download hf://spaces/shahzaib24681012/teamsync/src/lib/api.ts
-
curl -L -o api.ts https://huggingface.co/spaces/shahzaib24681012/teamsync/resolve/main/src/lib/api.ts
5.93 kB
| /** | |
| * Route handler helpers: auth guard, workspace membership resolution, | |
| * uniform error responses, and simple in-memory rate limiting. | |
| */ | |
| import { NextRequest, NextResponse } from 'next/server'; | |
| import { Role, User, WorkspaceMember } from '@prisma/client'; | |
| import { prisma } from './db'; | |
| import { getAuthUserId } from './auth'; | |
| import { atLeast } from './rbac'; | |
| export class ApiError extends Error { | |
| status: number; | |
| constructor(status: number, message: string) { | |
| super(message); | |
| this.status = status; | |
| } | |
| } | |
| export function jsonError(status: number, message: string) { | |
| return NextResponse.json({ error: message }, { status }); | |
| } | |
| type Handler<C> = (req: NextRequest, ctx: C) => Promise<NextResponse | Response>; | |
| /** Wrap a handler: catches ApiError and unexpected failures. */ | |
| export function handler<C = { params: Record<string, string> }>(fn: Handler<C>): Handler<C> { | |
| return async (req, ctx) => { | |
| try { | |
| return await fn(req, ctx); | |
| } catch (e) { | |
| if (e instanceof ApiError) return jsonError(e.status, e.message); | |
| console.error('[api]', req.method, req.nextUrl.pathname, e); | |
| // in development, surface the real error to the client to speed up debugging | |
| if (process.env.NODE_ENV === 'development' && e instanceof Error) { | |
| return jsonError(500, `${e.name}: ${e.message.slice(0, 500)}`); | |
| } | |
| return jsonError(500, 'Internal server error'); | |
| } | |
| }; | |
| } | |
| export async function requireUser(): Promise<User> { | |
| const uid = getAuthUserId(); | |
| if (!uid) throw new ApiError(401, 'Not authenticated'); | |
| const user = await prisma.user.findUnique({ where: { id: uid } }); | |
| if (!user) throw new ApiError(401, 'Not authenticated'); | |
| return user; | |
| } | |
| /** Resolve the caller's membership in a workspace (403 if not a member). */ | |
| export async function requireMember(workspaceId: string, minRole: Role = 'EMPLOYEE'): Promise<{ user: User; member: WorkspaceMember }> { | |
| const user = await requireUser(); | |
| const member = await prisma.workspaceMember.findUnique({ | |
| where: { workspaceId_userId: { workspaceId, userId: user.id } }, | |
| }); | |
| if (!member || !member.isActive) throw new ApiError(403, 'Not a member of this workspace'); | |
| if (!atLeast(member.role, minRole)) throw new ApiError(403, 'Insufficient permissions'); | |
| return { user, member }; | |
| } | |
| /** Caller must be a member of the channel (and channel must exist). */ | |
| export async function requireChannelMember(channelId: string) { | |
| const user = await requireUser(); | |
| const channel = await prisma.channel.findUnique({ where: { id: channelId } }); | |
| if (!channel) throw new ApiError(404, 'Channel not found'); | |
| const cm = await prisma.channelMember.findUnique({ | |
| where: { channelId_userId: { channelId, userId: user.id } }, | |
| }); | |
| if (!cm) { | |
| // public channels are readable by workspace members | |
| const wm = await prisma.workspaceMember.findUnique({ | |
| where: { workspaceId_userId: { workspaceId: channel.workspaceId, userId: user.id } }, | |
| }); | |
| if (!wm || channel.isPrivate) throw new ApiError(403, 'Not a member of this channel'); | |
| return { user, channel, channelMember: null, workspaceMember: wm }; | |
| } | |
| const wm = await prisma.workspaceMember.findUnique({ | |
| where: { workspaceId_userId: { workspaceId: channel.workspaceId, userId: user.id } }, | |
| }); | |
| if (!wm) throw new ApiError(403, 'Not a member of this workspace'); | |
| return { user, channel, channelMember: cm, workspaceMember: wm }; | |
| } | |
| export async function requireConversationMember(conversationId: string) { | |
| const user = await requireUser(); | |
| const convo = await prisma.conversation.findUnique({ | |
| where: { id: conversationId }, | |
| include: { members: true }, | |
| }); | |
| if (!convo) throw new ApiError(404, 'Conversation not found'); | |
| const me = convo.members.find((m) => m.userId === user.id); | |
| if (!me) throw new ApiError(403, 'Not a member of this conversation'); | |
| return { user, conversation: convo }; | |
| } | |
| /** Board access: workspace members can use open boards; private boards need membership. */ | |
| export async function requireBoardAccess(boardId: string, opts: { allowArchived?: boolean } = {}) { | |
| const user = await requireUser(); | |
| const board = await prisma.board.findUnique({ where: { id: boardId }, include: { members: true } }); | |
| if (!board || (board.isArchived && !opts.allowArchived)) throw new ApiError(404, 'Board not found'); | |
| const wm = await prisma.workspaceMember.findUnique({ | |
| where: { workspaceId_userId: { workspaceId: board.workspaceId, userId: user.id } }, | |
| }); | |
| if (!wm || !wm.isActive) throw new ApiError(403, 'Not a member of this workspace'); | |
| const boardMember = board.members.find((m) => m.userId === user.id); | |
| if (board.isPrivate && !boardMember) throw new ApiError(403, 'This board is private'); | |
| return { user, board, workspaceMember: wm, isBoardAdmin: boardMember?.isAdmin || ['ADMIN', 'OWNER'].includes(wm.role) }; | |
| } | |
| export async function readBody<T>(req: NextRequest): Promise<T> { | |
| try { | |
| return (await req.json()) as T; | |
| } catch { | |
| throw new ApiError(400, 'Invalid JSON body'); | |
| } | |
| } | |
| export function required<T>(v: T | null | undefined, name: string): T { | |
| if (v === null || v === undefined || (typeof v === 'string' && v.trim() === '')) { | |
| throw new ApiError(400, `Missing required field: ${name}`); | |
| } | |
| return v; | |
| } | |
| // ---- simple fixed-window rate limiter (per-process; swap for Redis at scale) ---- | |
| const buckets = new Map<string, { count: number; resetAt: number }>(); | |
| export function rateLimit(key: string, limit: number, windowMs: number) { | |
| const now = Date.now(); | |
| const b = buckets.get(key); | |
| if (!b || b.resetAt < now) { | |
| buckets.set(key, { count: 1, resetAt: now + windowMs }); | |
| return; | |
| } | |
| b.count++; | |
| if (b.count > limit) throw new ApiError(429, 'Too many requests. Try again shortly.'); | |
| } | |
| export function clientIp(req: NextRequest): string { | |
| return req.headers.get('x-forwarded-for')?.split(',')[0]?.trim() || 'local'; | |
| } | |