34 lines
1.3 KiB
JavaScript
34 lines
1.3 KiB
JavaScript
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
|
||
}
|
||
}
|