-
Notifications
You must be signed in to change notification settings - Fork 568
/
session.ts
63 lines (57 loc) 路 1.61 KB
/
session.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import {
Config,
Inject,
Logger,
Middleware,
IMiddleware,
MidwayConfigMissingError,
MidwayConfigService,
} from '@midwayjs/core';
import * as session from 'express-session';
import * as cookieSession from 'cookie-session';
import { SessionStoreManager } from '../store';
@Middleware()
export class SessionMiddleware implements IMiddleware<any, any> {
@Config('session')
sessionConfig;
@Logger()
logger;
@Inject()
sessionStoreManager: SessionStoreManager;
@Inject()
configService: MidwayConfigService;
resolve() {
if (this.sessionConfig.enable) {
const secret =
this.sessionConfig.secret ??
this.configService.getConfiguration('express.keys') ??
this.configService.getConfiguration('keys');
if (!secret) {
throw new MidwayConfigMissingError('config.session.secret');
}
this.sessionConfig.secret = [].concat(secret);
if (!this.sessionConfig.cookie.httpOnly) {
this.logger.warn(
'[midway-session]: please set `config.session.cookie.httpOnly` to true. It is very dangerous if session can read by client JavaScript.'
);
}
const store = this.sessionStoreManager.getSessionStore(session);
if (store) {
this.sessionConfig.store = store;
}
if (!this.sessionConfig.store) {
return cookieSession(
Object.assign(this.sessionConfig.cookie, {
keys: this.sessionConfig.secret,
name: this.sessionConfig.name,
})
);
} else {
return session(this.sessionConfig);
}
}
}
static getName() {
return 'session';
}
}