2020-05-13 11:46:52 +02:00
'use strict' ;
2020-05-13 12:27:46 +02:00
const crypto = require ( 'crypto' ) ;
2020-10-27 11:27:17 +01:00
const _ = require ( 'lodash' ) ;
2020-05-14 11:06:16 +02:00
const jwt = require ( 'jsonwebtoken' ) ;
2020-10-27 11:27:17 +01:00
2020-05-14 11:06:16 +02:00
const defaultJwtOptions = { expiresIn : '30d' } ;
const getTokenOptions = ( ) => {
2021-10-26 12:07:57 +02:00
const { options , secret } = strapi . config . get ( 'admin.auth' , { } ) ;
2020-05-14 11:06:16 +02:00
return {
secret ,
options : _ . merge ( defaultJwtOptions , options ) ,
} ;
} ;
2020-05-13 11:46:52 +02:00
2020-05-14 10:37:32 +02:00
/ * *
2020-05-14 11:06:16 +02:00
* Create a random token
2020-05-14 10:37:32 +02:00
* @ returns { string }
* /
2020-05-14 11:06:16 +02:00
const createToken = ( ) => {
2020-05-14 18:54:52 +02:00
return crypto . randomBytes ( 20 ) . toString ( 'hex' ) ;
2020-05-14 11:06:16 +02:00
} ;
/ * *
* Creates a JWT token for an administration user
* @ param { object } user - admin user
* /
2022-08-08 23:33:39 +02:00
const createJwtToken = ( user ) => {
2020-05-14 11:06:16 +02:00
const { options , secret } = getTokenOptions ( ) ;
return jwt . sign ( { id : user . id } , secret , options ) ;
} ;
/ * *
* Tries to decode a token an return its payload and if it is valid
* @ param { string } token - a token to decode
* @ return { Object } decodeInfo - the decoded info
* /
2022-08-08 23:33:39 +02:00
const decodeJwtToken = ( token ) => {
2020-05-14 11:06:16 +02:00
const { secret } = getTokenOptions ( ) ;
try {
const payload = jwt . verify ( token , secret ) ;
return { payload , isValid : true } ;
} catch ( err ) {
return { payload : null , isValid : false } ;
}
} ;
2020-05-14 10:37:32 +02:00
2022-01-24 18:13:27 +01:00
/ * *
* @ returns { void }
* /
const checkSecretIsDefined = ( ) => {
if ( strapi . config . serveAdminPanel && ! strapi . config . get ( 'admin.auth.secret' ) ) {
throw new Error (
2022-03-18 17:55:22 +01:00
` Missing auth.secret. Please set auth.secret in config/admin.js (ex: you can generate one using Node with \` crypto.randomBytes(16).toString('base64') \` ).
For security reasons , prefer storing the secret in an environment variable and read it in config / admin . js . See https : //docs.strapi.io/developer-docs/latest/setup-deployment-guides/configurations/optional/environment.html#configuration-using-environment-variables.`
2022-01-24 18:13:27 +01:00
) ;
}
} ;
2020-05-13 11:46:52 +02:00
module . exports = {
2020-05-14 11:06:16 +02:00
createToken ,
createJwtToken ,
getTokenOptions ,
decodeJwtToken ,
2022-01-24 18:13:27 +01:00
checkSecretIsDefined ,
2020-05-13 11:46:52 +02:00
} ;