-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
84 lines (74 loc) · 1.84 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
/*
* A class to decide if we should let the user pass
*/
var Troll = function()
{
this.strategies = [];
this.redirectUrl = '/login';
}
Troll.prototype.PREMADESTRATEGIES = {
PASSPORT: require('./bakedstrategies/passport'),
USERPROPERTY: require('./bakedstrategies/userproperty')
}
/**
* Sets the redirectUrl if it is unable to login
* @param redirectUrl {string} the redirectUrl
*/
Troll.prototype.setRedirectUrl = function(redirectUrl) {
this.redirectUrl = redirectUrl;
}
/**
* Adds strategies to the troll repository to run through
* @param strategies {array} Array of functions to run through
*/
Troll.prototype.addStrategies = function(strategies) {
if (!(strategies instanceof Array)) {
strategies = [strategies];
}
this.strategies = this.strategies.concat(strategies);
}
/**
* Function to use if troll shows an error
*/
Troll.prototype.shallNotPass = function(permission)
{
var that = this;
return function(req, res, next)
{
that.userHasPermission(req, permission, function(error, hasPermission) {
if (hasPermission) {
next();
return;
}
req.session.error = error;
res.redirect(that.redirectUrl);
});
}
}
Troll.prototype.userHasPermission = function(req, permission, cb)
{
try {
for (var index in this.strategies) {
this.strategies[index](req, permission);
}
} catch(e) {
if (cb) {
cb(e, false);
}
return false;
}
if (cb) {
cb(null, true);
}
return true;
}
/**
* Can be used with a templating language
*/
Troll.prototype.layoutHasPermission = function(req) {
var that = this;
return function(permission) {
return that.userHasPermission(req, permission);
}
}
module.exports = new Troll();