75 lines
2.5 KiB
C#
75 lines
2.5 KiB
C#
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Swashbuckle.AspNetCore.Annotations;
|
|
using UserManagement.Application.Dtos.Auth;
|
|
using UserManagement.Application.Interfaces;
|
|
|
|
namespace UserManagement.API.Controllers
|
|
{
|
|
[ApiController]
|
|
[Route("api/[controller]")]
|
|
public class AuthController : ControllerBase
|
|
{
|
|
// CTOR
|
|
private readonly IUserService _userService;
|
|
private readonly IAuthService _authService;
|
|
private readonly ILogger<AuthController> _logger;
|
|
|
|
public AuthController(IUserService userService, IAuthService authService, ILogger<AuthController> logger)
|
|
{
|
|
_userService = userService;
|
|
_authService = authService;
|
|
_logger = logger;
|
|
}
|
|
|
|
// SIGN IN
|
|
[HttpPost("login")]
|
|
[SwaggerOperation(Summary = "Login")]
|
|
[ProducesResponseType(StatusCodes.Status200OK)]
|
|
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
|
|
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
|
|
public async Task<IActionResult> Login([FromBody] LoginDto login)
|
|
{
|
|
try
|
|
{
|
|
await _authService.SignInAsync(login.Username, login.Password, HttpContext);
|
|
return Ok();
|
|
}
|
|
catch (UnauthorizedAccessException ex)
|
|
{
|
|
_logger.LogError(ex, ex.Message);
|
|
return Unauthorized(ex.Message);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(ex, ex.Message);
|
|
return StatusCode(StatusCodes.Status500InternalServerError);
|
|
}
|
|
}
|
|
|
|
// LOGOUT
|
|
[HttpPost("logout")]
|
|
[SwaggerOperation(Summary = "Logout")]
|
|
[ProducesResponseType(StatusCodes.Status200OK)]
|
|
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
|
|
public async Task<IActionResult> Logout()
|
|
{
|
|
try
|
|
{
|
|
await _authService.SignOutAsync(HttpContext);
|
|
return Ok();
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(ex, ex.Message);
|
|
return StatusCode(StatusCodes.Status500InternalServerError);
|
|
}
|
|
}
|
|
|
|
// AUTH CHECK
|
|
[HttpGet]
|
|
[SwaggerOperation(Summary = "Authentication Check")]
|
|
public IActionResult IsAuth() => Ok(User?.Identity?.IsAuthenticated ?? false);
|
|
}
|
|
}
|