mm_session 1.5.0 → 1.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/test.js ADDED
@@ -0,0 +1,190 @@
1
+ const { Session, Store } = require('./index.js');
2
+
3
+ String.prototype.aes_encode = function(key) {
4
+ // 简单的AES编码模拟
5
+ return Buffer.from(this).toString('base64') + '_' + key.substring(0, 8);
6
+ };
7
+
8
+ // 模拟Koa应用
9
+ class MockKoaApp {
10
+ constructor() {
11
+ this.middlewares = [];
12
+ }
13
+
14
+ use(middleware) {
15
+ this.middlewares.push(middleware);
16
+ }
17
+
18
+ async handleRequest(ctx) {
19
+ // 执行中间件链
20
+ const executeMiddleware = async (index) => {
21
+ if (index < this.middlewares.length) {
22
+ const middleware = this.middlewares[index];
23
+ await middleware(ctx, () => executeMiddleware(index + 1));
24
+ }
25
+ };
26
+
27
+ await executeMiddleware(0);
28
+ }
29
+ }
30
+
31
+ // 模拟Koa的上下文对象
32
+ class MockContext {
33
+ constructor() {
34
+ this.cookies = new MockCookies();
35
+ this.headers = {};
36
+ this.ip = '127.0.0.1';
37
+ this.request = {
38
+ header: {
39
+ 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
40
+ }
41
+ };
42
+ this.session = null;
43
+ }
44
+ }
45
+
46
+ // 模拟Koa的cookies对象
47
+ class MockCookies {
48
+ constructor() {
49
+ this._cookies = new Map();
50
+ }
51
+
52
+ get(key, options) {
53
+ return this._cookies.get(key);
54
+ }
55
+
56
+ set(key, value, options) {
57
+ if (value === null) {
58
+ this._cookies.delete(key);
59
+ } else {
60
+ this._cookies.set(key, value);
61
+ }
62
+ }
63
+ }
64
+
65
+ // 测试session模块
66
+ async function testSession() {
67
+ console.log('开始测试session模块...\n');
68
+
69
+ try {
70
+ // 测试1: 创建Session实例
71
+ console.log('测试1: 创建Session实例');
72
+ const session = new Session({
73
+ key: 'test_session',
74
+ max_age: 3600
75
+ });
76
+ console.log('✅ Session实例创建成功\n');
77
+
78
+ // 测试2: 创建Koa应用并注册中间件
79
+ console.log('测试2: 创建Koa应用并注册中间件');
80
+ const app = new MockKoaApp();
81
+
82
+ // 使用Koa标准方式注册session中间件
83
+ app.use(session.middleware());
84
+
85
+ // 添加一个业务中间件来测试session功能
86
+ app.use(async (ctx, next) => {
87
+ // 测试session数据操作
88
+ if (!ctx.session.user_id) {
89
+ ctx.session.user_id = 123;
90
+ ctx.session.username = 'test_user';
91
+ }
92
+
93
+ await next();
94
+ });
95
+
96
+ console.log('✅ Koa应用创建成功,中间件注册完成\n');
97
+
98
+ // 测试3: 测试新session创建
99
+ console.log('测试3: 测试新session创建');
100
+ const ctx1 = new MockContext();
101
+
102
+ await app.handleRequest(ctx1);
103
+
104
+ // 等待session保存完成(模拟异步保存过程)
105
+ await new Promise(resolve => setTimeout(resolve, 50));
106
+
107
+ if (ctx1.session) {
108
+ console.log('✅ 新session创建成功');
109
+ console.log(' session对象:', typeof ctx1.session);
110
+ console.log(' user_id:', ctx1.session.user_id);
111
+ console.log(' username:', ctx1.session.username);
112
+ } else {
113
+ throw new Error('session创建失败');
114
+ }
115
+
116
+ // 测试4: 测试session保存和读取
117
+ console.log('\n测试4: 测试session保存和读取');
118
+
119
+ // 检查cookie是否设置
120
+ const sessionCookie = ctx1.cookies.get('test_session');
121
+ if (sessionCookie) {
122
+ console.log('✅ session保存成功,cookie已设置');
123
+ console.log(' session ID:', sessionCookie);
124
+ } else {
125
+ console.log('⚠️ session保存但cookie未设置');
126
+ }
127
+
128
+ // 测试5: 测试session读取(模拟有cookie的情况)
129
+ console.log('\n测试5: 测试session读取');
130
+ const ctx2 = new MockContext();
131
+
132
+ // 设置cookie模拟已有session
133
+ if (sessionCookie) {
134
+ ctx2.cookies.set('test_session', sessionCookie);
135
+ }
136
+
137
+ await app.handleRequest(ctx2);
138
+
139
+ if (ctx2.session) {
140
+ console.log('✅ session读取成功');
141
+ console.log(' session对象存在');
142
+ console.log(' user_id:', ctx2.session.user_id);
143
+ console.log(' username:', ctx2.session.username);
144
+ } else {
145
+ console.log('⚠️ session读取失败(可能是新session)');
146
+ }
147
+
148
+ // 测试6: 测试Store类
149
+ console.log('\n测试6: 测试Store类');
150
+ const store = new Store('test');
151
+
152
+ // 模拟获取session ID
153
+ const sessionId = await store.getID(ctx1);
154
+ console.log('✅ Store类测试成功');
155
+ console.log(' 生成的session ID:', sessionId);
156
+
157
+ // 测试7: 测试session销毁
158
+ console.log('\n测试7: 测试session销毁');
159
+ const ctx3 = new MockContext();
160
+
161
+ // 添加一个中间件来测试session销毁
162
+ const destroyApp = new MockKoaApp();
163
+ destroyApp.use(session.middleware());
164
+ destroyApp.use(async (ctx, next) => {
165
+ // 设置session为null触发销毁
166
+ ctx.session = null;
167
+ await next();
168
+ });
169
+
170
+ await destroyApp.handleRequest(ctx3);
171
+ console.log('✅ session销毁逻辑测试完成');
172
+
173
+ console.log('\n🎉 所有测试通过!session模块功能正常。');
174
+
175
+ } catch (error) {
176
+ console.error('❌ 测试失败:', error.message);
177
+ console.error(error.stack);
178
+ }
179
+ }
180
+
181
+ // 运行测试
182
+ if (require.main === module) {
183
+ testSession().catch(console.error);
184
+ }
185
+
186
+ module.exports = {
187
+ MockContext,
188
+ MockCookies,
189
+ testSession
190
+ };
package/store.js DELETED
@@ -1,96 +0,0 @@
1
- const crypto = require('crypto');
2
- const CacheBase = require('mm_cachebase');
3
-
4
- if (!$.cache) {
5
- $.cache = new CacheBase();
6
- }
7
-
8
- /**
9
- * @class 缓存
10
- */
11
- class Store {
12
- /**
13
- * @description 构造函数
14
- * @param {String} key 键
15
- * @constructor
16
- */
17
- constructor(key) {
18
- if (key) {
19
- this.key = key + "_";
20
- } else {
21
- this.key = $.dict.session_id + "_";
22
- }
23
- }
24
- }
25
-
26
- /**
27
- * @description 获取session ID
28
- * @param {Object} ctx HTTP上下文
29
- */
30
- Store.prototype.getID = async function(ctx) {
31
- var hd = ctx.request.header;
32
- var agent = hd['user-agent'];
33
- if (!agent) {
34
- agent = "mm";
35
- }
36
- var start = agent.md5().substring(0, 32);
37
- var stamp = Date.parse(new Date()) / 1000;
38
- var uuid = (ctx.ip + '_' + stamp).aes_encode(start);
39
- return uuid;
40
- };
41
-
42
- /**
43
- * @description 获取session缓存
44
- * @param {String} uuid 客户端唯一ID
45
- */
46
- Store.prototype.get = async function(uuid) {
47
- if (!$.cache.has(this.key + uuid)) return undefined;
48
- // 我们正在解码数据来自我们的srote, 我们假定它是在储存之前
49
- var val = await $.cache.get(this.key + uuid);
50
- if (val) {
51
- if (typeof(val) == "string") {
52
- return JSON.parse(val);
53
- }
54
- return val;
55
- } else {
56
- return null;
57
- }
58
- };
59
-
60
- /**
61
- * @description 设置session到缓存
62
- * @param {Object} obj
63
- * @property {String} obj.uuid 客户端唯一表示ID
64
- * @property {Number} obj.maxAge 最大寿命
65
- * @param {Object} ctx HTTP请求上下文
66
- */
67
- Store.prototype.set = async function(session, {
68
- uuid,
69
- maxAge
70
- } = {}, ctx) {
71
- if (!uuid) {
72
- uuid = await this.getID(ctx);
73
- }
74
- if (!maxAge) {
75
- maxAge = 7200;
76
- }
77
- try {
78
- if (typeof(session) == "object") {
79
- session = JSON.stringify(session);
80
- }
81
- await $.cache.set(this.key + uuid, session, maxAge);
82
- } catch (err) {
83
- console.log('Set session error:', err);
84
- }
85
- return uuid;
86
- };
87
-
88
- /**
89
- * @description 销毁缓存
90
- * @param {String} uuid
91
- */
92
- Store.prototype.destroy = function(uuid) {
93
- $.cache.del(this.key + uuid);
94
- };
95
-
96
- module.exports = Store;