47 lines
1.1 KiB
TypeScript
47 lines
1.1 KiB
TypeScript
import 'dotenv/config';
|
|
import { Request, Response } from 'express';
|
|
import jwt from 'jsonwebtoken';
|
|
import { prisma } from './prisma/client';
|
|
import { Session } from '@generated/types';
|
|
|
|
export interface IdentityContext {
|
|
identity?: {
|
|
id: string;
|
|
username: string;
|
|
};
|
|
}
|
|
|
|
export async function getIdentityContext({
|
|
req,
|
|
res
|
|
}: {
|
|
req: Request;
|
|
res: Response;
|
|
}): Promise<IdentityContext> {
|
|
const authHeaders = req.headers.authorization;
|
|
if (authHeaders == null) return {};
|
|
|
|
const session: Session = JSON.parse(authHeaders);
|
|
console.log(session);
|
|
const accessToken = session.accessToken;
|
|
|
|
const accessTokenSecret = process.env.ACCESS_TOKEN_SECRET;
|
|
if (accessTokenSecret == null) throw new Error('No `accessToken`.');
|
|
|
|
const decoded = jwt.verify(accessToken, accessTokenSecret) as {
|
|
userId: string;
|
|
iat: number;
|
|
exp: number;
|
|
};
|
|
|
|
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 };
|
|
}
|