86 lines
1.8 KiB
JavaScript
86 lines
1.8 KiB
JavaScript
/**
|
|
* 会话模块
|
|
* @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'
|
|
|
|
const DEFAULT_CONFIG = {
|
|
ttl: 3600 * 24 * 7,
|
|
domain: '', // NODESSID域, 默认等于domain
|
|
level: 0, // 校验级别, 0: 不校验客户端, 2: ua, 4: ip, 6: ua + ip
|
|
db: {
|
|
host: '127.0.0.1',
|
|
port: 6379,
|
|
db: 0
|
|
}
|
|
}
|
|
|
|
// 会话安装包
|
|
export const SessionModule = {
|
|
name: 'session',
|
|
install(conf = {}) {
|
|
if (!conf.domain) {
|
|
throw new Error('Please make sure to set the `domain` field')
|
|
}
|
|
let session = Object.assign({}, DEFAULT_CONFIG, conf)
|
|
this.set({ session })
|
|
// 这里只创建session的存储器, 而初始化操作在中间件中进行
|
|
return new RedisStore(session)
|
|
}
|
|
}
|
|
|
|
// 会话中间件
|
|
export function createSession() {
|
|
return function (req, res, next) {
|
|
let opt = this.get('session')
|
|
let cache = req.cookie('NODESSID')
|
|
let deviceID = ''
|
|
let ssid
|
|
|
|
// options请求不处理会话
|
|
if (req.method === 'OPTIONS') {
|
|
return next()
|
|
}
|
|
|
|
// 校验UA
|
|
if (opt.level & 2) {
|
|
deviceID += req.header('user-agent')
|
|
}
|
|
|
|
// 校验IP
|
|
if (opt.level & 4) {
|
|
deviceID += req.ip()
|
|
}
|
|
|
|
if (deviceID) {
|
|
deviceID = sha1(deviceID)
|
|
|
|
// ssid 最后16位是指纹
|
|
if (cache) {
|
|
if (cache.slice(-16) === deviceID.slice(-16)) {
|
|
ssid = cache
|
|
} else {
|
|
ssid = uuid('') + deviceID.slice(-16)
|
|
}
|
|
}
|
|
} else {
|
|
ssid = cache || sha1(uuid())
|
|
}
|
|
|
|
res.cookie('NODESSID', ssid, {
|
|
maxAge: opt.ttl,
|
|
httpOnly: true,
|
|
domain: opt.domain
|
|
})
|
|
// 缓存ssid到req上
|
|
req.ssid = ssid
|
|
this.$$session.update(ssid)
|
|
|
|
next()
|
|
}
|
|
}
|