LoginService
using FluentResults;
using Microsoft.AspNetCore.Identity;
using System.Linq;
using UsuariosApi.Data.Requests;
using UsuariosApi.Models;
using UsuariosApi.Services;
public class LoginService
{
private SignInManager<IdentityUser<int>> _signInManager;
private TokenService _tokenService;
public LoginService(SignInManager<IdentityUser<int>> signInManager,
TokenService tokenService)
{
_signInManager = signInManager;
_tokenService = tokenService;
}
public Result LogaUsuario(LoginRequest request)
{
var resultadoIdentity = _signInManager
.PasswordSignInAsync(request.Username, request.Password, false, false);
if (resultadoIdentity.Result.Succeeded)
{
var identityUser = _signInManager
.UserManager
.Users
.FirstOrDefault(usuario =>
usuario.NormalizedUserName == request.Username.ToUpper());
Token token = _tokenService.CreateToken(identityUser);
return Result.Ok().WithSuccess(token.Value);
}
return Result.Fail("Login falhou");
}
}
LoginRequest
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace UsuariosApi.Data.Requests
{
public class LoginRequest
{
[Required]
public string Username { get; set; }
[Required]
public string Password { get; set; }
}
}
LoginController
using FluentResults;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using UsuariosApi.Data.Requests;
using UsuariosApi.Services;
namespace UsuariosApi.Controllers
{
[ApiController]
[Route("[controller]")]
public class LoginController : ControllerBase
{
private LoginService _loginService;
public LoginController(LoginService loginService)
{
_loginService = loginService;
}
[HttpPost]
public IActionResult LogaUsuario(LoginRequest request)
{
Result resultado = _loginService.LogaUsuario(request);
if (resultado.IsFailed) return Unauthorized(resultado.Errors);
return Ok(resultado.Successes);
}
}
}