-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathtenant.js
75 lines (64 loc) · 1.86 KB
/
tenant.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
function getUrlTenant (req) {
var hostParts = req.get('host').split('.');
if (hostParts.length > 2) {
return hostParts[0];
}
}
function getAuthorizedTenants (req) {
if (req.user) {
return req.user._json[`http://${process.env.ROOT_DOMAIN}/claims/groups`];
}
}
module.exports = {
// Attempts to sets req.tenant
setCurrent: function (predicate) {
return function (req, res, next) {
// first try the passed predicate
if (predicate) {
var value = predicate(req);
if (value) {
req.tenant = value;
return next();
}
}
// then try the URL
var urlTenant = getUrlTenant(req);
if (urlTenant)
{
req.tenant = urlTenant;
return next();
}
// finally check to see if the authenticated user has a single authorized tenant
var tenants = getAuthorizedTenants(req);
if (tenants && tenants.length === 1) {
req.tenant = tenants[0];
}
next();
};
},
// Makes sure req.tenant exists
// and that the current user is authorized to access it;
// otherwise, redirect to appropriate tenant picker
ensureCurrent: function () {
return function (req, res, next) {
if (!req.tenant)
return res.redirect('/tenant/choose');
var tenants = getAuthorizedTenants(req);
if (!tenants || !tenants.some(tenant => tenant === req.tenant))
return res.redirect('/tenant/unauthorized');
next();
};
},
// If req.tenant exists but there's no tenant in the URL
// redirect to an equivalent URL with the tenant
ensureUrl: function () {
return function (req, res, next) {
var urlTenant = getUrlTenant(req);
if (req.tenant && !urlTenant) {
var url = `http://${req.tenant}.${req.get('host')}${req.originalUrl}`;
return res.redirect(url);
}
next();
};
}
};