This commit is contained in:
陆柯 2022-08-06 11:53:45 +08:00
parent df2db84fa8
commit a5e6d8112c

View File

@ -2,13 +2,16 @@ const JsonWebToken = require('jsonwebtoken')
const crypto = require('crypto')
const my = {}
const my = { envar: typeof wo !== 'undefined' ? wo.envar : globalThis.envar || {} }
module.exports = {
init (envar) {
my.tokenKey = envar.tokenKey
my.envar = envar
},
createToken (content, key) {
createToken (content, key = my.envar.tokenKey) {
if (!key) {
console.warn('*** tokenkey is empty! ***')
}
// content 可以是数字,非空字符串或非空对象,不可以是数组。
// key 可以未定义,则默认设为空字符串,再转化为哈希。(jsonwebtoken 要求 key 必须有值)
try {
@ -16,20 +19,23 @@ module.exports = {
content,
crypto
.createHash('sha256')
.update(key || my.tokenKey || wo.envar.tokenKey || '', 'utf8')
.update(key || '', 'utf8')
.digest('hex')
)
} catch (exp) {
return null
}
},
verifyToken (token, key) {
verifyToken (token, key = my.envar.tokenKey) {
if (!key) {
console.warn('*** tokenkey is empty! ***')
}
try {
return JsonWebToken.verify(
token,
crypto
.createHash('sha256')
.update(key || my.tokenKey || wo.envar.tokenKey || '', 'utf8')
.update(key || '', 'utf8')
.digest('hex')
)
} catch (exp) {