CodeLiturgy.Dashboard/BlueWest.Api/Controllers/AuthController.cs

109 lines
3.5 KiB
C#

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;
/// <summary>
/// Auth controller
/// </summary>
[ApiController]
[Route("api/[controller]")]
[Authorize(Policy = SessionConstants.ApiNamePolicy)]
/*[EnableCors(Constants.CorsPolicyName)]*/
public class AuthController : Controller
{
private readonly IAuthManager _authManager;
private readonly IUserManager _userManager;
/// <summary>
///
/// </summary>
/// <param name="authManager"></param>
/// <param name="userManager"></param>
public AuthController( IAuthManager authManager, IUserManager userManager)
{
_authManager = authManager;
_userManager = userManager;
}
/// <summary>
/// Signup user
/// </summary>
/// <param name="registerRequest"></param>
/// <returns></returns>
[AllowAnonymous]
[HttpPost("register")]
public async Task<ActionResult<IdentityResult>> SignupUserAsync(RegisterRequest registerRequest)
{
return await _authManager.CreateUserAsync(registerRequest);
}
/// <summary>
/// Gets a bearer token
/// </summary>
/// <param name="loginViewModel"></param>
/// <returns></returns>
[AllowAnonymous]
[HttpPost("login")]
public async Task<ActionResult<IdentityResult>> GetSessionToken(LoginRequest loginViewModel)
{
var (success, sessionToken, _) = await _authManager.GetSessionTokenIdByLoginRequest(loginViewModel, JwtBearerDefaults.AuthenticationScheme);
if (success)
{
return Ok(new {sessionToken});
}
return Problem();
}
/// <summary>
/// Do Cookie based login.
/// </summary>
/// <param name="loginDto"></param>
/// <returns></returns>
/*[AllowAnonymous]
[HttpPost("login")]
public async Task<ActionResult> 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);
}*/
/// <summary>
/// Do Cookie based logout
/// </summary>
/// <returns></returns>
[AllowAnonymous]
[HttpPost("logout")]
public async Task DoCookieLogoutAsync()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
}
}