using System.Threading.Tasks; using BlueWest.Data.Auth; using BlueWest.Data.Auth.Context.Users; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; namespace BlueWest.WebApi.Controllers; /// /// Auth controller /// [ApiController] [Route("api/[controller]")] [Authorize(Policy = SessionConstants.ApiNamePolicy)] /*[EnableCors(Constants.CorsPolicyName)]*/ public class AuthController : Controller { private readonly IAuthManager _authManager; private readonly IUserManager _userManager; /// /// /// /// /// public AuthController( IAuthManager authManager, IUserManager userManager) { _authManager = authManager; _userManager = userManager; } /// /// Signup user /// /// /// [AllowAnonymous] [HttpPost("register")] public async Task> SignupUserAsync(RegisterRequest registerRequest) { return await _authManager.CreateUserAsync(registerRequest); } /// /// Gets a bearer token /// /// /// [AllowAnonymous] [HttpPost("login")] public async Task> GetSessionToken(LoginRequest loginViewModel) { var (success, sessionToken, _) = await _authManager.GetSessionTokenIdByLoginRequest(loginViewModel, JwtBearerDefaults.AuthenticationScheme); if (success) { return Ok(new {sessionToken}); } return Problem(); } /// /// Do Cookie based login. /// /// /// /*[AllowAnonymous] [HttpPost("login")] public async Task DoLoginByCookie(LoginRequest loginDto) { var (success, sessionToken, identity) = await _authManager.GetSessionTokenId(loginDto); if (success) { await HttpContext.SignInAsync( CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity), new AuthenticationProperties { IsPersistent = true, ExpiresUtc = DateTime.UtcNow.Add(SessionConstants.DefaultValidForSpan) }); return Ok(new {authenticated = true, sessionToken}); } return new ForbidResult(CookieAuthenticationDefaults.AuthenticationScheme); }*/ /// /// Do Cookie based logout /// /// [AllowAnonymous] [HttpPost("logout")] public async Task DoCookieLogoutAsync() { await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); } }