123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105 |
- using System;
- using System.Linq;
- 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.Basic;
- using Luticate2.Utils.Dbo.PaginatedRequest;
- 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, IServiceProvider serviceProvider, IDateTime dateTime) : base(dataAccess, serviceProvider)
- {
- _dateTime = dateTime;
- }
-
- public LuResult<LuUsersTokenDbo> GetToken(string token)
- {
- return GetSingleById(token).To(dbo => dbo.ToUserToken());
- }
-
- public string GenerateId()//TODO
- {
- var token = new byte[50];
- using (var rng = RandomNumberGenerator.Create())
- {
- rng.GetBytes(token);
- }
- return Convert.ToBase64String(token).Trim('=');
- }
-
- public LuResult<string> RegisterToken(LuUsersTokenDbo 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<LuUsersTokenDbo> UnRegisterToken(string token)
- {
- return this.DeleteSingleByIdDbo(token).To(dbo => dbo.ToUserToken());
- }
-
- public bool IsTokenValid(LuUsersTokenDbo 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 LuUsersTokenDbo
- {
- Data = null,//TODO
- NotAfter = null,
- NotBefore = null,
- UserId = user.Id
- };
-
- return RegisterToken(token);
- }
-
- public LuResult<LuPaginatedDbo<LuUsersTokenDbo>> GetTokensForUser(LuUsersDbo user, LuPaginatedRequestDbo paginatedRequestDbo)
- {
- if (paginatedRequestDbo.Filter.Filters.ContainsKey("userId"))
- {
- paginatedRequestDbo.Filter.Filters["userId"] = user.Id;
- }
- else
- {
- paginatedRequestDbo.Filter.Filters.Add("userId", user.Id);
- }
- return GetMultiple(paginatedRequestDbo)
- .To(dbo => dbo.To(dbos => dbos.Select(tokensDbo => tokensDbo.ToUserToken()).ToList()));
- }
- }
- }
|