You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

LuTokensBusiness.cs 2.7KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using System;
  2. using System.Security.Cryptography;
  3. using Luticate2.Auth.DataAccess;
  4. using Luticate2.Auth.Dbo.Tokens;
  5. using Luticate2.Auth.Dbo.Users;
  6. using Luticate2.Auth.Interfaces.Tokens;
  7. using Luticate2.Utils.Business;
  8. using Luticate2.Utils.Dbo.Result;
  9. using Luticate2.Utils.Interfaces;
  10. using Luticate2.Utils.Utils;
  11. namespace Luticate2.Auth.Business
  12. {
  13. public class LuTokensBusiness : LuCrudBusiness<LuTokensDataAccess, LuTokensAddDbo, LuTokensDbo, LuTokensEditDbo, string>, ILuTokensBusiness
  14. {
  15. private readonly IDateTime _dateTime;
  16. public LuTokensBusiness(LuTokensDataAccess dataAccess, ILuNotificationsBusiness notificationsBusiness, IDateTime dateTime) : base(dataAccess, notificationsBusiness)
  17. {
  18. _dateTime = dateTime;
  19. }
  20. public LuResult<LuUsersToken> GetToken(string token)
  21. {
  22. return GetSingleById(token).To(dbo => dbo.ToUserToken());
  23. }
  24. public string GenerateId()
  25. {
  26. var token = new byte[50];
  27. using (var rng = RandomNumberGenerator.Create())
  28. {
  29. rng.GetBytes(token);
  30. }
  31. return Convert.ToBase64String(token).Trim('=');
  32. }
  33. public LuResult<string> RegisterToken(LuUsersToken token)
  34. {
  35. string id;
  36. LuResult<LuTokensDbo> tokenRes;
  37. do
  38. {
  39. id = GenerateId();
  40. tokenRes = GetSingleById(id);
  41. } while (tokenRes);
  42. if (tokenRes.Status != LuStatus.NotFound)
  43. {
  44. return tokenRes.To<string>();
  45. }
  46. return this.AddId(new LuTokensAddDbo
  47. {
  48. Data = token.Data,
  49. Id = id,
  50. NotAfter = token.NotAfter,
  51. NotBefore = token.NotBefore,
  52. UserId = token.UserId
  53. });
  54. }
  55. public LuResult<LuUsersToken> UnRegisterToken(string token)
  56. {
  57. return this.DeleteSingleByIdDbo(token).To(dbo => dbo.ToUserToken());
  58. }
  59. public bool IsTokenValid(LuUsersToken token)
  60. {
  61. var now = _dateTime.Now;
  62. return (token.NotBefore == null || now >= token.NotBefore) &&
  63. (token.NotAfter == null || now <= token.NotAfter);
  64. }
  65. public LuResult<string> GenerateToken(LuUsersDbo user)
  66. {
  67. var token = new LuUsersToken
  68. {
  69. Data = null,//TODO
  70. NotAfter = null,
  71. NotBefore = null,
  72. UserId = user.Id
  73. };
  74. return RegisterToken(token);
  75. }
  76. }
  77. }