|
1
|
import jwt, { type Secret, type SignOptions } from "jsonwebtoken" |
|
2
|
import { MedusaError } from "../common" |
|
3
|
|
|
4
|
export const generateJwtToken = ( |
|
5
|
tokenPayload: Record<string, unknown>, |
|
6
|
jwtConfig: { |
|
7
|
secret?: Secret |
|
8
|
expiresIn?: number | string |
|
9
|
jwtOptions?: SignOptions |
|
10
|
} |
|
11
|
) => { |
|
12
|
if ( |
|
13
|
!jwtConfig.secret || |
|
14
|
(!jwtConfig.expiresIn && !jwtConfig.jwtOptions?.expiresIn) |
|
15
|
) { |
|
16
|
throw new MedusaError( |
|
17
|
MedusaError.Types.INVALID_ARGUMENT, |
|
18
|
"JWT secret and expiresIn must be provided when generating a token" |
|
19
|
) |
|
20
|
} |
|
21
|
|
|
22
|
const expiresIn = jwtConfig.expiresIn ?? jwtConfig.jwtOptions?.expiresIn |
|
23
|
return jwt.sign(tokenPayload, jwtConfig.secret, { |
|
24
|
...jwtConfig.jwtOptions, |
|
25
|
expiresIn, |
|
26
|
}) |
|
27
|
} |