using System.Security.Claims; using System.Threading.Tasks; using BlueWest.WebApi.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 /// [Route("api/[controller]")] [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] [Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)] [ApiController] 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(RegisterViewModel registerViewModel) { return await _authManager.CreateUserAsync(registerViewModel); } /// /// Gets a bearer token /// /// /// [AllowAnonymous] [HttpPost("login")] public async Task> GetTokenAsync(LoginViewModel loginViewModel) { var loginResultSucceded = await _authManager.GetToken(loginViewModel); if (loginResultSucceded != null) { return Ok(loginResultSucceded); } return Problem(); } /// /// Do Cookie based login. /// /// /// [AllowAnonymous] [HttpPost("logincookie")] public async Task> DoLoginAsync(LoginViewModel loginDto) { var user = await _userManager.FindByEmailAsync(loginDto.Email); if (user != null) { if(await _userManager.CheckPasswordAsync(user, loginDto.Password)) { var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme); identity.AddClaim(new Claim(ClaimTypes.Email, user.Email)); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity)); return Json(true); } } return Json(false); } /// /// Do Cookie based logout /// /// /// [AllowAnonymous] [HttpPost("logout")] public async Task> DoLogoutAsync(LoginViewModel loginDto) { await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); return Json(true); } }