From cac7d4cfd3986735258c1d754399ccd384701b29 Mon Sep 17 00:00:00 2001 From: Mathis Date: Tue, 9 Jul 2024 15:06:37 +0200 Subject: [PATCH] feat(credentials): add new Credentials service and module Introduce the Credentials service which is responsible for hashing and verifying passwords. Added appropriate methods within the service and provided it in a new Credentials module. The module exports the service to allow its use in other parts of the application. --- src/credentials/credentials.module.ts | 10 ++++++++++ src/credentials/credentials.service.ts | 24 ++++++++++++++++++++++++ 2 files changed, 34 insertions(+) create mode 100644 src/credentials/credentials.module.ts create mode 100644 src/credentials/credentials.service.ts diff --git a/src/credentials/credentials.module.ts b/src/credentials/credentials.module.ts new file mode 100644 index 0000000..d655932 --- /dev/null +++ b/src/credentials/credentials.module.ts @@ -0,0 +1,10 @@ +import { Module } from "@nestjs/common"; +import { CredentialsService } from "./credentials.service"; +import { ConfigModule } from "@nestjs/config"; + +@Module({ + imports: [ConfigModule], + providers: [CredentialsService], + exports: [CredentialsService] +}) +export class CredentialsModule {} diff --git a/src/credentials/credentials.service.ts b/src/credentials/credentials.service.ts new file mode 100644 index 0000000..6c25230 --- /dev/null +++ b/src/credentials/credentials.service.ts @@ -0,0 +1,24 @@ +import { BadRequestException, Injectable } from "@nestjs/common"; +import * as argon from "argon2"; +// biome-ignore lint/style/useImportType: used by Next.js +import { ConfigService } from "@nestjs/config"; + +@Injectable() +export class CredentialsService { + + constructor(private configService: ConfigService) { + } + + async hash(plaintextPassword: string) { + if (plaintextPassword.length < 6) throw new BadRequestException("Password is not strong enough !") + return argon.hash(Buffer.from(plaintextPassword), { + secret: this.configService.get("APP_HASH_SECRET"), + }) + } + + async check(plaintextPassword: string, hashedPassword: string) { + return argon.verify(hashedPassword, Buffer.from(plaintextPassword), { + secret: this.configService.get("APP_HASH_SECRET"), + }) + } +}