2024-09-12 15:42:28 +02:00

96 lines
3.2 KiB
C#

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Swashbuckle.AspNetCore.Annotations;
using System.Security.Claims;
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;
public AuthController(IUserService userService, IAuthService authService)
{
_userService = userService;
_authService = authService;
}
// LOGIN
[AllowAnonymous]
[HttpPost("login")]
[SwaggerOperation(Summary = "Login")]
public async Task<IActionResult> Login([FromBody] LoginDto login)
{
// Validate user
var user = await _userService.GetByUsernameAsync(login.Username);
if (user is null)
{
return Unauthorized();
}
// Validate login credentials
var isValid = await _authService.ValidateAsync(login.Username, login.Password);
if (!isValid)
{
return Unauthorized();
}
// Create claims based on the user information
var claims = new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
new Claim(ClaimTypes.Name, user.UserName),
new Claim(ClaimTypes.Surname, user.LastName ?? ""),
new Claim(ClaimTypes.GivenName, user.FirstName ?? ""),
};
foreach (var userRole in user.UserRoles)
{
claims.Add(new Claim(ClaimTypes.Role, userRole!.Name));
}
// Create a ClaimsIdentity based on the created claims
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
// Set the authentication properties
var authProperties = new AuthenticationProperties
{
IsPersistent = true,
AllowRefresh = true,
ExpiresUtc = DateTime.UtcNow.AddMinutes(60)
};
// Sign in user using cookie-based authentication
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(claimsIdentity),
authProperties
);
return Ok();
}
// LOGOUT
[HttpPost("logout")]
[SwaggerOperation(Summary = "Logout")]
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return Ok();
}
// AUTH CHECK
[HttpGet]
[SwaggerOperation(Summary = "Authentication Check")]
public IActionResult IsAuth() => Ok(User?.Identity?.IsAuthenticated ?? false);
}
}