feat: 🚀 Jwt Service

This commit is contained in:
Mathis H (Avnyr) 2024-04-23 13:44:13 +02:00
parent ddd9a2fef4
commit db40b772f1
Signed by: Mathis
GPG Key ID: DD9E0666A747D126

View File

@ -0,0 +1,60 @@
import Jose, {JWTHeaderParameters, JWTPayload} 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 | object>}
* - The payload of the verified JWT token or null if verification fails.
*/
async function JwtVerifyService(jwt: string | Uint8Array): Promise<null | object> {
try {
const result = await Jose.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 Jose.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