re-implemented JWT auth
This commit is contained in:
parent
c190d368de
commit
b47b0f3752
18 changed files with 390 additions and 174 deletions
51
app/server/express/auth/refreshToken.ts
Normal file
51
app/server/express/auth/refreshToken.ts
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
import { config } from '@app/server/main';
|
||||
import { prisma } from '@app/server/prisma/client';
|
||||
import { Session } from '@generated/types';
|
||||
import 'dotenv/config';
|
||||
import { Request, Response } from 'express';
|
||||
import jwt from 'jsonwebtoken';
|
||||
|
||||
export async function refreshTokenController(req: Request, res: Response) {
|
||||
try {
|
||||
const cookie: { jwt?: string | null } = req.cookies;
|
||||
|
||||
if (cookie == null || cookie.jwt == null) {
|
||||
res.sendStatus(401);
|
||||
return;
|
||||
}
|
||||
|
||||
const refreshToken = cookie.jwt;
|
||||
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { refreshToken },
|
||||
select: { id: true }
|
||||
});
|
||||
|
||||
if (user == null) {
|
||||
res.statusMessage = 'User not found.';
|
||||
res.status(401).end();
|
||||
return;
|
||||
}
|
||||
|
||||
const decoded = jwt.verify(refreshToken, config.refreshToken.secret) as {
|
||||
userId: string;
|
||||
iat: number;
|
||||
exp: number;
|
||||
};
|
||||
|
||||
if (user.id !== decoded.userId) {
|
||||
res.statusMessage = 'Invalid token.';
|
||||
res.status(401).end();
|
||||
return;
|
||||
}
|
||||
|
||||
const accessToken = jwt.sign({ userId: user.id }, config.accessToken.secret, {
|
||||
expiresIn: config.accessToken.expiresIn
|
||||
});
|
||||
|
||||
const session: Session = { accessToken };
|
||||
res.json(session);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue