-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
UserAuth.cs
592 lines (512 loc) · 23.5 KB
/
UserAuth.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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
using System;
using System.Collections.Generic;
using System.Security.Claims;
using ServiceStack.DataAnnotations;
using ServiceStack.Text;
namespace ServiceStack.Auth
{
public class UserAuth : IUserAuth
{
[AutoIncrement]
public virtual int Id { get; set; }
[Index]
public virtual string UserName { get; set; }
[Index]
public virtual string Email { get; set; }
public virtual string PrimaryEmail { get; set; }
public virtual string PhoneNumber { get; set; }
public virtual string FirstName { get; set; }
public virtual string LastName { get; set; }
public virtual string DisplayName { get; set; }
public virtual string Company { get; set; }
public virtual DateTime? BirthDate { get; set; }
public virtual string BirthDateRaw { get; set; }
public virtual string Address { get; set; }
public virtual string Address2 { get; set; }
public virtual string City { get; set; }
public virtual string State { get; set; }
public virtual string Country { get; set; }
public virtual string Culture { get; set; }
public virtual string FullName { get; set; }
public virtual string Gender { get; set; }
public virtual string Language { get; set; }
public virtual string MailAddress { get; set; }
public virtual string Nickname { get; set; }
public virtual string PostalCode { get; set; }
public virtual string TimeZone { get; set; }
public virtual string Salt { get; set; }
public virtual string PasswordHash { get; set; }
public virtual string DigestHa1Hash { get; set; }
public virtual List<string> Roles { get; set; } = new List<string>();
public virtual List<string> Permissions { get; set; } = new List<string>();
public virtual DateTime CreatedDate { get; set; }
public virtual DateTime ModifiedDate { get; set; }
public virtual int InvalidLoginAttempts { get; set; }
public virtual DateTime? LastLoginAttempt { get; set; }
public virtual DateTime? LockedDate { get; set; }
public virtual string RecoveryToken { get; set; }
//Custom Reference Data
public virtual int? RefId { get; set; }
public virtual string RefIdStr { get; set; }
public virtual Dictionary<string, string> Meta { get; set; }
}
public class UserAuthDetails : IUserAuthDetails
{
[AutoIncrement]
public virtual int Id { get; set; }
public virtual int UserAuthId { get; set; }
public virtual string Provider { get; set; }
public virtual string UserId { get; set; }
public virtual string UserName { get; set; }
public virtual string FullName { get; set; }
public virtual string DisplayName { get; set; }
public virtual string FirstName { get; set; }
public virtual string LastName { get; set; }
public virtual string Company { get; set; }
public virtual string Email { get; set; }
public virtual string PhoneNumber { get; set; }
public virtual DateTime? BirthDate { get; set; }
public virtual string BirthDateRaw { get; set; }
public virtual string Address { get; set; }
public virtual string Address2 { get; set; }
public virtual string City { get; set; }
public virtual string State { get; set; }
public virtual string Country { get; set; }
public virtual string Culture { get; set; }
public virtual string Gender { get; set; }
public virtual string Language { get; set; }
public virtual string MailAddress { get; set; }
public virtual string Nickname { get; set; }
public virtual string PostalCode { get; set; }
public virtual string TimeZone { get; set; }
public virtual string RefreshToken { get; set; }
public virtual DateTime? RefreshTokenExpiry { get; set; }
public virtual string RequestToken { get; set; }
public virtual string RequestTokenSecret { get; set; }
public virtual Dictionary<string, string> Items { get; set; } = new Dictionary<string, string>();
public virtual string AccessToken { get; set; }
public virtual string AccessTokenSecret { get; set; }
public virtual DateTime CreatedDate { get; set; }
public virtual DateTime ModifiedDate { get; set; }
//Custom Reference Data
public virtual int? RefId { get; set; }
public virtual string RefIdStr { get; set; }
public virtual Dictionary<string, string> Meta { get; set; }
}
public class UserAuthRole
{
[AutoIncrement]
public virtual int Id { get; set; }
public virtual int UserAuthId { get; set; }
public virtual string Role { get; set; }
public virtual string Permission { get; set; }
public virtual DateTime CreatedDate { get; set; }
public virtual DateTime ModifiedDate { get; set; }
//Custom Reference Data
public virtual int? RefId { get; set; }
public virtual string RefIdStr { get; set; }
public virtual Dictionary<string, string> Meta { get; set; }
}
public static class UserAuthExtensions
{
public static void PopulateMissing(this IUserAuthDetails instance, IAuthTokens tokens, bool overwriteReserved = false)
{
if (instance == null)
throw new ArgumentNullException(nameof(instance));
if (tokens == null)
throw new ArgumentNullException(nameof(tokens));
if (!tokens.UserId.IsNullOrEmpty())
instance.UserId = tokens.UserId;
if (!tokens.RefreshToken.IsNullOrEmpty())
instance.RefreshToken = tokens.RefreshToken;
if (tokens.RefreshTokenExpiry.HasValue)
instance.RefreshTokenExpiry = tokens.RefreshTokenExpiry;
if (!tokens.RequestToken.IsNullOrEmpty())
instance.RequestToken = tokens.RequestToken;
if (!tokens.RequestTokenSecret.IsNullOrEmpty())
instance.RequestTokenSecret = tokens.RequestTokenSecret;
if (!tokens.AccessToken.IsNullOrEmpty())
instance.AccessToken = tokens.AccessToken;
if (!tokens.AccessTokenSecret.IsNullOrEmpty())
instance.AccessTokenSecret = tokens.AccessTokenSecret;
if (tokens.Items != null)
{
if (instance.Items == null)
instance.Items = new Dictionary<string, string>();
if (instance.Items != tokens.Items)
{
foreach (var entry in tokens.Items)
{
instance.Items[entry.Key] = entry.Value;
}
}
}
PopulateMissingExtended(instance, tokens, overwriteReserved);
}
public static void PopulateMissingExtended(this IUserAuthDetailsExtended instance,
IUserAuthDetailsExtended other, bool overwriteReserved = false)
{
if (instance == null)
throw new ArgumentNullException(nameof(instance));
if (other == null)
throw new ArgumentNullException(nameof(other));
// Don't override the Master UserAuth table's reserved fields if they already exists
if (!other.UserName.IsNullOrEmpty() && (overwriteReserved || instance.UserName.IsNullOrEmpty()))
instance.UserName = other.UserName;
if (!other.DisplayName.IsNullOrEmpty() && (overwriteReserved || instance.DisplayName.IsNullOrEmpty()))
instance.DisplayName = other.DisplayName;
if (!other.Email.IsNullOrEmpty() && (overwriteReserved || instance.Email.IsNullOrEmpty()))
instance.Email = other.Email;
if (instance is IUserAuth userAuth)
{
if (!other.Email.IsNullOrEmpty() && (overwriteReserved || userAuth.PrimaryEmail.IsNullOrEmpty()))
userAuth.PrimaryEmail = other.Email;
}
if (!other.PhoneNumber.IsNullOrEmpty())
instance.PhoneNumber = other.PhoneNumber;
if (!other.FirstName.IsNullOrEmpty())
instance.FirstName = other.FirstName;
if (!other.LastName.IsNullOrEmpty())
instance.LastName = other.LastName;
if (!other.FullName.IsNullOrEmpty())
instance.FullName = other.FullName;
if (!other.Company.IsNullOrEmpty())
instance.Company = other.Company;
if (other.BirthDate != null)
instance.BirthDate = other.BirthDate;
if (!other.BirthDateRaw.IsNullOrEmpty())
instance.BirthDateRaw = other.BirthDateRaw;
if (!other.Address.IsNullOrEmpty())
instance.Address = other.Address;
if (!other.Address2.IsNullOrEmpty())
instance.Address2 = other.Address2;
if (!other.City.IsNullOrEmpty())
instance.City = other.City;
if (!other.State.IsNullOrEmpty())
instance.State = other.State;
if (!other.Country.IsNullOrEmpty())
instance.Country = other.Country;
if (!other.Culture.IsNullOrEmpty())
instance.Culture = other.Culture;
if (!other.Gender.IsNullOrEmpty())
instance.Gender = other.Gender;
if (!other.MailAddress.IsNullOrEmpty())
instance.MailAddress = other.MailAddress;
if (!other.Nickname.IsNullOrEmpty())
instance.Nickname = other.Nickname;
if (!other.PostalCode.IsNullOrEmpty())
instance.PostalCode = other.PostalCode;
if (!other.TimeZone.IsNullOrEmpty())
instance.TimeZone = other.TimeZone;
}
public static T Get<T>(this IMeta instance)
{
if (instance == null)
throw new ArgumentNullException(nameof(instance));
if (instance.Meta == null)
return default(T);
string str;
instance.Meta.TryGetValue(typeof(T).GetOperationName(), out str);
return str == null ? default(T) : TypeSerializer.DeserializeFromString<T>(str);
}
public static bool TryGet<T>(this IMeta instance, out T value)
{
value = default(T);
if (instance == null)
throw new ArgumentNullException(nameof(instance));
string str;
if (!instance.Meta.TryGetValue(typeof(T).GetOperationName(), out str))
return false;
value = TypeSerializer.DeserializeFromString<T>(str);
return true;
}
public static T Set<T>(this IMeta instance, T value)
{
if (instance == null)
throw new ArgumentNullException(nameof(instance));
if (instance.Meta == null)
instance.Meta = new Dictionary<string, string>();
instance.Meta[typeof(T).GetOperationName()] = TypeSerializer.SerializeToString(value);
return value;
}
public static AuthTokens ToAuthTokens(this IAuthTokens from)
{
return new AuthTokens {
Provider = from.Provider,
UserId = from.UserId,
AccessToken = from.AccessToken,
AccessTokenSecret = from.AccessTokenSecret,
RefreshToken = from.RefreshToken,
RefreshTokenExpiry = from.RefreshTokenExpiry,
RequestToken = from.RequestToken,
RequestTokenSecret = from.RequestTokenSecret,
Items = from.Items,
};
}
public static void RecordSuccessfulLogin(this IUserAuthRepository repo, IUserAuth userAuth)
{
repo.RecordSuccessfulLogin(userAuth, rehashPassword:false, password:null);
}
public static void RecordSuccessfulLogin(this IUserAuthRepository repo, IUserAuth userAuth, bool rehashPassword, string password)
{
var recordLoginAttempts = HostContext.GetPlugin<AuthFeature>()?.MaxLoginAttempts != null;
if (recordLoginAttempts)
{
userAuth.InvalidLoginAttempts = 0;
userAuth.LastLoginAttempt = userAuth.ModifiedDate = DateTime.UtcNow;
}
if (rehashPassword)
{
userAuth.PopulatePasswordHashes(password);
}
if (recordLoginAttempts || rehashPassword)
{
repo.SaveUserAuth(userAuth);
}
}
public static void RecordInvalidLoginAttempt(this IUserAuthRepository repo, IUserAuth userAuth)
{
var feature = HostContext.GetPlugin<AuthFeature>();
if (feature?.MaxLoginAttempts == null) return;
userAuth.InvalidLoginAttempts += 1;
userAuth.LastLoginAttempt = userAuth.ModifiedDate = DateTime.UtcNow;
if (userAuth.InvalidLoginAttempts >= feature.MaxLoginAttempts.Value)
{
userAuth.LockedDate = userAuth.LastLoginAttempt;
}
repo.SaveUserAuth(userAuth);
}
public static void PopulateFromMap(this IAuthSession session, Dictionary<string, string> map)
{
var authSession = session as AuthUserSession ?? new AuthUserSession(); //Null Object Pattern
session.IsAuthenticated = true;
session.FromToken = true;
foreach (var entry in map)
{
switch (entry.Key)
{
case "jid":
case "Id":
session.Id = entry.Value;
break;
case "IsAuthenticated":
session.IsAuthenticated = entry.Value.FromJsv<bool>();
break;
case "FromToken":
session.FromToken = entry.Value.FromJsv<bool>();
break;
case "sub":
session.UserAuthId = entry.Value.LastRightPart('|'); //in-case of multi-components, last should contain userId
break;
case "UserAuthId":
session.UserAuthId = entry.Value;
break;
case "email":
case "Email":
session.Email = entry.Value;
break;
case "UserName":
case "preferred_username":
session.UserName = entry.Value;
break;
case "name":
case "DisplayName":
session.DisplayName = entry.Value;
break;
case "picture":
case "ProfileUrl":
session.ProfileUrl = entry.Value;
break;
case "roles":
case "Roles":
session.Roles = entry.Value.FromJson<List<string>>();
break;
case "perms":
case "Permissions":
session.Permissions = entry.Value.FromJson<List<string>>();
break;
case "iat":
case "CreatedAt":
session.CreatedAt = long.Parse(entry.Value).FromUnixTime();
break;
case "ReferrerUrl":
session.ReferrerUrl = entry.Value;
break;
case "UserAuthName":
session.UserAuthName = entry.Value;
break;
case "TwitterUserId":
authSession.TwitterUserId = entry.Value;
break;
case "TwitterScreenName":
authSession.TwitterScreenName = entry.Value;
break;
case "FacebookUserId":
authSession.FacebookUserId = entry.Value;
break;
case "FacebookUserName":
authSession.FacebookUserName = entry.Value;
break;
case "given_name":
case "GivenName":
case "FirstName":
session.FirstName = entry.Value;
break;
case "family_name":
case "Surname":
case "LastName":
session.LastName = entry.Value;
break;
case "Company":
authSession.Company = entry.Value;
break;
case "PrimaryEmail":
authSession.PrimaryEmail = entry.Value;
break;
case "PhoneNumber":
authSession.PhoneNumber = entry.Value;
break;
case "BirthDate":
authSession.BirthDate = long.Parse(entry.Value).FromUnixTime();
break;
case "Address":
authSession.Address = entry.Value;
break;
case "Address2":
authSession.Address2 = entry.Value;
break;
case "City":
authSession.City = entry.Value;
break;
case "State":
authSession.State = entry.Value;
break;
case "Country":
authSession.Country = entry.Value;
break;
case "Culture":
authSession.Culture = entry.Value;
break;
case "FullName":
authSession.FullName = entry.Value;
break;
case "Gender":
authSession.Gender = entry.Value;
break;
case "Language":
authSession.Language = entry.Value;
break;
case "MailAddress":
authSession.MailAddress = entry.Value;
break;
case "Nickname":
authSession.Nickname = entry.Value;
break;
case "PostalCode":
authSession.PostalCode = entry.Value;
break;
case "TimeZone":
authSession.TimeZone = entry.Value;
break;
case "RequestTokenSecret":
authSession.RequestTokenSecret = entry.Value;
break;
case "LastModified":
session.LastModified = long.Parse(entry.Value).FromUnixTime();
break;
case "Sequence":
session.Sequence = entry.Value;
break;
case "Tag":
authSession.Tag = long.Parse(entry.Value);
break;
case "Dns":
authSession.Dns = entry.Value;
break;
case "Rsa":
authSession.Rsa = entry.Value;
break;
case "Sid":
authSession.Sid = entry.Value;
break;
case "Hash":
authSession.Hash = entry.Value;
break;
case "HomePhone":
authSession.HomePhone = entry.Value;
break;
case "MobilePhone":
authSession.MobilePhone = entry.Value;
break;
case "Webpage":
authSession.Webpage = entry.Value;
break;
case "EmailConfirmed":
authSession.EmailConfirmed = entry.Value.FromJsv<bool>();
break;
case "PhoneNumberConfirmed":
authSession.PhoneNumberConfirmed = entry.Value.FromJsv<bool>();
break;
case "TwoFactorEnabled":
authSession.TwoFactorEnabled = entry.Value.FromJsv<bool>();
break;
case "SecurityStamp":
authSession.SecurityStamp = entry.Value;
break;
}
}
}
public static List<Claim> ConvertSessionToClaims(this IAuthSession session,
string issuer = null, string roleClaimType=ClaimTypes.Role, string permissionClaimType="perm")
{
var claims = new List<Claim>();
void addClaim(string type, string value)
{
if (value == null)
return;
claims.Add(new Claim(type, value, ClaimValueTypes.String, issuer));
}
addClaim(ClaimTypes.NameIdentifier, session.Id);
addClaim(ClaimTypes.Email, session.Email);
addClaim(ClaimTypes.Name, session.UserAuthName);
addClaim(ClaimTypes.GivenName, session.FirstName);
addClaim(ClaimTypes.Surname, session.LastName);
addClaim(ClaimTypes.AuthenticationMethod, session.AuthProvider);
if (session is IAuthSessionExtended sessionExt)
{
addClaim(ClaimTypes.StreetAddress, sessionExt.Address);
addClaim(ClaimTypes.Locality, sessionExt.City);
addClaim(ClaimTypes.StateOrProvince, sessionExt.State);
addClaim(ClaimTypes.PostalCode, sessionExt.PostalCode);
addClaim(ClaimTypes.Country, sessionExt.Country);
addClaim(ClaimTypes.HomePhone, sessionExt.HomePhone);
addClaim(ClaimTypes.MobilePhone, sessionExt.MobilePhone);
addClaim(ClaimTypes.DateOfBirth, sessionExt.BirthDateRaw ?? sessionExt.BirthDate?.ToShortDateString());
addClaim(ClaimTypes.Gender, sessionExt.Gender);
addClaim(ClaimTypes.Dns, sessionExt.Dns);
addClaim(ClaimTypes.Rsa, sessionExt.Rsa);
addClaim(ClaimTypes.Sid, sessionExt.Sid);
addClaim(ClaimTypes.Hash, sessionExt.Hash);
addClaim(ClaimTypes.HomePhone, sessionExt.HomePhone);
addClaim(ClaimTypes.MobilePhone, sessionExt.MobilePhone);
addClaim(ClaimTypes.OtherPhone, sessionExt.PhoneNumber);
addClaim(ClaimTypes.Webpage, sessionExt.Webpage);
}
if (session.Roles != null)
{
foreach (var role in session.Roles)
{
addClaim(roleClaimType, role);
}
}
if (session.Permissions != null)
{
foreach (var permission in session.Permissions)
{
addClaim(permissionClaimType, permission);
}
}
return claims;
}
}
}