refactor: handle authentication state in middleware

This commit is contained in:
Elias Schneider
2023-02-04 18:12:49 +01:00
parent 064ef38d78
commit 4e840ecd29
17 changed files with 511 additions and 474 deletions

View File

@@ -120,7 +120,7 @@ export class AuthController {
const accessToken = await this.authService.refreshAccessToken(
request.cookies.refresh_token
);
response.cookie("access_token", accessToken);
response = this.addTokensToResponse(response, undefined, accessToken);
return new TokenDTO().from({ accessToken });
}
@@ -162,11 +162,13 @@ export class AuthController {
refreshToken?: string,
accessToken?: string
) {
if (accessToken) response.cookie("access_token", accessToken);
if (accessToken)
response.cookie("access_token", accessToken, { sameSite: "lax" });
if (refreshToken)
response.cookie("refresh_token", refreshToken, {
path: "/api/auth/token",
httpOnly: true,
sameSite: "strict",
maxAge: 1000 * 60 * 60 * 24 * 30 * 3,
});

View File

@@ -110,26 +110,30 @@ export class AuthService {
{
sub: user.id,
email: user.email,
isAdmin: user.isAdmin,
refreshTokenId,
},
{
expiresIn: "15min",
expiresIn: "10s",
secret: this.config.get("JWT_SECRET"),
}
);
}
async signOut(accessToken: string) {
const { refreshTokenId } = this.jwtService.decode(accessToken) as {
refreshTokenId: string;
};
const { refreshTokenId } =
(this.jwtService.decode(accessToken) as {
refreshTokenId: string;
}) || {};
await this.prisma.refreshToken
.delete({ where: { id: refreshTokenId } })
.catch((e) => {
// Ignore error if refresh token doesn't exist
if (e.code != "P2025") throw e;
});
if (refreshTokenId) {
await this.prisma.refreshToken
.delete({ where: { id: refreshTokenId } })
.catch((e) => {
// Ignore error if refresh token doesn't exist
if (e.code != "P2025") throw e;
});
}
}
async refreshAccessToken(refreshToken: string) {