69 lines
2.1 KiB
C#
69 lines
2.1 KiB
C#
using System.Security.Claims;
|
|
using Yuna.Website.Server.Model;
|
|
|
|
namespace Yuna.Website.Server.Infrastructure
|
|
{
|
|
public static class CookieExtensions
|
|
{
|
|
public static T LoadFromCookies<T>(this HttpContext context, string key)
|
|
{
|
|
if (context.Request.Cookies.TryGetValue(key, out var value))
|
|
{
|
|
try
|
|
{
|
|
return System.Text.Json.JsonSerializer.Deserialize<T>(value)
|
|
?? throw new Exception();
|
|
}
|
|
|
|
catch
|
|
{
|
|
return default!;
|
|
}
|
|
}
|
|
|
|
return default!;
|
|
}
|
|
|
|
public static void SaveToCookies<T>(this HttpContext context, string key, T value, TimeSpan? maxAge = null, bool httpOnly = false)
|
|
{
|
|
var dataStr = System.Text.Json.JsonSerializer.Serialize<T>(value);
|
|
|
|
if (context.Request.Cookies.ContainsKey(key)) context.Response.Cookies.Delete(key);
|
|
|
|
var sameSite = !Settings.IsDevEnv;
|
|
|
|
context.Response.Cookies.Append(key, dataStr, new CookieOptions()
|
|
{ HttpOnly = httpOnly,
|
|
MaxAge = maxAge ?? TimeSpan.FromDays(365),
|
|
SameSite = sameSite ? SameSiteMode.Strict : SameSiteMode.None ,
|
|
Secure = true
|
|
});
|
|
}
|
|
|
|
public static void ClearCookies(this HttpContext context)
|
|
{
|
|
foreach (var cookie in context.Request.Cookies)
|
|
{
|
|
context.Response.Cookies.Delete(cookie.Key);
|
|
}
|
|
}
|
|
|
|
public static long? GetUserIdFromCookie(this HttpContext context)
|
|
{
|
|
var idStr = context.User.FindFirstValue(ClaimTypes.NameIdentifier);
|
|
var isParsed = long.TryParse(idStr, out var result);
|
|
return isParsed ? result : null;
|
|
}
|
|
|
|
public static bool GetRoleFromCookie(this HttpContext context)
|
|
{
|
|
if (bool.TryParse(context.User.FindFirstValue(ClaimTypes.Role), out var result))
|
|
{
|
|
return result;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
}
|
|
}
|