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 Login([FromBody] LoginDto login) { // Validate user var user = await _userService.GetByUsernameAsync(login.Username, includeRoles: true); 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 { 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 Logout() { await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); return Ok(); } // AUTH CHECK [HttpGet] [SwaggerOperation(Summary = "Authentication Check")] public IActionResult IsAuth() => Ok(User?.Identity?.IsAuthenticated ?? false); } }