forked from launchdarkly/node-server-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
user_filter.js
58 lines (53 loc) · 2.02 KB
/
user_filter.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
var messages = require('./messages');
/**
* The UserFilter object transforms user objects into objects suitable to be sent as JSON to
* the server, hiding any private user attributes.
*
* @param {Object} the LaunchDarkly client configuration object
**/
function UserFilter(config) {
var filter = {};
const allAttributesPrivate = config.allAttributesPrivate;
const privateAttributeNames = config.privateAttributeNames || [];
var ignoreAttrs = { key: true, custom: true, anonymous: true };
var allowedTopLevelAttrs = { key: true, secondary: true, ip: true, country: true, email: true,
firstName: true, lastName: true, avatar: true, name: true, anonymous: true, custom: true };
filter.filterUser = function(user) {
var allPrivateAttrs = {};
var userPrivateAttrs = user.privateAttributeNames || [];
var isPrivateAttr = function(name) {
return !ignoreAttrs[name] && (
allAttributesPrivate || userPrivateAttrs.indexOf(name) !== -1 ||
privateAttributeNames.indexOf(name) !== -1);
}
var filterAttrs = function(props, isAttributeAllowed) {
return Object.keys(props).reduce(function(acc, name) {
if (isAttributeAllowed(name)) {
if (isPrivateAttr(name)) {
// add to hidden list
acc[1][name] = true;
} else {
acc[0][name] = props[name];
}
}
return acc;
}, [{}, {}]);
}
var result = filterAttrs(user, function(key) { return allowedTopLevelAttrs[key]; });
var filteredProps = result[0];
var removedAttrs = result[1];
if (user.custom) {
var customResult = filterAttrs(user.custom, function(key) { return true; });
filteredProps.custom = customResult[0];
Object.assign(removedAttrs, customResult[1]);
}
var removedAttrNames = Object.keys(removedAttrs);
if (removedAttrNames.length) {
removedAttrNames.sort();
filteredProps.privateAttrs = removedAttrNames;
}
return filteredProps;
}
return filter;
}
module.exports = UserFilter;