-
Notifications
You must be signed in to change notification settings - Fork 567
/
session.stratey.ts
77 lines (70 loc) 路 2 KB
/
session.stratey.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import { Strategy } from './strategy';
import { httpError } from '@midwayjs/core';
import { pause } from './pause';
/**
* `SessionStrategy` constructor.
*
* @api public
*/
export class SessionStrategy extends Strategy {
_deserializeUser;
constructor(
readonly options: {
userProperty: string;
sessionUserProperty: string;
pauseStream?: boolean;
},
deserializeUser
) {
super();
this.name = 'session';
this._deserializeUser = deserializeUser;
}
/**
* Authenticate request based on the current session state.
*
* The session authentication strategy uses the session to restore any login
* state across requests. If a login session has been established, `req.user`
* will be populated with the current user.
*
* This strategy is registered automatically by Passport.
*
* @param {Object} req
* @param {Object} options
* @api protected
*/
authenticate(req, options) {
if (!req.session) {
throw new httpError.UnauthorizedError(
'Login sessions require session support锛宲lease enable it.'
);
}
options = options || {};
let su;
if (req.session[this.options.sessionUserProperty]) {
su = req.session[this.options.sessionUserProperty].user;
}
if (su || su === 0) {
// NOTE: Stream pausing is desirable in the case where later middleware is
// listening for events emitted from request. For discussion on the
// matter, refer to: https://github.com/jaredhanson/passport/pull/106
const paused = options.pauseStream ? pause(req) : null;
this._deserializeUser(su, req, (err, user) => {
if (err) {
throw new httpError.UnauthorizedError(err.message);
}
if (!user) {
delete req.session[this.options.sessionUserProperty].user;
this.pass();
} else {
this.success(user);
}
if (paused) {
paused.resume();
}
});
} else {
this.pass();
}
}
}