This commit is contained in:
Luk Lu
2022-03-23 09:22:50 +08:00
parent abc9b9f4e7
commit 4c807cf458
2 changed files with 1 additions and 0 deletions

39
webtoken.js Normal file
View File

@@ -0,0 +1,39 @@
const JsonWebToken = require('jsonwebtoken')
const crypto = require('crypto')
const my = {}
module.exports = {
init (envi) {
my.tokenKey = envi.tokenKey
},
createToken: function (content, key) {
// content 可以是数字,非空字符串或非空对象,不可以是数组。
// key 可以未定义,则默认设为空字符串,再转化为哈希。(jsonwebtoken 要求 key 必须有值)
try {
return JsonWebToken.sign(
content,
crypto
.createHash('sha256')
.update(key || my.tokenKey || wo.envi.tokenKey || '', 'utf8')
.digest('hex')
)
} catch (exp) {
return null
}
},
verifyToken: function (token, key) {
try {
return JsonWebToken.verify(
token,
crypto
.createHash('sha256')
.update(key || my.tokenKey || wo.envi.tokenKey || '', 'utf8')
.digest('hex')
)
} catch (exp) {
return null
}
},
}