Some checks failed
Build and Publish / Build Yale Access Backend (pull_request) Failing after 1m28s
Build and Publish / Push Yale Access Backend Docker Image (pull_request) Has been skipped
Build and Publish / Build Yale Access Frontend (pull_request) Successful in 1m42s
Build and Publish / Push Yale Access Frontend Docker Image (pull_request) Has been skipped
68 lines
2.3 KiB
C#
68 lines
2.3 KiB
C#
using Microsoft.AspNetCore.Authentication;
|
|
using Microsoft.AspNetCore.Authentication.Cookies;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.Cors;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.Extensions.Options;
|
|
using System.Security.Claims;
|
|
using YaleAccess.Models;
|
|
|
|
namespace YaleAccess.Controllers
|
|
{
|
|
[ApiController]
|
|
[Route("api/[controller]")]
|
|
[EnableCors]
|
|
[Authorize]
|
|
public class AuthenticationController(IOptions<Models.Options.AuthenticationOptions> authenticationOptions, ILogger<AuthenticationController> logger) : ControllerBase
|
|
{
|
|
[HttpPost("login")]
|
|
[AllowAnonymous]
|
|
public async Task<IActionResult> Login([FromBody] string password)
|
|
{
|
|
try
|
|
{
|
|
// Check if the password is correct
|
|
if (password != authenticationOptions.Value.Password)
|
|
{
|
|
return Unauthorized(new ApiResponse("Incorrect password."));
|
|
}
|
|
|
|
// Log the user in
|
|
List<Claim> claims = new()
|
|
{
|
|
new Claim(ClaimTypes.Name, "YaleAccess")
|
|
};
|
|
ClaimsIdentity claimsIdentity = new(claims, CookieAuthenticationDefaults.AuthenticationScheme);
|
|
ClaimsPrincipal claimsPrincipal = new(claimsIdentity);
|
|
|
|
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal);
|
|
|
|
// Return the response
|
|
return Ok(new ApiResponse(true));
|
|
}
|
|
catch(Exception ex)
|
|
{
|
|
logger.LogError(ex, "An error occurred logging in.");
|
|
return BadRequest(new ApiResponse("An error occurred logging in."));
|
|
}
|
|
}
|
|
|
|
[HttpPost("logout")]
|
|
[AllowAnonymous]
|
|
public async Task<IActionResult> Logout()
|
|
{
|
|
try
|
|
{
|
|
// Sign the user out
|
|
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
|
|
|
|
return Ok(new ApiResponse(true));
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
logger.LogError(ex, "An error occured logging out.");
|
|
return BadRequest(new ApiResponse("An error occured logging out."));
|
|
}
|
|
}
|
|
}
|
|
} |