wo-base-webtoken/index.js
2020-06-01 16:26:32 +08:00

34 lines
1.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const JsonWebToken = require('jsonwebtoken')
const crypto = require('crypto')
module.exports={
createToken: function(content, key) { // content 可以是数字,字符串或对象,不可以是数组。
key=key||(wo&&wo.Config&&wo.Config.tokenKey?wo.Config.tokenKey:'') // key或wo.Config.tokenKey其中之一必须存在
if (content && !Array.isArray(content) && typeof(key)==='string' && key.length>0){ // 注意jwt.sign(null|'') 会出错。但 sign(0)可以的。
try{
return JsonWebToken.sign(content, crypto.createHash('sha256').update(key, 'utf8').digest('hex'))
}catch(exp){
return null
}
}
return null
}
,
verifyToken: function(token, key) {
key=key||(wo&&wo.Config&&wo.Config.tokenKey?wo.Config.tokenKey:'') // key或wo.Config.tokenKey其中之一必须存在
if (token && typeof token==='string' && typeof(key)==='string' && key.length>0) {
try{
token=JsonWebToken.verify(token, crypto.createHash('sha256').update(key, 'utf8').digest('hex'))
}catch(exp){
return null
}
if (Date.now() - Date.parse(token.whenStamp) > 2*60*60*1000) { // 每过2小时核对一遍密码
}
return token
}
return null
}
}