2020-07-10 00:29:39 +03:00
|
|
|
|
using NetworkResurrector.Application.Stores;
|
|
|
|
|
using NetworkResurrector.Domain.Entities;
|
|
|
|
|
using NetworkResurrector.Domain.Models;
|
2020-07-09 02:58:04 +03:00
|
|
|
|
using NetworkResurrector.Domain.Services;
|
2020-07-10 00:29:39 +03:00
|
|
|
|
using System;
|
|
|
|
|
using System.Linq;
|
2020-07-09 02:58:04 +03:00
|
|
|
|
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);
|
2020-07-09 02:58:04 +03:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public class UserService : IUserService
|
|
|
|
|
{
|
|
|
|
|
private readonly IParamProvider _paramProvider;
|
2020-07-10 00:29:39 +03:00
|
|
|
|
private readonly ISecurityStore _securityStore;
|
2020-07-09 02:58:04 +03:00
|
|
|
|
|
2020-07-10 00:29:39 +03:00
|
|
|
|
public UserService(IParamProvider paramProvider, ISecurityStore securityStore)
|
2020-07-09 02:58:04 +03:00
|
|
|
|
{
|
|
|
|
|
_paramProvider = paramProvider;
|
2020-07-10 00:29:39 +03:00
|
|
|
|
_securityStore = securityStore;
|
2020-07-09 02:58:04 +03:00
|
|
|
|
}
|
|
|
|
|
|
2020-07-10 00:29:39 +03:00
|
|
|
|
public async Task<SecurityToken> Login(string userName, string password)
|
2020-07-09 02:58:04 +03:00
|
|
|
|
{
|
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}";
|
|
|
|
|
_securityStore.SetToken(token, user.UserId);
|
|
|
|
|
|
|
|
|
|
var securityToken = new SecurityToken() { UserId = user.UserId, Token = token };
|
|
|
|
|
return securityToken;
|
2020-07-09 02:58:04 +03:00
|
|
|
|
}
|
|
|
|
|
|
2020-07-10 00:29:39 +03:00
|
|
|
|
public async Task<User> Authenticate(string token)
|
2020-07-09 02:58:04 +03:00
|
|
|
|
{
|
2020-07-10 00:29:39 +03:00
|
|
|
|
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;
|
2020-07-09 02:58:04 +03:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|