tuitio/IdentityServer.Application/CommandHandlers/AuthenticateUserHandler.cs

43 lines
1.6 KiB
C#
Raw Normal View History

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