re-implemented JWT auth

This commit is contained in:
lnn0q 2025-04-18 14:47:42 +03:00
parent c190d368de
commit b47b0f3752
18 changed files with 390 additions and 174 deletions

View file

@ -1,8 +1,10 @@
import { Session } from '@generated/types';
import 'dotenv/config';
import { Request, Response } from 'express';
import jwt from 'jsonwebtoken';
import { config } from './main';
import { prisma } from './prisma/client';
import { Session } from '@generated/types';
import { GraphQLError } from 'graphql';
export interface IdentityContext {
req: Request;
@ -20,38 +22,42 @@ export async function getIdentityContext({
req: Request;
res: Response;
}): Promise<IdentityContext> {
const authHeaders = req.headers.authorization;
if (authHeaders == null) return { req, res };
try {
const authHeaders = req.headers.authorization;
if (authHeaders == null) return { req, res };
const session: Session = JSON.parse(authHeaders);
const { accessToken } = session;
const session: Session = JSON.parse(authHeaders);
const { accessToken } = session;
const accessTokenSecret = process.env.ACCESS_TOKEN_SECRET;
if (accessTokenSecret == null) throw new Error('No `accessToken`.');
const decoded = jwt.verify(accessToken, config.accessToken.secret) as {
userId: string;
iat: number;
exp: number;
};
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 { req, res, identity };
}
/* throw new GraphQLError('User is not authenticated', {
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 }
}
}); */
// throw new GraphQLError(`${error}`);
});
}
}