refactor: delegate cookie writing to SessionService

This commit is contained in:
Oliver Booth 2024-02-24 15:37:39 +00:00
parent fa394480b1
commit 14d73851ea
Signed by: oliverbooth
GPG Key ID: E60B570D1B7557B5
3 changed files with 27 additions and 3 deletions

View File

@ -60,9 +60,7 @@ public sealed class AdminController : ControllerBase
} }
ISession session = _sessionService.CreateSession(Request, user); ISession session = _sessionService.CreateSession(Request, user);
Span<byte> sessionBytes = stackalloc byte[16]; _sessionService.SaveSessionCookie(Response, session);
session.Id.TryWriteBytes(sessionBytes);
Response.Cookies.Append("sid", Convert.ToBase64String(sessionBytes));
return RedirectToPage("/admin/index"); return RedirectToPage("/admin/index");
} }

View File

@ -27,6 +27,18 @@ public interface ISessionService
/// <exception cref="ArgumentNullException"><paramref name="session" /> is <see langword="null" />.</exception> /// <exception cref="ArgumentNullException"><paramref name="session" /> is <see langword="null" />.</exception>
void DeleteSession(ISession session); void DeleteSession(ISession session);
/// <summary>
/// Saves a session cookie to the client's browser.
/// </summary>
/// <param name="response">The response to edit.</param>
/// <param name="session">The session to write.</param>
/// <exception cref="ArgumentNullException">
/// <para><paramref name="request" /> is <see langword="null" />.</para>
/// -or-
/// <para><paramref name="session" /> is <see langword="null" />.</para>
/// </exception>
void SaveSessionCookie(HttpResponse response, ISession session);
/// <summary> /// <summary>
/// Attempts to find a session with the specified ID. /// Attempts to find a session with the specified ID.
/// </summary> /// </summary>

View File

@ -63,6 +63,20 @@ internal sealed class SessionService : ISessionService
context.SaveChanges(); context.SaveChanges();
} }
/// <inheritdoc />
public void SaveSessionCookie(HttpResponse response, ISession session)
{
if (response is null) throw new ArgumentNullException(nameof(response));
if (session is null) throw new ArgumentNullException(nameof(session));
Span<byte> buffer = stackalloc byte[16];
if (!session.Id.TryWriteBytes(buffer)) return;
IPAddress? remoteIpAddress = response.HttpContext.Connection.RemoteIpAddress;
_logger.LogDebug("Writing cookie 'sid' to HTTP response for {RemoteAddr}", remoteIpAddress);
response.Cookies.Append("sid", Convert.ToBase64String(buffer));
}
/// <inheritdoc /> /// <inheritdoc />
public bool TryGetSession(Guid sessionId, [NotNullWhen(true)] out ISession? session) public bool TryGetSession(Guid sessionId, [NotNullWhen(true)] out ISession? session)
{ {