102 lines
3.1 KiB
C#
102 lines
3.1 KiB
C#
using System.Text.Json;
|
|
using Femto.Api.Auth;
|
|
using Femto.Modules.Auth.Application.Dto;
|
|
using Femto.Modules.Auth.Models;
|
|
using Microsoft.Extensions.Options;
|
|
|
|
namespace Femto.Api.Sessions;
|
|
|
|
internal record SessionInfo(string? SessionId, Guid? UserId);
|
|
|
|
internal static class HttpContextSessionExtensions
|
|
{
|
|
private static readonly JsonSerializerOptions JsonOptions = new()
|
|
{
|
|
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
|
};
|
|
|
|
public static SessionInfo GetSessionInfo(this HttpContext httpContext)
|
|
{
|
|
var sessionId = httpContext.Request.Cookies["sid"];
|
|
|
|
var userJson = httpContext.Request.Cookies["user"];
|
|
|
|
UserInfo? user = null;
|
|
if (userJson is not null)
|
|
{
|
|
user = JsonSerializer.Deserialize<UserInfo>(userJson, JsonOptions);
|
|
}
|
|
|
|
return new SessionInfo(sessionId, user?.Id);
|
|
}
|
|
|
|
public static void SetSession(this HttpContext context, Session session, UserInfo user)
|
|
{
|
|
var cookieSettings = context.RequestServices.GetRequiredService<
|
|
IOptions<CookieSettings>
|
|
>();
|
|
|
|
context.Response.Cookies.Append(
|
|
"sid",
|
|
session.Id,
|
|
new CookieOptions
|
|
{
|
|
Path = "/",
|
|
IsEssential = true,
|
|
Domain = cookieSettings.Value.Domain,
|
|
HttpOnly = true,
|
|
Secure = cookieSettings.Value.Secure,
|
|
SameSite = cookieSettings.Value.SameSite,
|
|
Expires = session.Expires,
|
|
}
|
|
);
|
|
|
|
context.Response.Cookies.Append(
|
|
"user",
|
|
JsonSerializer.Serialize(user, JsonOptions),
|
|
new CookieOptions
|
|
{
|
|
Path = "/",
|
|
Domain = cookieSettings.Value.Domain,
|
|
IsEssential = true,
|
|
Secure = cookieSettings.Value.Secure,
|
|
SameSite = cookieSettings.Value.SameSite,
|
|
Expires = session.Expires,
|
|
}
|
|
);
|
|
}
|
|
|
|
public static void DeleteSession(this HttpContext httpContext)
|
|
{
|
|
var cookieSettings = httpContext.RequestServices.GetRequiredService<
|
|
IOptions<CookieSettings>
|
|
>();
|
|
|
|
httpContext.Response.Cookies.Delete(
|
|
"sid",
|
|
new CookieOptions
|
|
{
|
|
Path = "/",
|
|
HttpOnly = true,
|
|
Domain = cookieSettings.Value.Domain,
|
|
IsEssential = true,
|
|
Secure = cookieSettings.Value.Secure,
|
|
SameSite = cookieSettings.Value.SameSite,
|
|
Expires = DateTimeOffset.UtcNow.AddDays(-1),
|
|
}
|
|
);
|
|
|
|
httpContext.Response.Cookies.Delete(
|
|
"user",
|
|
new CookieOptions
|
|
{
|
|
Path = "/",
|
|
Domain = cookieSettings.Value.Domain,
|
|
IsEssential = true,
|
|
Secure = cookieSettings.Value.Secure,
|
|
SameSite = cookieSettings.Value.SameSite,
|
|
Expires = DateTimeOffset.UtcNow.AddDays(-1),
|
|
}
|
|
);
|
|
}
|
|
}
|