Compare commits

...

5 Commits
v1 ... master

Author SHA1 Message Date
yutent 4673b541a6 调整session的调用方式;增加index.d.ts 2025-01-03 15:34:42 +08:00
yutent ebccbf270f update 2025-01-02 18:37:40 +08:00
yutent 4b5dd61525 更新readme 2023-11-01 15:48:48 +08:00
yutent 6e6e97467d 重构2.0 2023-11-01 15:47:53 +08:00
yutent 7cba707799 重构2.0 2023-10-27 19:18:04 +08:00
5 changed files with 122 additions and 40 deletions

View File

@ -1,4 +1,6 @@
![module info](https://nodei.co/npm/@gm5/session.png?downloads=true&downloadRank=true&stars=true)
![downloads](https://img.shields.io/npm/dt/@gm5/session.svg)
![version](https://img.shields.io/npm/v/@gm5/session.svg)
# @gm5/session # @gm5/session
@ -7,17 +9,20 @@
## 安装 ## 安装
```bash ```bash
npm install @gm5/session npm i @gm5/session
``` ```
## 使用 ## 使用
```js ```js
import { sessionPackage, sessionConnect } from '@gm5/session' import { createApp } from '@gm5/core
import { createSession, SessionModule } from '@gm5/session'
app.install(sessionPackage) const app = createApp()
app.use(sessionConnect) app.install(SessionModule, {domain: 'your_domain'})
.use(createSession)
.run()
``` ```

38
index.d.ts vendored Normal file
View File

@ -0,0 +1,38 @@
/**
* {}
* @author yutent<yutent.io@gmail.com>
* @date 2025/01/03 10:39:13
*/
declare interface RedisConfig {
host: string
port: number
db: number
}
declare interface SessionConfig {
ttl?: number
domain?: string
level?: 0 | 2 | 4 | 6
secret: string
db: RedisConfig
}
declare class Store {
update(ssid: string): void
get(ssid: string, key?: string): Promise<string | object>
set(ssid: string, key: string, val: string): void
unset(ssid: string, key: string): void
clear(ssid: string): void
}
declare interface Session {
name: 'session'
install(conf?: SessionConfig): Store
}
export function createSession(): Session

View File

@ -6,24 +6,25 @@
import { uuid, sha1 } from 'crypto.js' import { uuid, sha1 } from 'crypto.js'
import RedisStore from './lib/redis-store.js' import Store from './lib/redis-store.js'
// 会话安装包 const DEFAULT_CONFIG = {
export const sessionPackage = { ttl: 3600 * 24 * 7,
name: 'session', domain: '', // NODESSID域
install() { level: 0, // 校验级别, 0: 不校验客户端, 2: ua, 4: ip, 6: ua + ip
var session = this.get('session') secret: 'it_is_secret_key', // jwt密钥, 使用时请修改
// 这里只创建session的存储器, 而初始化操作在中间件中进行 db: {
return new RedisStore(session) host: '127.0.0.1',
port: 6379,
db: 0
} }
} }
// 会话中间件 function sessionMiddleware(req, res, next) {
export function sessionConnect(req, res, next) { let opt = this.get('session')
var opt = this.get('session') let cache = req.cookie('NODESSID')
var cache = req.cookie('NODESSID') let deviceID = ''
var deviceID = '' let ssid
var ssid
// options请求不处理会话 // options请求不处理会话
if (req.method === 'OPTIONS') { if (req.method === 'OPTIONS') {
@ -55,10 +56,38 @@ export function sessionConnect(req, res, next) {
ssid = cache || sha1(uuid()) ssid = cache || sha1(uuid())
} }
res.cookie('NODESSID', ssid, { maxAge: opt.ttl, domain: opt.domain }) res.cookie('NODESSID', ssid, {
maxAge: opt.ttl,
httpOnly: true,
domain: opt.domain
})
// 缓存ssid到req上 // 缓存ssid到req上
req.ssid = ssid req.ssid = ssid
this.$$session.start(ssid) this.$$session.update(ssid)
next() 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.'
)
)
}
let session = Object.assign({}, DEFAULT_CONFIG, conf)
this.set({ session })
// 注册中间件
this.use(sessionMiddleware)
// 这里只创建session的存储器, 而初始化操作在中间件中进行
return new Store(session)
}
}
}

View File

@ -3,29 +3,32 @@
* @author yutent<yutent.io@gmail.com> * @author yutent<yutent.io@gmail.com>
* @date 2020/09/18 16:35:26 * @date 2020/09/18 16:35:26
*/ */
import 'es.shim'
import Ioredis from 'ioredis' import Ioredis from 'ioredis'
export default class Session { export default class Store {
#store = null
#ttl = 60
constructor(opt) { constructor(opt) {
this.store = new Ioredis({ this.#store = new Ioredis({
host: opt.db.host || '127.0.0.1', host: opt.db.host || '127.0.0.1',
port: opt.db.port || 6379, port: opt.db.port || 6379,
db: opt.db.db || 0 db: opt.db.db || 0
}) })
this.ttl = opt.ttl this.#ttl = opt.ttl
} }
start(ssid) { update(ssid) {
// 设置session有效期 // 设置session有效期
this.store.expire(ssid, this.ttl) this.#store.expire(ssid, this.#ttl)
} }
// 获取session字段值, 需要await指令 // 获取session字段值, 需要await指令
get(ssid, key) { get(ssid, key) {
var defer = Promise.defer() let defer = Promise.defer()
this.store.hgetall(ssid, (err, obj) => { this.#store.hgetall(ssid, (err, obj) => {
if (err) { if (err) {
return defer.reject(err) return defer.reject(err)
} }
@ -37,7 +40,7 @@ export default class Session {
} }
//不传key时,直接返回全部字段 //不传key时,直接返回全部字段
if (key) { if (key) {
defer.resolve(obj.hasOwnProperty(key) ? obj[key] : null) defer.resolve(obj[key])
} else { } else {
defer.resolve(obj) defer.resolve(obj)
} }
@ -49,20 +52,20 @@ export default class Session {
set(ssid, key, val) { set(ssid, key, val) {
if (typeof key === 'object') { if (typeof key === 'object') {
for (let i in key) { for (let i in key) {
this.store.hset(ssid, i, key[i]) this.#store.hset(ssid, i, key[i])
} }
} else { } else {
this.store.hset(ssid, key, val) this.#store.hset(ssid, key, val)
} }
} }
//删除单个字段 //删除单个字段
unset(ssid, key) { unset(ssid, key) {
this.store.hdel(ssid, key) this.#store.hdel(ssid, key)
} }
//清除个人session //清除个人session
clear(ssid) { clear(ssid) {
this.store.del(ssid) this.#store.del(ssid)
} }
} }

View File

@ -1,15 +1,22 @@
{ {
"name": "@gm5/session", "name": "@gm5/session",
"version": "1.1.2", "version": "3.0.0",
"type": "module", "type": "module",
"description": "会话中间件。", "description": "会话中间件。",
"main": "index.js",
"author": "yutent <yutent.io@gmail.com>", "author": "yutent <yutent.io@gmail.com>",
"keywords": ["fivejs", "session", "http"], "main": "index.js",
"types": "index.d.ts",
"keywords": [
"fivejs",
"gm5",
"session",
"http"
],
"dependencies": { "dependencies": {
"crypto.js": "^2.0.2", "crypto.js": "^3.1.2",
"ioredis": "^4.17.3" "ioredis": "^5.3.2",
"es.shim": "^2.2.0"
}, },
"repository": "https://github.com/bytedo/gmf.session.git", "repository": "https://git.wkit.fun/gm5/session.git",
"license": "MIT" "license": "MIT"
} }