12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- using System;
- using System.Security.Cryptography;
- using Luticate2.Auth.DataAccess;
- using Luticate2.Auth.Dbo.Tokens;
- using Luticate2.Auth.Dbo.Users;
- using Luticate2.Auth.Interfaces.Tokens;
- using Luticate2.Utils.Business;
- using Luticate2.Utils.Dbo.Result;
- using Luticate2.Utils.Interfaces;
- using Luticate2.Utils.Utils;
-
- namespace Luticate2.Auth.Business
- {
- public class LuTokensBusiness : LuCrudBusiness<LuTokensDataAccess, LuTokensAddDbo, LuTokensDbo, LuTokensEditDbo, string>, ILuTokensBusiness
- {
- private readonly IDateTime _dateTime;
-
- public LuTokensBusiness(LuTokensDataAccess dataAccess, ILuNotificationsBusiness notificationsBusiness, IDateTime dateTime) : base(dataAccess, notificationsBusiness)
- {
- _dateTime = dateTime;
- }
-
- public LuResult<LuUsersToken> GetToken(string token)
- {
- return GetSingleById(token).To(dbo => dbo.ToUserToken());
- }
-
- public string GenerateId()
- {
- var token = new byte[50];
- using (var rng = RandomNumberGenerator.Create())
- {
- rng.GetBytes(token);
- }
- return Convert.ToBase64String(token).Trim('=');
- }
-
- public LuResult<string> RegisterToken(LuUsersToken token)
- {
- string id;
- LuResult<LuTokensDbo> tokenRes;
- do
- {
- id = GenerateId();
- tokenRes = GetSingleById(id);
- } while (tokenRes);
-
- if (tokenRes.Status != LuStatus.NotFound)
- {
- return tokenRes.To<string>();
- }
-
- return this.AddId(new LuTokensAddDbo
- {
- Data = token.Data,
- Id = id,
- NotAfter = token.NotAfter,
- NotBefore = token.NotBefore,
- UserId = token.UserId
- });
- }
-
- public LuResult<LuUsersToken> UnRegisterToken(string token)
- {
- return this.DeleteSingleByIdDbo(token).To(dbo => dbo.ToUserToken());
- }
-
- public bool IsTokenValid(LuUsersToken token)
- {
- var now = _dateTime.Now;
- return (token.NotBefore == null || now >= token.NotBefore) &&
- (token.NotAfter == null || now <= token.NotAfter);
- }
-
- public LuResult<string> GenerateToken(LuUsersDbo user)
- {
- var token = new LuUsersToken
- {
- Data = null,//TODO
- NotAfter = null,
- NotBefore = null,
- UserId = user.Id
- };
-
- return RegisterToken(token);
- }
- }
- }
|