-
-
Notifications
You must be signed in to change notification settings - Fork 219
/
authorization.js
98 lines (82 loc) · 2.46 KB
/
authorization.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
95
96
97
98
const auth = require('../auth');
const serverUtils = require('../server-utils');
const FIREWALL_ERROR = {
code: 403,
error: 'forbidden',
details: 'Offline users are not allowed access to this endpoint'
};
const getUserSettings = (req) => {
return auth
.getUserSettings(req.userCtx)
.then(userCtx => {
req.userCtx = userCtx;
})
.catch(err => err);
};
module.exports = {
// saves CouchDB _session information as `userCtx` in the `req` object
getUserCtx: (req, res, next) => {
return auth
.getUserCtx(req)
.then(userCtx => {
req.userCtx = userCtx;
req.replicationId = req.headers['medic-replication-id'];
})
.catch(err => {
req.authErr = err;
})
.then(next);
},
handleAuthErrors: (req, res, next) => {
if (req.authErr) {
return serverUtils.error(req.authErr, req, res);
}
if (!req.userCtx) {
return serverUtils.error('Authentication error', req, res);
}
next();
},
handleAuthErrorsAllowingAuthorized: (req, res, next) => {
if (req.authorized) {
return next();
}
return module.exports.handleAuthErrors(req, res, next);
},
// blocks offline users not-authorized requests
offlineUserFirewall: (req, res, next) => {
if (req.userCtx && !auth.isOnlineOnly(req.userCtx) && !req.authorized) {
res.status(FIREWALL_ERROR.code);
return res.json(FIREWALL_ERROR);
}
next();
},
// proxies unauthenticated requests to CouchDB
// proxies online users requests to CouchDB
// saves offline user-settings doc in the request object
onlineUserProxy: (proxy, req, res, next) => {
if (!req.userCtx || auth.isOnlineOnly(req.userCtx)) {
return proxy.web(req, res);
}
return getUserSettings(req).then(next);
},
// online users requests pass through to the next route, skipping other middleware in the stack
// saves offline user-settings doc in the request object
// used for audited endpoints
onlineUserPassThrough: (req, res, next) => {
if (auth.isOnlineOnly(req.userCtx)) {
return next('route');
}
return getUserSettings(req).then(next);
},
// sets the authorized flag for a request. authorized requests may pass through the firewall.
setAuthorized: (req, res, next) => {
req.authorized = true;
next();
},
getUserSettings: (req, res, next) => {
if (auth.isOnlineOnly(req.userCtx)) {
return next();
}
return getUserSettings(req).then(next);
}
};