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);
Span<byte> sessionBytes = stackalloc byte[16];
session.Id.TryWriteBytes(sessionBytes);
Response.Cookies.Append("sid", Convert.ToBase64String(sessionBytes));
_sessionService.SaveSessionCookie(Response, session);
return RedirectToPage("/admin/index");
}

View File

@ -27,6 +27,18 @@ public interface ISessionService
/// <exception cref="ArgumentNullException"><paramref name="session" /> is <see langword="null" />.</exception>
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>
/// Attempts to find a session with the specified ID.
/// </summary>

View File

@ -63,6 +63,20 @@ internal sealed class SessionService : ISessionService
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 />
public bool TryGetSession(Guid sessionId, [NotNullWhen(true)] out ISession? session)
{