58 lines
1.7 KiB
C#
58 lines
1.7 KiB
C#
using System.Text.Json;
|
|
using System.Text.Json.Serialization;
|
|
using Femto.Api.Auth;
|
|
using Femto.Modules.Auth.Application.Dto;
|
|
using Microsoft.Extensions.Options;
|
|
|
|
namespace Femto.Api.Sessions;
|
|
|
|
internal static class HttpContextSessionExtensions
|
|
{
|
|
public static void SetSession(
|
|
this HttpContext httpContext,
|
|
Session session,
|
|
UserInfo user
|
|
)
|
|
{
|
|
var cookieSettings = httpContext.RequestServices.GetService<IOptions<CookieSettings>>();
|
|
var secure = cookieSettings?.Value.Secure ?? true;
|
|
var sameSite = secure ? SameSiteMode.None : SameSiteMode.Unspecified;
|
|
var expires = session.Expires;
|
|
|
|
httpContext.Response.Cookies.Append(
|
|
"session",
|
|
session.SessionId,
|
|
new CookieOptions
|
|
{
|
|
HttpOnly = true,
|
|
Secure = secure,
|
|
SameSite = sameSite,
|
|
Expires = expires,
|
|
}
|
|
);
|
|
|
|
httpContext.Response.Cookies.Append(
|
|
"user",
|
|
JsonSerializer.Serialize(
|
|
user,
|
|
new JsonSerializerOptions
|
|
{
|
|
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
|
Converters = { new JsonStringEnumConverter() },
|
|
}
|
|
),
|
|
new CookieOptions
|
|
{
|
|
Secure = secure,
|
|
SameSite = sameSite,
|
|
Expires = session.Expires,
|
|
}
|
|
);
|
|
}
|
|
|
|
public static void DeleteSession(this HttpContext httpContext)
|
|
{
|
|
httpContext.Response.Cookies.Delete("session");
|
|
httpContext.Response.Cookies.Delete("user");
|
|
}
|
|
}
|