-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathldap.js
138 lines (113 loc) · 2.58 KB
/
ldap.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
const ldap = require('ldapjs');
module.exports = class LDAP {
constructor(servers, suffix, base) {
this._urls = servers.map(server => 'ldaps://' + server);
this._suffix = '@' + suffix;
this._base = base;
}
resetPassword(username, password, targetUsername, targetPassword, callback) {
let client = this._connect(username, password, err => {
function done(err) {
client.destroy();
callback(err);
}
if (err) {
done(err);
return;
}
this._search(client, targetUsername, (err, dn) => {
if (err) {
done(err);
return;
}
client.modify(dn, new ldap.Change({
operation: 'replace',
modification: {
unicodePwd: encode(targetPassword)
}
}), done);
});
});
}
changePassword(username, password, newPassword, callback) {
let client = this._connect(username, password, err => {
function done(err) {
client.destroy();
callback(err);
}
if (err) {
done(err);
return;
}
this._search(client, username, (err, dn) => {
if (err) {
done(err);
return;
}
client.modify(dn, [
new ldap.Change({
operation: 'delete',
modification: {
unicodePwd: encode(password)
}
}),
new ldap.Change({
operation: 'add',
modification: {
unicodePwd: encode(newPassword)
}
})
], done);
});
});
}
_connect(username, password, callback) {
let client = ldap.createClient({url: this._urls});
client.on('error', err => {
callback(err);
});
client.on('connect', () => {
client.bind(username + this._suffix, password, err => {
callback(err);
});
});
return client;
}
_search(client, username, callback) {
username = username.replace(/[*()\\\0]/g, char => '\\' + char.charCodeAt(0).toString(16).padStart(2, '0'));
let options = {
filter: '(&(objectClass=user)(objectCategory=person)(sAMAccountName=' + username + '))',
scope: 'sub',
sizeLimit: 1
}
client.search(this._base, options, (err, res) => {
if (err) {
callback(err);
return;
}
let dn = null;
res.on('error', err => {
callback(err);
});
res.on('searchEntry', entry => {
dn = entry.objectName;
});
res.on('end', result => {
if (result.status !== 0) {
callback(new Error(result.errorMessage));
return;
}
if (dn === null) {
let err = new Error('User not found');
err.name = 'UserNotFoundError';
callback(err);
return;
}
callback(null, dn);
});
});
}
}
function encode(password) {
return Buffer.from('"' + password + '"', 'utf16le').toString();
}