2026-04-12 02:23:26 +02:00

81 lines
2.4 KiB
C#

using Microsoft.AspNetCore.Authentication.JwtBearer;
using OnlyPrompt.Backend.Database.Models;
using System.Diagnostics.CodeAnalysis;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
using System.Security.Claims;
namespace OnlyPrompt.Backend.Utils
{
public static class Extensions
{
public static string? GetIdentifier(this ClaimsPrincipal principal) => principal.FindFirstValue(ClaimTypes.NameIdentifier);
public static bool TryGetIdentifier(this ClaimsPrincipal principal, [NotNullWhen(true)]out string? identifier)
{
identifier = principal.FindFirstValue(ClaimTypes.NameIdentifier);
return identifier != null;
}
public static Guid? GetUserId(this ClaimsPrincipal principal)
{
if (principal.TryGetIdentifier(out var identifier) && Guid.TryParse(identifier, out var userId))
return userId;
return null;
}
public static IEnumerable<Claim> GetClaims(this UserModel user)
{
yield return new Claim(ClaimTypes.NameIdentifier, user.Id.ToString());
yield return new Claim(ClaimTypes.Name, user.UserName);
yield return new Claim(ClaimTypes.Email, user.Email);
foreach (var role in user.Roles)
yield return new Claim(ClaimTypes.Role, role);
}
public static IQueryable<T> OrderBy<T, TKey>(this IQueryable<T> source, Expression<Func<T, TKey>> selecter, bool ascending)
{
if(ascending)
return source.OrderBy(selecter);
else
return source.OrderByDescending(selecter);
}
public static CookieOptions Copy(this CookieOptions options, Action<CookieOptions>? modify = null)
{
var newOptions = new CookieOptions
{
Domain = options.Domain,
Expires = options.Expires,
HttpOnly = options.HttpOnly,
IsEssential = options.IsEssential,
MaxAge = options.MaxAge,
Path = options.Path,
SameSite = options.SameSite,
Secure = options.Secure
};
modify?.Invoke(newOptions);
return newOptions;
}
public static string Limit(this string @string, int maxLength)
{
if (@string.Length <= maxLength)
return @string;
return @string.Substring(0, maxLength);
}
public const string LowerAlphabet = "abcdefghijklmnopqrstuvwxyz";
public static string GetString(this Random @random, int lenght, string alphabet = LowerAlphabet)
{
Span<char> chars = stackalloc char[lenght];
for (int i = 0; i < lenght; i++)
chars[i] = alphabet[@random.Next(alphabet.Length)];
return new string(chars);
}
}
}