token refresh

This commit is contained in:
Julian Krauser 2024-08-23 14:42:47 +02:00
parent bcfba8b448
commit 55caf69bf0
4 changed files with 102 additions and 8 deletions

View file

@ -1,6 +1,6 @@
import { Request, Response } from "express";
import { JWTHelper } from "../helpers/jwtHelper";
import { JWTToken } from "../type/jwtTypes";
import { JWTData, JWTToken } from "../type/jwtTypes";
import InternalException from "../exceptions/internalException";
import RefreshCommandHandler from "../command/refreshCommandHandler";
import { CreateRefreshCommand } from "../command/refreshCommand";
@ -10,6 +10,8 @@ import UnauthorizedRequestException from "../exceptions/unauthorizedRequestExcep
import QRCode from "qrcode";
import { CreateUserCommand } from "../command/userCommand";
import UserCommandHandler from "../command/userCommandHandler";
import RefreshService from "../service/refreshService";
import BadRequestException from "../exceptions/badRequestException";
/**
* @description Check authentication status by token
@ -80,6 +82,51 @@ export async function logout(req: Request, res: Response): Promise<any> {}
export async function refresh(req: Request, res: Response): Promise<any> {
let token = req.body.token;
let refresh = req.body.refresh;
const tokenUser = await JWTHelper.decode(token);
if (typeof tokenUser == "string" || !tokenUser) {
throw new InternalException("process failed");
}
let tokenUserId = (tokenUser as JWTToken).userId;
let { user } = await RefreshService.getByToken(refresh);
if (tokenUserId != user.id) {
throw new UnauthorizedRequestException("user not identified with token and refresh");
}
let { id, username } = await UserService.getById(tokenUserId);
let jwtData: JWTToken = {
userId: id,
username: username,
rights: [],
};
let accessToken: string;
let refreshToken: string;
JWTHelper.create(jwtData)
.then((result) => {
accessToken = result;
})
.catch((err) => {
console.log(err);
throw new InternalException("Failed accessToken creation");
});
let refreshCommand: CreateRefreshCommand = {
userId: id,
};
refreshToken = await RefreshCommandHandler.create(refreshCommand);
await RefreshCommandHandler.deleteByToken(refresh);
res.json({
accessToken,
refreshToken,
});
}
/**