session/index.js

65 lines
1.3 KiB
JavaScript
Raw Normal View History

2020-09-24 19:56:01 +08:00
/**
* 会话模块
* @author yutent<yutent.io@gmail.com>
* @date 2020/09/24 11:18:23
*/
import { uuid, sha1 } from 'crypto.js'
import RedisStore from './lib/redis-store.js'
2020-09-25 18:32:00 +08:00
// 会话安装包
export const sessionPackage = {
2020-09-24 19:56:01 +08:00
name: 'session',
install() {
var session = this.get('session')
// 这里只创建session的存储器, 而初始化操作在中间件中进行
2020-10-06 10:43:28 +08:00
return new RedisStore(session)
2020-10-06 10:53:00 +08:00
}
2020-09-24 19:56:01 +08:00
}
// 会话中间件
2020-09-25 18:32:00 +08:00
export function sessionConnect(req, res, next) {
2020-09-24 19:56:01 +08:00
var opt = this.get('session')
2020-09-25 18:32:00 +08:00
var cache = req.cookie('NODESSID')
var deviceID = ''
2020-09-24 19:56:01 +08:00
var ssid
// options请求不处理会话
if (req.method === 'OPTIONS') {
return next()
}
2020-09-25 18:32:00 +08:00
// 校验UA
if (opt.level & 2) {
deviceID += req.header('user-agent')
}
2020-09-24 19:56:01 +08:00
2020-09-25 18:32:00 +08:00
// 校验IP
if (opt.level & 4) {
deviceID += req.ip()
}
2020-09-24 19:56:01 +08:00
2020-09-25 18:32:00 +08:00
if (deviceID) {
deviceID = sha1(deviceID)
2020-09-24 19:56:01 +08:00
2020-09-25 18:32:00 +08:00
// ssid 最后16位是指纹
if (cache) {
if (cache.slice(-16) === deviceID.slice(-16)) {
ssid = cache
} else {
ssid = uuid('') + deviceID.slice(-16)
2020-09-24 19:56:01 +08:00
}
}
2020-09-25 18:32:00 +08:00
} else {
ssid = cache || sha1(uuid())
2020-09-24 19:56:01 +08:00
}
2020-09-25 18:32:00 +08:00
res.cookie('NODESSID', ssid, { maxAge: opt.ttl, domain: opt.domain })
// 缓存ssid到req上
req.ssid = ssid
this.$$session.start(ssid)
2020-09-24 19:56:01 +08:00
next()
}