-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDirectoryRepository.cs
331 lines (266 loc) · 10.8 KB
/
DirectoryRepository.cs
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
using System;
using System.Collections.Generic;
using System.DirectoryServices.Protocols;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
namespace DirLink
{
public class DirectoryRepository : IDisposable
{
private readonly NetworkCredential _credentials;
private readonly LdapDirectoryIdentifier _identifier;
private LdapConnection _connection;
private RootDse _lastRootDse;
/// <summary>
/// Creates a new instance of <see cref="DirectoryRepository" /> with the specified connections parameters and
/// credentials.
/// </summary>
public DirectoryRepository(LdapDirectoryIdentifier identifier, NetworkCredential credentials)
{
_identifier = identifier;
_credentials = credentials;
}
public Action<LdapConnection> ConfigureConnectionCallback { get; set; }
public void Dispose()
{
if (_connection == null) return;
_connection.Dispose();
_connection = null;
}
/// <summary>
/// Tests the specified <paramref name="credentials" /> against <paramref name="host" /> using fast concurrent bind.
/// </summary>
/// <param name="identifier"></param>
/// <param name="credentials"></param>
/// <param name="configCallback"></param>
/// <returns></returns>
public static Task<TestBindResult> TestBind(LdapDirectoryIdentifier identifier, NetworkCredential credentials,
Action<LdapConnection> configCallback = null)
{
Action<LdapConnection> config = configCallback ?? DefaultConnectionConfiguration;
var connection = new LdapConnection(identifier)
{
AutoBind = false,
AuthType = AuthType.Basic,
Timeout = TimeSpan.FromSeconds(10)
};
config(connection);
var tcs = new TaskCompletionSource<TestBindResult>();
Task.Run(() =>
{
try
{
connection.SessionOptions.FastConcurrentBind();
connection.Bind(credentials);
tcs.TrySetResult(new TestBindResult {Success = true});
}
catch (LdapException e)
{
tcs.TrySetResult(new TestBindResult
{
Success = false,
ErrorCode = e.ErrorCode,
ServerErrorMessage = e.ServerErrorMessage
});
}
finally
{
connection.Dispose();
}
});
return tcs.Task;
}
private async Task<DirectoryResponse> SendRequest(DirectoryRequest request)
{
IAsyncResult ar = _connection.BeginSendRequest(request, default(PartialResultProcessing), null, null);
return await Task.Factory.FromAsync(ar, x => _connection.EndSendRequest(x));
}
public async Task<ResultCode> Add(string dn, string objectClass)
{
await EnsureBind();
try
{
var request = new AddRequest(dn, objectClass);
var response = (AddResponse) await SendRequest(request);
return response.ResultCode;
}
catch (DirectoryOperationException ex)
{
if (ex.Response != null)
{
return ex.Response.ResultCode;
}
throw;
}
}
public async Task<ResultCode> Delete(string dn)
{
await EnsureBind();
try
{
var request = new DeleteRequest(dn);
var response = (DeleteResponse) await SendRequest(request);
return response.ResultCode;
}
catch (DirectoryOperationException ex)
{
if (ex.Response != null)
{
return ex.Response.ResultCode;
}
throw;
}
}
public async Task<ResultCode> Modify(string dn, params DirectoryAttributeModification[] modifications)
{
await EnsureBind();
try
{
var request = new ModifyRequest(dn, modifications);
request.Controls.Add(new ShowDeletedControl());
var response = (ModifyResponse) await SendRequest(request);
return response.ResultCode;
}
catch (DirectoryOperationException ex)
{
if (ex.Response != null)
{
return ex.Response.ResultCode;
}
throw;
}
}
public async Task<ResultCode> Modify(string dn, IEnumerable<DirectoryAttributeModification> modifications)
{
return await Modify(dn, modifications.ToArray());
}
public async Task<ResultCode> ModifyDn(string dn, string newParentDn, string newObjectName)
{
await EnsureBind();
var request = new ModifyDNRequest(dn, newParentDn, newObjectName);
request.Controls.Add(new ShowDeletedControl());
var response = (ModifyDNResponse) await SendRequest(request);
return response.ResultCode;
}
public async Task<ResultCode> SetPassword(string dn, string password)
{
await EnsureBind();
return await Modify(dn, Modification.Set("userPassword", password));
}
/// <summary>
/// Asynchronously executes a <paramref name="request" />.
/// </summary>
/// <param name="request"></param>
/// <param name="option"></param>
/// <param name="pageSize"></param>
/// <returns></returns>
public async Task<IList<SearchResultWrapper>> Search(
SearchRequest request,
SearchOption option = SearchOption.DomainScope,
int pageSize = 1000)
{
await EnsureBind();
var result = new List<SearchResponse>();
request.Controls.Add(new SearchOptionsControl(option));
var pager = new PageResultRequestControl(pageSize);
request.Controls.Add(pager);
while (true)
{
var response = (SearchResponse) await SendRequest(request);
result.Add(response);
PageResultResponseControl pagerResponse = response.Controls
.OfType<PageResultResponseControl>()
.FirstOrDefault();
if (pagerResponse == null || pagerResponse.Cookie.Length == 0)
break;
pager.Cookie = pagerResponse.Cookie;
}
return result.SelectMany(x => x.Entries
.Cast<SearchResultEntry>())
.Select(x => new SearchResultWrapper(x))
.ToList();
}
/// <summary>
/// Asynchronous wrapper for simple searches. If no <paramref name="startDn" /> is defined,
/// <see cref="RootDse.DefaultNamingContext" /> will be used. The RootDse will be acquired if necessary.
/// </summary>
/// <param name="filter">A LDAP filter.</param>
/// <param name="startDn">
/// The DN of the object to start searching from -or- <c>null</c> if the
/// <see cref="RootDse.DefaultNamingContext" /> should be used.
/// </param>
/// <returns></returns>
public async Task<IList<SearchResultWrapper>> Query(string filter, string startDn = null)
{
if (startDn == null)
{
await EnsureRootDse();
startDn = _lastRootDse.DefaultNamingContext;
}
return await Search(new SearchRequest(startDn, filter, SearchScope.Subtree));
}
/// <summary>
/// Asynchronously retrieves one directory object by its distinguished name. If the object isn't found, <c>null</c> is returned.
/// </summary>
/// <param name="distinguishedName">The DN to look for.</param>
/// <param name="includeDeleted">Specify <c>true</c> to return the object even if it has been deleted.</param>
public async Task<SearchResultWrapper> GetObjectByDn(string distinguishedName, bool includeDeleted = false)
{
var sr = new SearchRequest(distinguishedName, (string) null, SearchScope.Base);
if (includeDeleted)
{
sr.Controls.Add(new ShowDeletedControl());
}
var results = await Search(sr);
return results.FirstOrDefault();
}
public async Task<RootDse> GetRootDse()
{
var search = new SearchRequest(null, "(objectClass=*)", SearchScope.Base);
SearchResultWrapper result = (await Search(search)).FirstOrDefault();
if (result == null)
return null;
var rootDse = new RootDse(result);
_lastRootDse = rootDse;
return rootDse;
}
private Task<bool> EnsureBind()
{
if (_connection != null) return Task.FromResult(false);
Action<LdapConnection> config = ConfigureConnectionCallback ?? DefaultConnectionConfiguration;
var connection = new LdapConnection(_identifier) {AutoBind = false};
config(connection);
var tcs = new TaskCompletionSource<bool>();
Task.Run(() =>
{
try
{
connection.Bind(_credentials);
_connection = connection;
tcs.TrySetResult(true);
}
catch (Exception e)
{
tcs.TrySetException(e);
}
});
return tcs.Task;
}
private async Task EnsureRootDse()
{
if (_lastRootDse != null) return;
await GetRootDse();
}
private static void DefaultConnectionConfiguration(LdapConnection connection)
{
connection.SessionOptions.SecureSocketLayer = true;
}
public class TestBindResult
{
public bool Success { get; set; }
public int ErrorCode { get; set; }
public string ServerErrorMessage { get; set; }
}
}
}