-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
92 lines (80 loc) · 2.38 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
const express = require('express');
const appendQuery = require('append-query');
module.exports = (
handler,
tokenStorage,
{
identityPath = '/user',
landingPath = '/',
callbackPath = '/authentication',
callbackRouteMethod = 'get',
serviceValidator = () => true,
useCookie = false,
cookieOptions = {},
app = express(),
tokenEncrypter = token => Promise.resolve(token),
} = {}
) => {
app.get(landingPath, [
(req, res, next) => {
const service = handler.parseService(req);
if (!service) {
return res.status(400).send('Service not present');
}
if (!serviceValidator(service, req)) {
return res.status(403).send('Invalid service');
}
if (useCookie) {
const token = req.cookies.get('paale_token', cookieOptions);
if (token) {
return tokenEncrypter(token, service, req)
.then(encryptedToken => res.redirect(appendQuery(service, `token=${encryptedToken}`)));
}
}
next();
},
handler.landing(callbackPath),
]);
app.route(callbackPath)[callbackRouteMethod]([
(req, res, next) => {
const service = handler.parseService(req);
if (!service || !serviceValidator(service, req)) {
return res.status(403).send('Invalid service');
}
req.paale_service = service;
next();
},
handler.authentication(callbackPath),
tokenStorage.store,
(req, res) => {
if (useCookie) {
res.cookies.set('paale_token', req.paale_token, cookieOptions);
}
tokenEncrypter(req.paale_token, req.paale_service, req)
.then(encryptedToken => res.redirect(appendQuery(req.paale_service, `token=${encryptedToken}`)));
},
]);
app.get(identityPath, [
(req, res, next) => {
if (useCookie) {
req.paale_token = req.cookies.get('paale_token', cookieOptions);
if (req.paale_token) {
return next();
}
}
let parts = req.get('Authorization');
if (!parts) {
return res.status(401).send({ message: 'Unauthenticated' });
}
parts = parts.split(' ');
if (parts.length !== 2) {
return res.status(400).send({ message: 'Incorrect Authorization header format' });
}
req.paale_token = parts[1];
next();
},
tokenStorage.parse,
(req, res) => res.status(200).send(req.paale_user),
]);
return app;
};