tuitio/IdentityServer.Application/Services/UserService.cs

61 lines
2.0 KiB
C#

using IdentityServer.Application.Stores;
using IdentityServer.Domain.Abstractions;
using IdentityServer.Domain.Entities;
using IdentityServer.Domain.Models;
using IdentityServer.Domain.Repositories;
using System;
using System.Threading.Tasks;
namespace IdentityServer.Application.Services
{
internal class UserService : IUserService
{
private readonly ITokenStore _securityStore;
private readonly IIdentityRepository _identityRepository;
private readonly ITokenService _tokenService;
private readonly IConfigProvider _configProvider;
public UserService(ITokenStore securityStore, IIdentityRepository identityRepository, ITokenService tokenService, IConfigProvider configProvider)
{
_securityStore = securityStore;
_identityRepository = identityRepository;
_tokenService = tokenService;
_configProvider = configProvider;
}
public async Task<Token> Authenticate(string userName, string password)
{
var user = await _identityRepository.GetUser(userName, password);
var valid = ValidateUser(user);
if (!valid)
return null;
var token = _tokenService.GenerateToken(user);
_securityStore.SetToken(token, user.UserId);
await _identityRepository.UpdateUserAfterAuthentication(user, token);
return token;
}
public TokenCore Authorize(string token)
{
var tokenCore = _securityStore.ValidateAndGetTokenCore(token);
if (tokenCore == null)
return null;
return tokenCore;
}
private bool ValidateUser(AppUser user)
{
if (user == null)
return false;
if (user.FailedLoginAttempts.HasValue && user.FailedLoginAttempts.Value > _configProvider.Restrictions.MaxFailedLoginAttempts)
return false;
return true;
}
}
}