-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.js
90 lines (75 loc) · 2.21 KB
/
auth.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
module.exports = (Grown, util) => {
function _callback() {
}
return Grown('Session.Auth', {
_callback,
effect(callback, _middleware) {
const session = require('./use/session')(this, callback);
const middleware = this.extensions.reduce((prev, cur) => {
Object.assign(prev, cur);
return prev;
}, {});
return util.chain(Grown, {
session,
...middleware,
..._middleware,
});
},
use(path, types, callback) {
if (path.charAt() !== '/') {
throw new Error(`Missing root, given '${path}'`);
}
const middleware = Object.keys(types).reduce((prev, cur) => {
prev[cur] = ctx => {
try {
const is = types[cur].enabled;
const ok = typeof is === 'function' ? is(ctx) : is;
if (ok) {
return require(`./passport/${cur}`)(types[cur], ctx, callback);
}
} catch (e) {
throw new Error(`Failed at loading '${cur}' strategy (${e.message})`);
}
};
return prev;
}, {});
return (req, res, next) => {
if (req.url.indexOf(path) !== 0) {
next();
return;
}
const [baseUri, searchQuery] = req.url.split('?');
const [,, type, action] = baseUri.split('/');
if (!type) {
next(new Error('Missing authorization'));
return;
}
if (!req.query) {
req.query = Object.fromEntries(new URLSearchParams(searchQuery || ''));
}
if (!middleware[type]) {
next(new Error(`Missing authorization for ${type}`));
return;
}
if (action) {
middleware[type](req)(req, res, err => {
if (err) {
next(err);
return;
}
const prefix = types[type].redirect || '/';
const param = types[type].parameter || 'token';
res.setHeader('Location', `${prefix}?${param}=${req.user.token || ''}`);
res.status(301).end();
});
return;
}
try {
middleware[type](req)(req, res, next);
} catch (e) {
next(e);
}
};
},
});
};