session/index.js

94 lines
1.9 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 Store from './lib/redis-store.js'
2020-09-24 19:56:01 +08:00
2023-11-01 15:47:53 +08:00
const DEFAULT_CONFIG = {
ttl: 3600 * 24 * 7,
domain: '', // NODESSID域
2023-11-01 15:47:53 +08:00
level: 0, // 校验级别, 0: 不校验客户端, 2: ua, 4: ip, 6: ua + ip
2025-01-02 18:37:40 +08:00
secret: 'it_is_secret_key', // jwt密钥, 使用时请修改
2023-11-01 15:47:53 +08:00
db: {
host: '127.0.0.1',
port: 6379,
db: 0
}
}
2023-10-27 19:18:04 +08:00
function sessionMiddleware(req, res, next) {
let opt = this.get('session')
let cache = req.cookie('NODESSID')
let deviceID = ''
let ssid
// options请求不处理会话
if (req.method === 'OPTIONS') {
return next()
2020-10-06 10:53:00 +08:00
}
2020-09-24 19:56:01 +08:00
// 校验UA
if (opt.level & 2) {
deviceID += req.header('user-agent')
}
2023-11-01 15:47:53 +08:00
// 校验IP
if (opt.level & 4) {
deviceID += req.ip()
}
2023-11-01 15:47:53 +08:00
if (deviceID) {
deviceID = sha1(deviceID)
2023-11-01 15:47:53 +08:00
// ssid 最后16位是指纹
if (cache) {
if (cache.slice(-16) === deviceID.slice(-16)) {
ssid = cache
} else {
ssid = uuid('') + deviceID.slice(-16)
}
2023-10-27 19:18:04 +08:00
}
} else {
ssid = cache || sha1(uuid())
}
2023-11-01 15:47:53 +08:00
res.cookie('NODESSID', ssid, {
maxAge: opt.ttl,
httpOnly: true,
domain: opt.domain
})
// 缓存ssid到req上
req.ssid = ssid
this.$$session.update(ssid)
2023-11-01 15:47:53 +08:00
next()
}
// 会话中间件
export function createSession() {
return {
name: 'session',
install(conf = {}) {
if (!conf.secret) {
console.warn(
new Error(
'You must set a `secret` key for session, or it will use the default key.'
)
)
2020-09-24 19:56:01 +08:00
}
let session = Object.assign({}, DEFAULT_CONFIG, conf)
this.set({ session })
2023-11-01 15:47:53 +08:00
// 注册中间件
this.use(sessionMiddleware)
2023-11-01 15:47:53 +08:00
// 这里只创建session的存储器, 而初始化操作在中间件中进行
return new Store(session)
}
2020-09-24 19:56:01 +08:00
}
}