forked from ServiceStack/ServiceStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRavenDbUserAuthRepositoryAsync.cs
More file actions
340 lines (277 loc) · 14.3 KB
/
RavenDbUserAuthRepositoryAsync.cs
File metadata and controls
340 lines (277 loc) · 14.3 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
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
332
333
334
335
336
337
338
339
340
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using ServiceStack.Auth;
using Raven.Client;
using ServiceStack.DataAnnotations;
using Raven.Client.Documents;
using Raven.Client.Documents.Indexes;
using Raven.Client.Documents.Session;
using Raven.Client.Documents.Linq;
using ServiceStack.Text;
namespace ServiceStack.Authentication.RavenDb
{
public partial class RavenDbUserAuthRepository<TUserAuth, TUserAuthDetails> : IUserAuthRepositoryAsync, IQueryUserAuthAsync
where TUserAuth : class, IUserAuth
where TUserAuthDetails : class, IUserAuthDetails
{
public static async Task CreateOrUpdateUserAuthIndexAsync(IDocumentStore store, CancellationToken token=default)
{
// put this index into the ravendb database
await new UserAuth_By_UserNameOrEmail().ExecuteAsync(store, token: token).ConfigAwait();
await new UserAuth_By_UserAuthDetails().ExecuteAsync(store, token: token).ConfigAwait();
isInitialized = true;
}
public async Task<IUserAuth> CreateUserAuthAsync(IUserAuth newUser, string password, CancellationToken token = default)
{
newUser.ValidateNewUser(password);
await AssertNoExistingUserAsync(newUser, token: token).ConfigAwait();
newUser.PopulatePasswordHashes(password);
newUser.CreatedDate = DateTime.UtcNow;
newUser.ModifiedDate = newUser.CreatedDate;
using var session = documentStore.OpenSession();
session.Store(newUser);
session.SaveChanges();
return newUser;
}
public async Task<IUserAuth> UpdateUserAuthAsync(IUserAuth existingUser, IUserAuth newUser, CancellationToken token = default)
{
newUser.ValidateNewUser();
await AssertNoExistingUserAsync(newUser, existingUser, token).ConfigAwait();
UpdateKey(existingUser, newUser);
newUser.Id = existingUser.Id;
newUser.PasswordHash = existingUser.PasswordHash;
newUser.Salt = existingUser.Salt;
newUser.DigestHa1Hash = existingUser.DigestHa1Hash;
newUser.CreatedDate = existingUser.CreatedDate;
newUser.ModifiedDate = DateTime.UtcNow;
using var session = documentStore.OpenSession();
session.Store(newUser);
session.SaveChanges();
return newUser;
}
private async Task AssertNoExistingUserAsync(IUserAuth newUser, IUserAuth exceptForExistingUser = null, CancellationToken token = default)
{
if (newUser.UserName != null)
{
var existingUser = await GetUserAuthByUserNameAsync(newUser.UserName, token).ConfigAwait();
if (existingUser != null
&& (exceptForExistingUser == null || existingUser.Id != exceptForExistingUser.Id))
throw new ArgumentException(string.Format(ErrorMessages.UserAlreadyExistsTemplate1, newUser.UserName.SafeInput()));
}
if (newUser.Email != null)
{
var existingUser = await GetUserAuthByUserNameAsync(newUser.Email, token).ConfigAwait();
if (existingUser != null
&& (exceptForExistingUser == null || existingUser.Id != exceptForExistingUser.Id))
throw new ArgumentException(string.Format(ErrorMessages.EmailAlreadyExistsTemplate1, newUser.Email.SafeInput()));
}
}
public async Task<IUserAuth> UpdateUserAuthAsync(IUserAuth existingUser, IUserAuth newUser, string password, CancellationToken token = default)
{
newUser.ValidateNewUser(password);
await AssertNoExistingUserAsync(newUser, existingUser, token).ConfigAwait();
UpdateKey(existingUser, newUser);
newUser.Id = existingUser.Id;
newUser.PopulatePasswordHashes(password, existingUser);
newUser.CreatedDate = existingUser.CreatedDate;
newUser.ModifiedDate = DateTime.UtcNow;
using var session = documentStore.OpenSession();
session.Store(newUser);
session.SaveChanges();
return newUser;
}
public async Task<IUserAuth> GetUserAuthByUserNameAsync(string userNameOrEmail, CancellationToken token = default)
{
if (userNameOrEmail == null)
return null;
using var session = documentStore.OpenSession();
var userAuth = await session.Query<UserAuth_By_UserNameOrEmail.Result, UserAuth_By_UserNameOrEmail>()
.Customize(x => x.WaitForNonStaleResults())
.Where(x => x.Search.Contains(userNameOrEmail))
.OfType<TUserAuth>()
.FirstOrDefaultAsync(token).ConfigAwait();
return userAuth;
}
public async Task<IUserAuth> TryAuthenticateAsync(string userName, string password, CancellationToken token = default)
{
var userAuth = await GetUserAuthByUserNameAsync(userName, token).ConfigAwait();
if (userAuth == null)
return null;
if (userAuth.VerifyPassword(password, out var needsRehash))
{
await this.RecordSuccessfulLoginAsync(userAuth, needsRehash, password, token).ConfigAwait();
return userAuth;
}
await this.RecordInvalidLoginAttemptAsync(userAuth, token).ConfigAwait();
return null;
}
public async Task<IUserAuth> TryAuthenticateAsync(Dictionary<string, string> digestHeaders, string privateKey, int nonceTimeOut, string sequence, CancellationToken token = default)
{
var userAuth = await GetUserAuthByUserNameAsync(digestHeaders["username"], token).ConfigAwait();
if (userAuth == null)
return null;
if (userAuth.VerifyDigestAuth(digestHeaders, privateKey, nonceTimeOut, sequence))
{
await this.RecordSuccessfulLoginAsync(userAuth, token).ConfigAwait();
return userAuth;
}
await this.RecordInvalidLoginAttemptAsync(userAuth, token).ConfigAwait();
return null;
}
public async Task LoadUserAuthAsync(IAuthSession session, IAuthTokens tokens, CancellationToken token = default)
{
if (session == null)
throw new ArgumentNullException(nameof(session));
var userAuth = await GetUserAuthAsync(session, tokens, token).ConfigAwait();
await LoadUserAuthAsync(session, (TUserAuth)userAuth, token).ConfigAwait();
}
private async Task LoadUserAuthAsync(IAuthSession session, TUserAuth userAuth, CancellationToken token = default)
{
UpdateSessionKey(session, userAuth);
await session.PopulateSessionAsync(userAuth, this, token).ConfigAwait();
}
public Task DeleteUserAuthAsync(string userAuthId, CancellationToken token = default)
{
using var session = documentStore.OpenSession();
var userAuth = session.Load<TUserAuth>(userAuthId);
session.Delete(userAuth);
var userAuthDetails = session.Query<UserAuth_By_UserAuthDetails.Result, UserAuth_By_UserAuthDetails>()
.Customize(x => x.WaitForNonStaleResults())
.Where(q => q.UserAuthId == userAuthId);
userAuthDetails.Each(session.Delete);
return TypeConstants.EmptyTask;
}
public Task<IUserAuth> GetUserAuthAsync(string userAuthId, CancellationToken token = default)
{
using var session = documentStore.OpenSession();
return (int.TryParse(userAuthId, out var intAuthId)
? (IUserAuth)session.Load<TUserAuth>(intAuthId)
: session.Load<TUserAuth>(userAuthId)).InTask();
}
public Task SaveUserAuthAsync(IAuthSession authSession, CancellationToken token = default)
{
using var session = documentStore.OpenSession();
int idInt = int.Parse(authSession.UserAuthId);
var userAuth = !authSession.UserAuthId.IsNullOrEmpty()
? session.Load<TUserAuth>(idInt)
: authSession.ConvertTo<TUserAuth>();
if (userAuth.Id == default && !authSession.UserAuthId.IsNullOrEmpty())
userAuth.Id = idInt;
userAuth.ModifiedDate = DateTime.UtcNow;
if (userAuth.CreatedDate == default)
userAuth.CreatedDate = userAuth.ModifiedDate;
session.Store(userAuth);
session.SaveChanges();
return TypeConstants.EmptyTask;
}
public Task SaveUserAuthAsync(IUserAuth userAuth, CancellationToken token = default)
{
using var session = documentStore.OpenSession();
userAuth.ModifiedDate = DateTime.UtcNow;
if (userAuth.CreatedDate == default)
userAuth.CreatedDate = userAuth.ModifiedDate;
session.Store(userAuth);
session.SaveChanges();
return TypeConstants.EmptyTask;
}
public async Task<List<IUserAuthDetails>> GetUserAuthDetailsAsync(string userAuthId, CancellationToken token = default)
{
using var session = documentStore.OpenSession();
return (await session.Query<UserAuth_By_UserAuthDetails.Result, UserAuth_By_UserAuthDetails>()
.Customize(x => x.WaitForNonStaleResults())
.Where(q => q.UserAuthId == userAuthId)
.OrderBy(x => x.ModifiedDate)
.OfType<TUserAuthDetails>()
.ToListAsync(token).ConfigAwait())
.ConvertAll(x => x as IUserAuthDetails);
}
public async Task<IUserAuth> GetUserAuthAsync(IAuthSession authSession, IAuthTokens tokens, CancellationToken token = default)
{
if (!authSession.UserAuthId.IsNullOrEmpty())
{
var userAuth = await GetUserAuthAsync(authSession.UserAuthId, token).ConfigAwait();
if (userAuth != null) return userAuth;
}
if (!authSession.UserAuthName.IsNullOrEmpty())
{
var userAuth = await GetUserAuthByUserNameAsync(authSession.UserAuthName, token).ConfigAwait();
if (userAuth != null) return userAuth;
}
if (tokens == null || tokens.Provider.IsNullOrEmpty() || tokens.UserId.IsNullOrEmpty())
return null;
using var session = documentStore.OpenSession();
var oAuthProvider = await session
.Query<UserAuth_By_UserAuthDetails.Result, UserAuth_By_UserAuthDetails>()
.Customize(x => x.WaitForNonStaleResults())
.Where(q => q.Provider == tokens.Provider && q.UserId == tokens.UserId)
.OfType<TUserAuthDetails>()
.FirstOrDefaultAsync(token).ConfigAwait();
if (oAuthProvider != null)
{
var userAuth = session.Load<TUserAuth>(oAuthProvider.UserAuthId);
return userAuth;
}
return null;
}
public async Task<IUserAuthDetails> CreateOrMergeAuthSessionAsync(IAuthSession authSession, IAuthTokens tokens, CancellationToken token = default)
{
var userAuth = await GetUserAuthAsync(authSession, tokens, token)
?? typeof(TUserAuth).CreateInstance<TUserAuth>();
using var session = documentStore.OpenSession();
var authDetails = await session
.Query<UserAuth_By_UserAuthDetails.Result, UserAuth_By_UserAuthDetails>()
.Customize(x => x.WaitForNonStaleResults())
.Where(q => q.Provider == tokens.Provider && q.UserId == tokens.UserId)
.OfType<TUserAuthDetails>()
.FirstOrDefaultAsync(token).ConfigAwait();
if (authDetails == null)
{
authDetails = typeof(TUserAuthDetails).CreateInstance<TUserAuthDetails>();
authDetails.Provider = tokens.Provider;
authDetails.UserId = tokens.UserId;
}
authDetails.PopulateMissing(tokens);
userAuth.PopulateMissingExtended(authDetails);
userAuth.ModifiedDate = DateTime.UtcNow;
if (userAuth.CreatedDate == default)
userAuth.CreatedDate = userAuth.ModifiedDate;
session.Store(userAuth);
session.SaveChanges();
var key = (string)UserAuthKeyProp.PublicGetter(userAuth);
if (userAuth.Id == default)
{
userAuth.Id = RavenDbUserAuthRepository.ParseIntId(key);
}
authDetails.UserAuthId = userAuth.Id; // Partial FK int Id
authDetails.RefIdStr = key; // FK
if (authDetails.CreatedDate == default)
authDetails.CreatedDate = userAuth.ModifiedDate;
authDetails.ModifiedDate = userAuth.ModifiedDate;
session.Store(authDetails);
session.SaveChanges();
return authDetails;
}
public Task<List<IUserAuth>> GetUserAuthsAsync(string orderBy = null, int? skip = null, int? take = null, CancellationToken token = default)
{
using var session = documentStore.OpenSession();
var q = session.Query<TUserAuth>();
return SortAndPage(q, orderBy, skip, take).OfType<IUserAuth>().ToList().InTask();
}
public async Task<List<IUserAuth>> SearchUserAuthsAsync(string query, string orderBy = null, int? skip = null, int? take = null, CancellationToken token = default)
{
if (string.IsNullOrEmpty(query))
return await GetUserAuthsAsync(orderBy, skip, take, token).ConfigAwait();
using var session = documentStore.OpenSession();
// RavenDB cant query string Contains/IndexOf
var q = session.Query<TUserAuth>()
.Where(x => x.UserName.StartsWith(query) || x.UserName.EndsWith(query) ||
x.Email.StartsWith(query) || x.Email.EndsWith(query))
.Customize(x => x.WaitForNonStaleResults());
return SortAndPage(q, orderBy, skip, take).OfType<IUserAuth>().ToList();
}
}
}