-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
94 lines (83 loc) · 1.87 KB
/
index.js
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
const session = require('express-session');
passport = require('passport');
module.exports = function(settingsCallback) {
if(process.browser) return {};
function runMiddleware(req, res, fn) {
return new Promise((resolve, reject) => {
fn(req, res, (result) => {
if (result instanceof Error) {
return reject(result)
}
return resolve(result)
});
})
}
const sessionOptions = settingsCallback(session);
const baseMiddlewares = [
session(sessionOptions),
passport.initialize(),
passport.session(),
];
async function applyMiddlewares(req, res) {
for(let middleware of baseMiddlewares) {
await runMiddleware(req, res, middleware);
}
}
function control(next) {
return async function(req, res) {
await applyMiddlewares(req, res);
await next(req, res);
}
}
function auth(strategy, successRedirect, failureRedirect) {
return control(async function(req, res) {
await runMiddleware(req, res, passport.authenticate(strategy, { successRedirect, failureRedirect }));
});
}
function access(check, successAction, failureAction) {
return async function(context) {
const { req, res } = context;
await applyMiddlewares(req, res);
if(req.user && check(req.user)) {
if(typeof successAction == 'string') {
return {
redirect: {
destination: successAction,
permanent: false,
},
};
} else if(typeof successAction == 'function') {
return await successAction(context);
} else {
return {
props: {},
};
}
} else {
if(failureAction) {
return {
redirect: {
destination: failureAction,
permanent: false,
},
};
} else {
return {
props: {},
};
}
}
};
}
async function getUser(req, res) {
await applyMiddlewares(req, res);
return req.user;
}
return {
access,
control,
auth,
getUser,
passport,
};
}