using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System.Security.Claims; using UserManagement.Application.Dtos.Auth; using UserManagement.Application.Interfaces; using Swashbuckle.AspNetCore.Annotations; 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); if (user == 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 ?? ""), new Claim(ClaimTypes.Role, user?.Role?.Name.ToString() ?? "") }; // 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(); } } }