ln/app/server/identity.ts
lnn0q 6ada519e06 implemented identity, updated session, added 'workings' list
added paginated querying, added 'common'
2025-05-17 00:29:55 +03:00

64 lines
1.5 KiB
TypeScript

import { Session } from '@generated/types';
import 'dotenv/config';
import { Request, Response } from 'express';
import { GraphQLError } from 'graphql';
import jwt from 'jsonwebtoken';
import { config } from './main';
import { prisma } from './prisma/client';
export interface IdentityContext {
req: Request;
res: Response;
identity?: {
id: string;
email: string;
username: string;
};
}
export async function getIdentityContext({
req,
res
}: {
req: Request;
res: Response;
}): Promise<IdentityContext> {
try {
const authHeaders = req.headers.authorization;
if (authHeaders == null) return { req, res };
const session: Session = JSON.parse(authHeaders);
const { accessToken } = session;
const decoded = jwt.verify(accessToken, config.accessToken.secret) 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 { req, res, identity };
} catch (error) {
if (error instanceof Error)
throw new GraphQLError(error.message, {
extensions: {
code: 'UNAUTHENTICATED',
http: { status: 401 }
}
});
throw new GraphQLError(typeof error === 'string' ? error : 'Unknown error', {
extensions: {
code: 'UNAUTHENTICATED',
http: { status: 401 }
}
});
}
}