import 'dotenv/config'; import { Request, Response } from 'express'; import jwt from 'jsonwebtoken'; import { prisma } from './prisma/client'; export interface IdentityContext { identity?: { id: string; username: string; }; } export async function getIdentityContext({ req, res }: { req: Request; res: Response; }): Promise { const authHeader = req.headers.authorization; if (authHeader == null) return {}; const token = authHeader.split(' ')[1]; const accessTokenSecret = process.env.ACCESS_TOKEN_SECRET; if (accessTokenSecret == null) throw new Error('No `accessToken`.'); const decoded = jwt.verify(token, accessTokenSecret) as { userId: string }; const identity = await prisma.user.findUnique({ where: { id: decoded.userId }, select: { id: true, email: true, username: true } }); if (identity == null) throw new Error("Couldn't find the user."); return { identity }; }