brief-05-back/src/services/jwt.service.ts
Mathis 56bfd8cd0d
type: style
scope: services, interfaces

subject: Apply code formatting

- Correct indentation and formatting to match code style standards in multiple 'interfaces' and 'services' files.
- Also ensure lines at the end of the files.

Signed-off-by: Mathis <yidhra@tuta.io>
2024-04-30 10:55:37 +02:00

75 lines
1.8 KiB
TypeScript

import {
type JWTHeaderParameters,
type JWTPayload,
SignJWT,
jwtVerify,
} from "jose";
import { Logger } from "tslog";
const logger = new Logger({
name: "JwtService",
});
/**
* Verify a JWT token.
*
* @param {string | Uint8Array} jwt
* - The JWT token to verify.
* @returns {Promise<null | JWTPayload>}
* - The payload of the verified JWT token or null if verification fails.
*/
async function JwtVerifyService(
jwt: string | Uint8Array,
): Promise<null | JWTPayload> {
try {
const result = await jwtVerify(
jwt,
new TextEncoder().encode(`${process.env["JWT_SECRET"]}`),
{},
);
return result.payload;
} catch (error) {
logger.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<string>}
* - A promise that resolves with the signed JWT token.
*/
async function JwtSignService(
payload: JWTPayload,
pHeader: JWTHeaderParameters,
expTime: string | number | Date,
audience: string | string[],
): Promise<string> {
return await new SignJWT(payload)
.setProtectedHeader(pHeader)
.setIssuedAt(new Date())
.setIssuer(`${process.env["JWT_SECRET"]} - Mathis HERRIOT`)
.setAudience(audience)
.setExpirationTime(expTime)
.sign(
new TextEncoder().encode(`${process.env["JWT_SECRET"]}`),
);
}
const JwtService = {
verify: JwtVerifyService,
sign: JwtSignService,
};
export default JwtService;