From 2eda06f087bd9c839e12377223356af0c6bc850b Mon Sep 17 00:00:00 2001 From: Mathis Date: Wed, 15 May 2024 12:00:40 +0200 Subject: [PATCH] feat(authentication): add JWT service for sign and verify operations This commit includes a new JWT service for handling JWT signing and verification. It leverages utility functions for logging and environment variable handling. The signed JWT tokens cater to protected header parameters and adjustable expiration times. Moreover, this service supports JWT verification with transparent handling of verification failures. --- src/services/authentication/jwt.service.ts | 74 ++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 src/services/authentication/jwt.service.ts diff --git a/src/services/authentication/jwt.service.ts b/src/services/authentication/jwt.service.ts new file mode 100644 index 0000000..6acf8c0 --- /dev/null +++ b/src/services/authentication/jwt.service.ts @@ -0,0 +1,74 @@ +import { + type JWTHeaderParameters, + type JWTPayload, + SignJWT, + jwtVerify, +} from "jose"; +import {LogsUtils} from "@utils/logs.util"; +import {EnvUtils} from "@utils/env.util"; + +const logs = new LogsUtils('JwtService') +const envs = new EnvUtils('JwtService') + +/** + * Verify a JWT token. + * + * @param {string | Uint8Array} jwt + * - The JWT token to verify. + * @returns {Promise} + * - The payload of the verified JWT token or null if verification fails. + */ +async function JwtVerifyService( + jwt: string | Uint8Array, +): Promise { + try { + const result = await jwtVerify( + jwt, + new TextEncoder().encode(`${envs.get('JWT_SECRET')}`), + {}, + ); + return result.payload; + } catch (error) { + logs.error(error); + return null; + } +} + +/** + * Asynchronously signs a JWT token using the provided payload, header, expiration time, and audience. + * + * @param {JWTPayload} payload + * - The payload data to include in the JWT token. + * @param {JWTHeaderParameters} pHeader + * - The protected header parameters for the JWT token. + * @param {string | number | Date} expTime + * - The expiration time for the JWT token. (Can be expressed with '1d', '1mo'...) + * @param {string | string[]} audience + * - The intended audience for the JWT token. + * + * @returns {Promise} + * - A promise that resolves with the signed JWT token. + */ +async function JwtSignService( + payload: JWTPayload, + pHeader: JWTHeaderParameters, + expTime: string | number | Date, + audience: string | string[], +): Promise { + return await new SignJWT(payload) + .setProtectedHeader(pHeader) + .setIssuedAt(new Date()) + .setIssuer(`OnlyDevs`) + .setAudience(audience) + .setExpirationTime(expTime) + .sign(new TextEncoder().encode(`${envs.get('JWT_SECRET')}`)); +} + +logs.debug("Service loaded."); + +const JwtService = { + verify: JwtVerifyService, + sign: JwtSignService, +}; + +export default JwtService;