tuitio/IdentityServer.Application/CommandHandlers/AuthenticateUserHandler.cs

43 lines
1.6 KiB
C#

using AutoMapper;
using IdentityServer.Application.Commands;
using IdentityServer.Application.Services;
using IdentityServer.PublishedLanguage.Constants;
using IdentityServer.PublishedLanguage.Dto;
using IdentityServer.PublishedLanguage.Events;
using MediatR;
using Microsoft.Extensions.Logging;
using System.Threading;
using System.Threading.Tasks;
namespace IdentityServer.Application.CommandHandlers
{
public class AuthenticateUserHandler : IRequestHandler<AuthenticateUser, AuthenticateUserResult>
{
private readonly IUserService _userService;
private readonly IMapper _mapper;
private readonly ILogger<AuthenticateUserHandler> _logger;
public AuthenticateUserHandler(IUserService userService, IMapper mapper, ILogger<AuthenticateUserHandler> logger)
{
_userService = userService;
_mapper = mapper;
_logger = logger;
}
public async Task<AuthenticateUserResult> Handle(AuthenticateUser command, CancellationToken cancellationToken)
{
var internalToken = await _userService.Authenticate(command.UserName, command.Password);
if (internalToken == null)
{
_logger.LogDebug($"Authentication failed for user '{command.UserName}'.");
return new AuthenticateUserResult() { Status = AuthenticationStatus.BAD_CREDENTIALS };
}
_logger.LogDebug($"Authentication succeeded for user '{command.UserName}'.");
var token = _mapper.Map<Token>(internalToken);
return new AuthenticateUserResult() { Token = token, Status = AuthenticationStatus.SUCCESS };
}
}
}