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

55 lines
1.7 KiB
C#

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<SecurityToken> Login(string userName, string password);
Task<User> 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<SecurityToken> 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}";
_securityStore.SetToken(token, user.UserId);
var securityToken = new SecurityToken() { UserId = user.UserId, Token = token };
return securityToken;
}
public async Task<User> Authenticate(string token)
{
var tokenValidation = _securityStore.ValidateToken(token);
if (tokenValidation.Success)
{
var user = _paramProvider.Users.FirstOrDefault(z => z.UserId == tokenValidation.UserId);
if (user != null)
return user;
}
return null;
}
}
}