/
admin.js
144 lines (101 loc) · 2.72 KB
/
admin.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
'use strict';
const AdminGroup = require('./admin-group');
const Async = require('async');
const Joi = require('joi');
const MongoModels = require('mongo-models');
class Admin extends MongoModels {
static create(name, callback) {
const nameParts = name.trim().split(/\s/);
const document = {
name: {
first: nameParts.shift(),
middle: nameParts.length > 1 ? nameParts.shift() : undefined,
last: nameParts.join(' ')
},
timeCreated: new Date()
};
this.insertOne(document, (err, docs) => {
if (err) {
return callback(err);
}
callback(null, docs[0]);
});
}
static findByUsername(username, callback) {
const query = { 'user.name': username.toLowerCase() };
this.findOne(query, callback);
}
constructor(attrs) {
super(attrs);
Object.defineProperty(this, '_groups', {
writable: true,
enumerable: false
});
}
isMemberOf(group) {
if (!this.groups) {
return false;
}
return this.groups.hasOwnProperty(group);
}
hydrateGroups(callback) {
if (!this.groups) {
this._groups = {};
return callback(null, this._groups);
}
if (this._groups) {
return callback(null, this._groups);
}
const tasks = {};
Object.keys(this.groups).forEach((group) => {
tasks[group] = function (done) {
AdminGroup.findById(group, done);
};
});
Async.auto(tasks, (err, results) => {
if (err) {
return callback(err);
}
this._groups = results;
callback(null, this._groups);
});
}
hasPermissionTo(permission, callback) {
if (this.permissions && this.permissions.hasOwnProperty(permission)) {
return callback(null, this.permissions[permission]);
}
this.hydrateGroups((err) => {
if (err) {
return callback(err);
}
let groupHasPermission = false;
Object.keys(this._groups).forEach((group) => {
if (this._groups[group].hasPermissionTo(permission)) {
groupHasPermission = true;
}
});
callback(null, groupHasPermission);
});
}
}
Admin.collection = 'admins';
Admin.schema = Joi.object().keys({
_id: Joi.object(),
user: Joi.object().keys({
id: Joi.string().required(),
name: Joi.string().lowercase().required()
}),
groups: Joi.object().description('{ groupId: name, ... }'),
permissions: Joi.object().description('{ permission: boolean, ... }'),
name: Joi.object().keys({
first: Joi.string().required(),
middle: Joi.string().allow(''),
last: Joi.string().required()
}),
timeCreated: Joi.date()
});
Admin.indexes = [
{ key: { 'user.id': 1 } },
{ key: { 'user.name': 1 } }
];
module.exports = Admin;