tuitio/IdentityServer.Application/Services/UserService.cs

65 lines
2.2 KiB
C#
Raw Normal View History

using IdentityServer.Application.Services.Abstractions;
using IdentityServer.Application.Stores;
2021-11-13 17:17:13 +02:00
using IdentityServer.Domain.Abstractions;
using IdentityServer.Domain.Entities;
2020-12-20 03:06:43 +02:00
using IdentityServer.Domain.Models;
using IdentityServer.Domain.Repositories;
using System;
using System.Threading.Tasks;
namespace IdentityServer.Application.Services
{
internal class UserService : IUserService
2020-12-20 03:06:43 +02:00
{
2021-11-13 17:17:13 +02:00
private readonly ITokenStore _securityStore;
2020-12-20 03:06:43 +02:00
private readonly IIdentityRepository _identityRepository;
private readonly ITokenService _tokenService;
2021-11-13 17:17:13 +02:00
private readonly IConfigProvider _configProvider;
private readonly IHashingService _hashingService;
2020-12-20 03:06:43 +02:00
public UserService(ITokenStore securityStore, IIdentityRepository identityRepository, ITokenService tokenService, IConfigProvider configProvider, IHashingService hashingService)
2020-12-20 03:06:43 +02:00
{
_securityStore=securityStore;
_identityRepository=identityRepository;
_tokenService=tokenService;
_configProvider=configProvider;
_hashingService=hashingService;
2020-12-20 03:06:43 +02:00
}
public async Task<Token> Authenticate(string userName, string password)
{
var passwordHash = _hashingService.HashSha256(password);
var user = await _identityRepository.GetUser(userName, passwordHash);
2021-11-13 17:17:13 +02:00
var valid = ValidateUser(user);
if (!valid)
2020-12-20 03:06:43 +02:00
return null;
2021-11-13 17:17:13 +02:00
var token = _tokenService.GenerateToken(user);
2020-12-24 04:55:45 +02:00
_securityStore.SetToken(token, user.UserId);
2021-11-13 16:04:04 +02:00
await _identityRepository.UpdateUserAfterAuthentication(user, token);
2020-12-20 03:06:43 +02:00
return token;
}
public TokenCore Authorize(string token)
2020-12-20 03:06:43 +02:00
{
var tokenCore = _securityStore.ValidateAndGetTokenCore(token);
if (tokenCore == null)
return null;
2020-12-20 03:06:43 +02:00
return tokenCore;
2020-12-20 03:06:43 +02:00
}
2021-11-13 17:17:13 +02:00
private bool ValidateUser(AppUser user)
{
if (user == null)
return false;
if (user.FailedLoginAttempts.HasValue && user.FailedLoginAttempts.Value > _configProvider.Restrictions.MaxFailedLoginAttempts)
return false;
return true;
}
2020-12-20 03:06:43 +02:00
}
}