| 8 | |
| 9 | // Returns the login user email or the client IP address |
| 10 | export const getEndUser = async (req: NextApiRequest, res: NextApiResponse): Promise<string> => { |
| 11 | // Get from server session if available |
| 12 | const serverSession = await getServerSession(req, res, authOptions); |
| 13 | if (serverSession?.user?.email) { |
| 14 | return serverSession.user.email; |
| 15 | } |
| 16 | |
| 17 | // Get from session token if available |
| 18 | const token = req.headers.authorization?.substring(7); |
| 19 | if (token) { |
| 20 | const sessionInDb = await prisma.session.findUnique({ |
| 21 | where: { sessionToken: token }, |
| 22 | }); |
| 23 | if (sessionInDb?.userId) { |
| 24 | const user = await prisma.user.findUnique({ |
| 25 | where: { id: sessionInDb.userId }, |
| 26 | }); |
| 27 | if (user?.email) { |
| 28 | return user.email; |
| 29 | } |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | // Get from client IP address |
| 34 | return requestIp.getClientIp(req) || ""; |
| 35 | }; |