using NetworkResurrector.Application.Stores; using NetworkResurrector.Domain.Entities; using NetworkResurrector.Domain.Models; using NetworkResurrector.Domain.Services; using System; using System.Linq; using System.Threading.Tasks; namespace NetworkResurrector.Application.Services { public interface IUserService { Task Login(string userName, string password); Task Authenticate(string token); } public class UserService : IUserService { private readonly IParamProvider _paramProvider; private readonly ISecurityStore _securityStore; public UserService(IParamProvider paramProvider, ISecurityStore securityStore) { _paramProvider = paramProvider; _securityStore = securityStore; } public async Task Login(string userName, string password) { var user = _paramProvider.Users.FirstOrDefault(z => z.UserName == userName && z.Password == password); if (user == null) return null; var token = $"{Guid.NewGuid()}-{Guid.NewGuid()}-{user.UserId}"; await Task.Run(() =>_securityStore.SetToken(token, user.UserId)); var securityToken = new SecurityToken() { UserId = user.UserId, Token = token }; return securityToken; } public async Task Authenticate(string token) { var tokenValidation = await Task.Run(() => _securityStore.ValidateToken(token)); if (tokenValidation.Success) { var user = _paramProvider.Users.FirstOrDefault(z => z.UserId == tokenValidation.UserId); if (user != null) return user; } return null; } } }