|
| 1 | +import { eq } from 'drizzle-orm'; |
| 2 | +import type { Request, Response } from 'express'; |
| 3 | +import { StatusCodes } from 'http-status-codes'; |
| 4 | + |
| 5 | +import { db, rooms } from '@/lib/db'; |
| 6 | + |
| 7 | +export async function authCheck(req: Request, res: Response) { |
| 8 | + const roomId = req.query.roomId as string | undefined; |
| 9 | + const userId = req.query.userId as string | undefined; |
| 10 | + |
| 11 | + if (!roomId || !userId) { |
| 12 | + return { |
| 13 | + code: StatusCodes.UNPROCESSABLE_ENTITY, |
| 14 | + error: { |
| 15 | + message: 'Malformed', |
| 16 | + }, |
| 17 | + }; |
| 18 | + } |
| 19 | + |
| 20 | + try { |
| 21 | + const room = await db.select().from(rooms).where(eq(rooms.roomId, roomId)).limit(1); |
| 22 | + |
| 23 | + if (room.length === 0) { |
| 24 | + return res.status(StatusCodes.NOT_FOUND).json({ |
| 25 | + error: { |
| 26 | + message: 'Room not found', |
| 27 | + }, |
| 28 | + }); |
| 29 | + } |
| 30 | + |
| 31 | + const { userId1, userId2 } = room[0]; |
| 32 | + |
| 33 | + if (userId !== userId1 && userId !== userId2) { |
| 34 | + return res.status(StatusCodes.FORBIDDEN).json({ |
| 35 | + code: StatusCodes.FORBIDDEN, |
| 36 | + error: { message: 'User is not authorized to access this room' }, |
| 37 | + }); |
| 38 | + } |
| 39 | + |
| 40 | + return res.status(StatusCodes.OK).json({ |
| 41 | + code: StatusCodes.OK, |
| 42 | + data: { roomId }, |
| 43 | + }); |
| 44 | + } catch (error) { |
| 45 | + console.error('Error authenticating room:', error); |
| 46 | + return res.status(StatusCodes.INTERNAL_SERVER_ERROR).json({ |
| 47 | + code: StatusCodes.INTERNAL_SERVER_ERROR, |
| 48 | + error: { message: 'An error occurred while authenticating the room' }, |
| 49 | + }); |
| 50 | + } |
| 51 | +} |
0 commit comments