Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. using System;
  2. using System.Security.Cryptography;
  3. using System.Text;
  4. using Luticate2.Auth.DataAccess;
  5. using Luticate2.Auth.Dbo.Users;
  6. using Luticate2.Auth.Interfaces.Tokens;
  7. using Luticate2.Auth.Interfaces.Users;
  8. using Luticate2.Utils.Business;
  9. using Luticate2.Utils.Dbo.Basic;
  10. using Luticate2.Utils.Dbo.PaginatedRequest;
  11. using Luticate2.Utils.Dbo.Result;
  12. using Luticate2.Utils.Interfaces;
  13. using Luticate2.Utils.Utils;
  14. using Microsoft.AspNetCore.Cryptography.KeyDerivation;
  15. namespace Luticate2.Auth.Business
  16. {
  17. public class LuUsersBusiness : LuCrudBusiness<LuUsersDataAccess, LuUsersAddFullDbo, LuUsersFullDbo, LuUsersEditFullDbo, string>, ILuUsersBusiness
  18. {
  19. private readonly ILuTokensBusiness _luTokensBusiness;
  20. private readonly ILuLoggedUserAccessor _luLoggedUserAccessor;
  21. public LuUsersBusiness(LuUsersDataAccess dataAccess, IServiceProvider serviceProvider,
  22. ILuTokensBusiness luTokensBusiness, ILuLoggedUserAccessor luLoggedUserAccessor) : base(dataAccess, serviceProvider)
  23. {
  24. _luTokensBusiness = luTokensBusiness;
  25. _luLoggedUserAccessor = luLoggedUserAccessor;
  26. }
  27. public string GenerateSalt()
  28. {
  29. var salt = new byte[128 / 8];
  30. using (var rng = RandomNumberGenerator.Create())
  31. {
  32. rng.GetBytes(salt);
  33. }
  34. return Convert.ToBase64String(salt);
  35. }
  36. public string HashPassword(string password, string salt)
  37. {
  38. var hashed = Convert.ToBase64String(KeyDerivation.Pbkdf2(password, Encoding.ASCII.GetBytes(salt),
  39. KeyDerivationPrf.HMACSHA1, 10000, 256 / 8));
  40. return hashed;
  41. }
  42. public bool VerifyPasswordHash(string password, string hash, string salt)
  43. {
  44. var newHash = HashPassword(password, salt);
  45. return newHash == hash;
  46. }
  47. public LuResult<LuUsersFullDbo> FindByUsername(string username)
  48. {
  49. return DataAccess.FindByUsername(username);
  50. }
  51. public LuResult<LuUsersFullDbo> Register(LuUsersAddDbo user)
  52. {
  53. var userRes = FindByUsername(user.Username);
  54. if (userRes)
  55. {
  56. return LuResult<LuUsersFullDbo>.Error(LuStatus.InputError,
  57. $"username: {user.Username}", "Username already exists");
  58. }
  59. if (userRes.Status != LuStatus.NotFound)
  60. {
  61. return userRes;
  62. }
  63. var salt = GenerateSalt();
  64. var password = HashPassword(user.Password, salt);
  65. return this.AddDbo(new LuUsersAddFullDbo
  66. {
  67. AuthenticationSourceId = Guid.Empty.ToDbo(),
  68. Data = null,
  69. Password = password,
  70. Salt = salt,
  71. Username = user.Username
  72. });
  73. }
  74. public LuResult<LuUsersFullDbo> Edit(string id, LuUsersEditDbo user)
  75. {
  76. throw new NotImplementedException();
  77. }
  78. public LuResult<LuUsersLoginResultDbo> Login(string username, string password)
  79. {
  80. var userRes = FindByUsername(username);
  81. if (userRes.Status == LuStatus.NotFound)
  82. {
  83. return LuResult<LuUsersLoginResultDbo>.Error(LuStatus.LoginError,
  84. $"unknown username; username: {username}", "Invalid username or password");
  85. }
  86. if (!userRes)
  87. {
  88. return userRes.To<LuUsersLoginResultDbo>();
  89. }
  90. if (userRes.Data.Password == null)
  91. {
  92. return LuResult<LuUsersLoginResultDbo>.Error(LuStatus.LoginError,
  93. $"null password; username: {username}", "Invalid username or password");
  94. }
  95. if (!VerifyPasswordHash(password, userRes.Data.Password, userRes.Data.Salt))
  96. {
  97. return LuResult<LuUsersLoginResultDbo>.Error(LuStatus.LoginError,
  98. $"invalid password; username: {username}", "Invalid username or password");
  99. }
  100. var tokenRes = _luTokensBusiness.GenerateToken(userRes.Data.ToLite());
  101. if (!tokenRes)
  102. {
  103. return tokenRes.To<LuUsersLoginResultDbo>();
  104. }
  105. return LuResult<LuUsersLoginResultDbo>.Ok(new LuUsersLoginResultDbo
  106. {
  107. Token = tokenRes.Data,
  108. User = userRes.Data.ToLite()
  109. });
  110. }
  111. public LuResult<bool> Logout(string token)
  112. {
  113. if (token == null)
  114. {
  115. return LuResult<bool>.Ok(true);
  116. }
  117. return _luTokensBusiness.UnRegisterToken(token).To(usersToken => true);
  118. }
  119. public LuResult<LuUsersFullDbo> Me()
  120. {
  121. return LuResult<LuUsersFullDbo>.Ok(_luLoggedUserAccessor.GetLoggedUser());
  122. }
  123. LuResult<T> ILuCrudInterface<LuUsersAddFullDbo, LuUsersFullDbo, LuUsersEditFullDbo, string>.DeleteSingleById<T>(string id, Func<LuUsersFullDbo, T> returnFunc)
  124. {
  125. var loggedUser = _luLoggedUserAccessor.GetLoggedUser();
  126. if (id == Guid.Empty.ToDbo())
  127. {
  128. return LuResult<T>.Error(LuStatus.InputError,
  129. $"loggedUser: {loggedUser.Username}", "Can not remove anonymous user");
  130. }
  131. if (id == loggedUser.Id)
  132. {
  133. return LuResult<T>.Error(LuStatus.InputError,
  134. $"loggedUser: {loggedUser.Username}", "Can not remove yourself");
  135. }
  136. return base.DeleteSingleById(id, returnFunc);
  137. }
  138. public LuResult<LuPaginatedDbo<LuUsersTokenDbo>> Sessions(LuPaginatedRequestDbo paginatedRequestDbo)
  139. {
  140. return _luTokensBusiness.GetTokensForUser(_luLoggedUserAccessor.GetLoggedUser().ToLite(), paginatedRequestDbo);
  141. }
  142. }
  143. }