-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
110 lines (90 loc) · 2.75 KB
/
Copy pathindex.js
File metadata and controls
110 lines (90 loc) · 2.75 KB
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
99
100
101
102
103
104
105
106
107
108
109
110
'use strict'
var async = require('async')
module.exports = UserIs
var missingDefinitionErrorCode = 'E_MISSINGDEFINITION'
var notAuthorizedErrorCode = 'E_NOTAUTHORIZED'
var userNotFoundErrorCode = 'E_USERNOTFOUND'
function UserIs(roleFuncs, actionDefinitions, options) {
roleFuncs = roleFuncs || {}
actionDefinitions = actionDefinitions || {}
options = options || {}
options.errorOnMissingDefinitions = typeof(options.errorOnMissingDefinitions) !== 'undefined' ? options.errorOnMissingDefinitions : true
function forUser(user) {
function ableTo(action, cb) {
var rolesThatCan = actionDefinitions[action]
if (!rolesThatCan) {
if (options.errorOnMissingDefinitions) {
var error = new Error('You have not supplied a definition for action' + action)
error.code = missingDefinitionErrorCode
cb(error, false)
} else {
cb(null, false)
}
} else {
async.detect(
rolesThatCan
, function(role, next) {
a(role, function(err, isRole) {
next(isRole)
})
}
, function(result) {
if (typeof(result) === 'undefined') {
cb(null, false)
} else {
cb(null, true)
}
}
)
}
}
// As in "userIs.a or user is a"
// Justification for a one-letter function
function a(role, cb) {
var roleCheck = roleFuncs[role]
if (!roleCheck) {
if (options.errorOnMissingDefinitions) {
var error = new Error('You have not supplied a definition for role ' + role)
error.code = missingDefinitionErrorCode
cb(error, false)
} else {
cb(null, false)
}
} else {
roleCheck(user, cb)
}
}
return {
a: a
, ableTo: ableTo
}
}
function ensureAuthorizedTo(action) {
return function(req, res, next) {
options.retrieveUserFromRequest(req, function retrievedUser(err, user) {
if (err) return next(err)
if (!user) {
var error = new Error('User not found')
error.code = userNotFoundErrorCode
return next(error)
}
forUser(user).ableTo(action, function(err, isAble) {
if (err) return next(err)
if (!isAble) {
var error = new Error('Unauthorized')
error.code = notAuthorizedErrorCode
return next(error)
}
next()
})
})
}
}
return {
ensureAuthorizedTo: ensureAuthorizedTo
, forUser: forUser
}
}
UserIs.notAuthorizedErrorCode = notAuthorizedErrorCode
UserIs.userNotFoundErrorCode = userNotFoundErrorCode
UserIs.missingDefinitionErrorCode = missingDefinitionErrorCode