wo-base-webtoken/webtoken.js
2022-08-06 11:53:45 +08:00

46 lines
1.1 KiB
JavaScript

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