using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Project.Application.DTOs.Auth; using Project.Application.DTOs.Outgoing; using Project.Application.Interfaces; using System.Security.Claims; namespace Project.Web.Controllers { [ApiController] [Route("api/[controller]")] public class AuthController : ControllerBase { // FIELDS FOR CTOR private readonly IUserService _userService; private readonly IAuthService _authService; // CTOR public AuthController(IUserService userService, IAuthService authService) { _userService = userService; _authService = authService; } // LOGIN [AllowAnonymous] [HttpPost("login")] public async Task Login([FromBody] LoginDto login) { var isValid = await _authService.ValidateAsync(login.Username, login.Password); if (!isValid) { return Unauthorized(); } var user = await _userService.GetByUsernameAsync(login.Username); if (user == null) { return Unauthorized(user); } 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 ?? "") }; var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); var authProperties = new AuthenticationProperties { IsPersistent = true, AllowRefresh = true, ExpiresUtc = DateTime.UtcNow.AddMinutes(60) }; await HttpContext.SignInAsync( CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties ); return Ok(); } // LOGOUT [HttpPost("logout")] public async Task Logout() { await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); return Ok(); } //// LOGIN //[HttpPost("login")] //public async Task Login(LoginDto login) //{ // var user = await _authService.AuthenticateAsync(login.Username, login.Password); // if (user == null) // { // return Unauthorized(); // } // var claims = new ClaimsIdentity(new[] // { // new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()), // new Claim(ClaimTypes.Name, user.UserName) // }, CookieAuthenticationDefaults.AuthenticationScheme); // var authProperties = new AuthenticationProperties // { // IsPersistent = false, // ExpiresUtc = DateTime.UtcNow.AddMinutes(10) // }; // await HttpContext.SignInAsync( // CookieAuthenticationDefaults.AuthenticationScheme, // new ClaimsPrincipal(claims), // authProperties); // return Ok("Login successful"); //} //// LOGOUT //public async Task Logout() //{ // await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); // return Ok("Logout successful"); //} } }