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;