using System;
using System.Security.Claims;
using System.Threading.Tasks;
using BlueWest.Cryptography;
using BlueWest.Data.Application;
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.Cors;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
namespace BlueWest.WebApi.Controllers;
///
/// Auth controller
///
[ApiController]
[Route("api/[controller]")]
[Authorize(Policy = "ApiUser")]
/*[EnableCors(Constants.CorsPolicyName)]*/
public class AuthController : Controller
{
private readonly IAuthManager _authManager;
private readonly IUserManager _userManager;
private readonly ISessionManager _sessionManager;
///
///
///
///
///
public AuthController( IAuthManager authManager, IUserManager userManager, ISessionManager sessionManager)
{
_authManager = authManager;
_userManager = userManager;
_sessionManager = sessionManager;
}
///
/// Signup user
///
///
///
[AllowAnonymous]
[HttpPost("register")]
public async Task> SignupUserAsync(RegisterViewModel registerViewModel)
{
return await _authManager.CreateUserAsync(registerViewModel);
}
///
/// Gets a bearer token
///
///
///
[AllowAnonymous]
[HttpPost("token")]
public async Task> GetTokenAsync(LoginRequest loginViewModel)
{
var (success, sessionToken, token) = await _authManager.GetToken(loginViewModel);
if (success)
{
return Ok(new {sessionToken, token});
}
return Problem();
}
///
/// Check if user is logged in
///
///
[HttpGet("isLoggedIn")]
public ActionResult IsLoggedIn()
{
var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
if (identity.IsAuthenticated)
{
return Ok(true);
}
return Ok(false);
}
///
/// Checks if the session is authorized
///
///
///
[HttpGet("isAuthorized")]
public ActionResult IsAuthorized(string hash)
{
var isAuthorized = _sessionManager.IsAuthorized(hash);
return Ok(isAuthorized ? new {authenticated = true} : new {authenticated = false});
}
///
/// Do Cookie based login.
///
///
///
[AllowAnonymous]
[HttpPost("login")]
public async Task DoLoginAsync(LoginRequest loginDto)
{
var (success, identity, sessionToken) = await _authManager.DoLogin(loginDto);
if (success)
{
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(identity),
new AuthenticationProperties
{
IsPersistent = true,
ExpiresUtc = DateTime.UtcNow.AddDays(1)
});
return Ok(new {authenticated = true, sessionToken});
}
return new ForbidResult(CookieAuthenticationDefaults.AuthenticationScheme);
}
///
/// Do Cookie based logout
///
///
///
[AllowAnonymous]
[HttpPost("logout")]
public async Task DoLogoutAsync()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
}
}