network-resurrector/NetworkResurrector.Application/Services/UserService.cs

55 lines
1.8 KiB
C#
Raw Normal View History

2020-07-10 00:29:39 +03:00
using NetworkResurrector.Application.Stores;
using NetworkResurrector.Domain.Entities;
using NetworkResurrector.Domain.Models;
using NetworkResurrector.Domain.Services;
2020-07-10 00:29:39 +03:00
using System;
using System.Linq;
using System.Threading.Tasks;
namespace NetworkResurrector.Application.Services
{
public interface IUserService
{
2020-07-10 00:29:39 +03:00
Task<SecurityToken> Login(string userName, string password);
Task<User> Authenticate(string token);
}
public class UserService : IUserService
{
private readonly IParamProvider _paramProvider;
2020-07-10 00:29:39 +03:00
private readonly ISecurityStore _securityStore;
2020-07-10 00:29:39 +03:00
public UserService(IParamProvider paramProvider, ISecurityStore securityStore)
{
_paramProvider = paramProvider;
2020-07-10 00:29:39 +03:00
_securityStore = securityStore;
}
2020-07-10 00:29:39 +03:00
public async Task<SecurityToken> Login(string userName, string password)
{
2020-07-10 00:29:39 +03:00
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}";
2020-11-28 23:48:29 +02:00
await Task.Run(() =>_securityStore.SetToken(token, user.UserId));
2020-07-10 00:29:39 +03:00
var securityToken = new SecurityToken() { UserId = user.UserId, Token = token };
return securityToken;
}
2020-07-10 00:29:39 +03:00
public async Task<User> Authenticate(string token)
{
2020-11-28 23:48:29 +02:00
var tokenValidation = await Task.Run(() => _securityStore.ValidateToken(token));
2020-07-10 00:29:39 +03:00
if (tokenValidation.Success)
{
var user = _paramProvider.Users.FirstOrDefault(z => z.UserId == tokenValidation.UserId);
if (user != null)
return user;
}
return null;
}
}
}