using IdentityServer.Application.Services.Abstractions; 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; private readonly IHashingService _hashingService; public UserService(ITokenStore securityStore, IIdentityRepository identityRepository, ITokenService tokenService, IConfigProvider configProvider, IHashingService hashingService) { _securityStore=securityStore; _identityRepository=identityRepository; _tokenService=tokenService; _configProvider=configProvider; _hashingService=hashingService; } public async Task Authenticate(string userName, string password) { var passwordHash = _hashingService.HashSha256(password); var user = await _identityRepository.GetUser(userName, passwordHash); 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; } } }