refactor: move authentication to dedicated controller

This commit is contained in:
Oliver Booth 2024-02-25 15:54:32 +00:00
parent b6d3eb72fe
commit 0fbb94b86e
Signed by: oliverbooth
GPG Key ID: E60B570D1B7557B5
4 changed files with 122 additions and 86 deletions

View File

@ -1,84 +0,0 @@
using System.Net;
using Microsoft.AspNetCore.Mvc;
using OliverBooth.Data.Web;
using OliverBooth.Services;
using ISession = OliverBooth.Data.Web.ISession;
namespace OliverBooth.Controllers;
[Controller]
[Route("auth/admin")]
public sealed class AdminController : ControllerBase
{
private readonly ILogger<AdminController> _logger;
private readonly IUserService _userService;
private readonly ISessionService _sessionService;
/// <summary>
/// Initializes a new instance of the <see cref="AdminController" /> class.
/// </summary>
/// <param name="logger">The logger.</param>
/// <param name="userService">The user service.</param>
/// <param name="sessionService">The session service.</param>
public AdminController(ILogger<AdminController> logger,
IUserService userService,
ISessionService sessionService)
{
_logger = logger;
_userService = userService;
_sessionService = sessionService;
}
[HttpPost("login")]
public IActionResult Login()
{
string? loginEmail = Request.Form["login-email"];
string? loginPassword = Request.Form["login-password"];
IPAddress? remoteIpAddress = Request.HttpContext.Connection.RemoteIpAddress;
if (string.IsNullOrWhiteSpace(loginEmail))
{
_logger.LogInformation("Login attempt from {Host} with empty login", remoteIpAddress);
return RedirectToPage("/admin/login");
}
if (string.IsNullOrWhiteSpace(loginPassword))
{
_logger.LogInformation("Login attempt as '{Email}' from {Host} with empty password", loginEmail,
remoteIpAddress);
return RedirectToPage("/admin/login");
}
if (_userService.VerifyLogin(loginEmail, loginPassword, out IUser? user))
{
_logger.LogInformation("Login attempt for '{Email}' succeeded from {Host}", loginEmail, remoteIpAddress);
}
else
{
_logger.LogInformation("Login attempt for '{Email}' failed from {Host}", loginEmail, remoteIpAddress);
return RedirectToPage("/admin/login");
}
ISession session = _sessionService.CreateSession(Request, user);
_sessionService.SaveSessionCookie(Response, session);
return RedirectToPage("/admin/index");
}
[HttpGet("logout")]
public IActionResult Logout()
{
if (_sessionService.TryGetSession(Request, out ISession? session))
{
_sessionService.DeleteSession(session);
}
_sessionService.DeleteSessionCookie(Response);
if (Request.Headers.Referer is var referer && !string.IsNullOrWhiteSpace(referer.ToString()))
{
return Redirect(referer!);
}
return RedirectToPage("/admin/login");
}
}

View File

@ -0,0 +1,116 @@
using Asp.Versioning;
using Microsoft.AspNetCore.Mvc;
using OliverBooth.Data.Web;
using OliverBooth.Services;
using ISession = OliverBooth.Data.Web.ISession;
namespace OliverBooth.Controllers.Api.v1;
/// <summary>
/// Represents a controller which handles user authentication.
/// </summary>
[Controller]
[Route("api/v{version:apiVersion}/auth")]
[ApiVersion(1)]
public sealed class AuthenticationController : ControllerBase
{
private readonly ILogger<AuthenticationController> _logger;
private readonly ISessionService _sessionService;
private readonly IUserService _userService;
/// <summary>
/// Initializes a new instance of the <see cref="AuthenticationController" /> class.
/// </summary>
/// <param name="logger">The logger.</param>
/// <param name="sessionService">The session service.</param>
/// <param name="userService">The user service.</param>
public AuthenticationController(ILogger<AuthenticationController> logger,
ISessionService sessionService,
IUserService userService)
{
_logger = logger;
_sessionService = sessionService;
_userService = userService;
}
/// <summary>
/// Authorizes a login request using the specified credentials.
/// </summary>
/// <param name="emailAddress">The login email address.</param>
/// <param name="password">The login password.</param>
/// <returns>The result of the authentication process.</returns>
[HttpPost("signin")]
public IActionResult DoSignIn([FromForm(Name = "login-email")] string emailAddress,
[FromForm(Name = "login-password")] string password)
{
string epName = nameof(DoSignIn);
if (Request.HttpContext.Connection.RemoteIpAddress is not { } ip)
{
_logger.LogWarning("Endpoint {Name} reached with no remote IP!", epName);
return BadRequest();
}
IActionResult redirectResult = RedirectToPage("/admin/login");
if (Request.Headers.Referer is var referer && !string.IsNullOrWhiteSpace(referer.ToString()))
{
_logger.LogInformation("Endpoint {Name} reached by {Host} with referer {Referer}", epName, ip, referer);
redirectResult = Redirect(referer!);
}
if (string.IsNullOrWhiteSpace(emailAddress))
{
_logger.LogInformation("Login attempt from {Host} has empty login", ip);
return redirectResult;
}
if (string.IsNullOrWhiteSpace(emailAddress))
{
_logger.LogInformation("Login attempt from {Host} with login {Login} has empty password", ip, emailAddress);
return redirectResult;
}
if (!_userService.VerifyLogin(emailAddress, password, out IUser? user))
{
_logger.LogInformation("Login attempt from {Host} with login {Login} failed", ip, emailAddress);
return redirectResult;
}
ISession session = _sessionService.CreateSession(Request, user);
_sessionService.SaveSessionCookie(Response, session);
_logger.LogInformation("Login attempt from {Host} with login {Login} succeeded", ip, emailAddress);
return redirectResult;
}
/// <summary>
/// Signs the client out of its current session.
/// </summary>
/// <returns>The result of the sign-out process.</returns>
[HttpGet("signout")]
public IActionResult DoSignOut()
{
string epName = nameof(DoSignOut);
if (Request.HttpContext.Connection.RemoteIpAddress is not { } ip)
{
_logger.LogWarning("Endpoint {Name} reached with no remote IP!", epName);
return BadRequest();
}
IActionResult redirectResult = RedirectToPage("/admin/login");
if (Request.Headers.Referer is var referer && !string.IsNullOrWhiteSpace(referer.ToString()))
{
_logger.LogInformation("Endpoint {Name} reached by {Host} with referer {Referer}", epName, ip, referer);
redirectResult = Redirect(referer!);
}
if (!_sessionService.TryGetSession(HttpContext.Request, out ISession? session))
{
_logger.LogInformation("Session sign-out from {Host} requested with no valid session", ip);
return redirectResult;
}
_sessionService.DeleteSession(session);
_sessionService.DeleteSessionCookie(HttpContext.Response);
_logger.LogInformation("Session sign-out from {Host} completed successfully", ip);
return redirectResult;
}
}

View File

@ -6,7 +6,7 @@
} }
<div class="m-auto" style="max-width: 330px; padding: 1rem;"> <div class="m-auto" style="max-width: 330px; padding: 1rem;">
<form method="post" asp-controller="Admin" asp-action="Login"> <form method="post" asp-controller="Authentication" asp-action="DoSignIn" asp-route-version="1">
<h1 class="h3 mb-3 fw-normal">Please sign in</h1> <h1 class="h3 mb-3 fw-normal">Please sign in</h1>
<div class="form-floating"> <div class="form-floating">

View File

@ -126,7 +126,11 @@
<li><a class="dropdown-item" href="#">Settings</a></li> <li><a class="dropdown-item" href="#">Settings</a></li>
<li><a class="dropdown-item" href="#">Profile</a></li> <li><a class="dropdown-item" href="#">Profile</a></li>
<li><hr class="dropdown-divider"></li> <li><hr class="dropdown-divider"></li>
<li><a class="dropdown-item" asp-controller="Admin" asp-action="Logout">Sign out</a></li> <li>
<a class="dropdown-item" asp-controller="Authentication" asp-action="DoSignOut" asp-route-version="1">
Sign out
</a>
</li>
</ul> </ul>
</div> </div>
</div> </div>