brief-08-back/src/credentials/credentials.service.ts
Mathis b558d344e1
fix(credentials): handle token verification errors
Added try-catch block in verifyAuthToken to handle and log JWT verification errors. This change ensures that invalid tokens are caught and a relevant BadRequestException is thrown.
2024-07-24 20:26:53 +02:00

58 lines
1.6 KiB
TypeScript

import { BadRequestException, Injectable } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import * as argon from "argon2";
import * as jose from "jose";
import { JWTPayload, generateSecret } from "jose";
@Injectable()
export class CredentialsService {
constructor(private readonly configService: ConfigService) {}
async hash(plaintextPassword: string) {
console.log(plaintextPassword);
if (plaintextPassword.length < 6)
throw new BadRequestException("Password is not strong enough !");
return argon.hash(plaintextPassword, {
secret: Buffer.from(this.configService.get("APP_HASH_SECRET")),
});
}
async check(plaintextPassword: string, hashedPassword: string) {
return argon.verify(hashedPassword, plaintextPassword, {
secret: Buffer.from(this.configService.get("APP_HASH_SECRET")),
});
}
async verifyAuthToken(token: string) {
try {
const result = await jose.jwtVerify(
token,
Uint8Array.from(this.configService.get("APP_TOKEN_SECRET")),
{
audience: "auth:user",
issuer: "ShouldStick",
},
);
console.log(result);
return result;
} catch (error) {
console.log(error)
throw new BadRequestException("Invalid token");
}
}
async signAuthToken(payload: JWTPayload) {
console.log(this.configService.get("APP_TOKEN_SECRET"));
const token = new jose.SignJWT(payload)
.setProtectedHeader({ alg: "HS512", enc: "A128CBC-HS512" })
.setIssuedAt()
.setExpirationTime("3 day")
.setIssuer("ShouldStick")
.setAudience("auth:user");
console.log(token);
return await token.sign(
Uint8Array.from(this.configService.get("APP_TOKEN_SECRET")),
);
}
}