updated context

This commit is contained in:
lnn0q 2025-03-23 21:27:14 +02:00
parent 04b606b7fa
commit 40c35bda13
7 changed files with 67 additions and 25 deletions

39
app/server/identity.ts Normal file
View file

@ -0,0 +1,39 @@
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<IdentityContext> {
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 };
}