60 lines
1.8 KiB
TypeScript
60 lines
1.8 KiB
TypeScript
import Jose, {type JWTHeaderParameters, type 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 | 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 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 |