using System.ComponentModel.DataAnnotations.Schema; using System.Security.Claims; using System.Security.Cryptography; using System.Text; using AspNetCore.Authentication.ApiKey; using AutoMapPropertyHelper; using NejCommon.Models; using NejCommon.Validation; namespace NejCommon.Models; public partial class ApiKey : IApiKey { [AutoMapProperty("Response")] public string Id { get; set; } = NanoidDotNet.Nanoid.Generate(size: 64); [StandardText] [AutoMapProperty("Request")] public string Name { get; set; } = null!; public byte[] LookupHash { get; set; } = null!; public string KeyHash { get; set; } = null!; [AutoMapProperty("Response")] public bool Revoked { get; set; } [NotMapped] public string key = ""; [NotMapped] [AutoMapProperty("CreateResponse")] public string Key { get => key; set { key = value; LookupHash = ComputeLookupHash(value); KeyHash = ComputeStrongHash(value); } } [NotMapped] public string OwnerName => Id; [NotMapped] public IReadOnlyCollection Claims => [ new Claim(ClaimTypes.NameIdentifier, Id), new Claim(ClaimTypes.Name, Name) ]; public static byte[] ComputeLookupHash(string key) { using var sha256 = SHA256.Create(); return sha256.ComputeHash(Encoding.UTF8.GetBytes(key)); } public static string ComputeStrongHash(string key) { return BCrypt.Net.BCrypt.EnhancedHashPassword(key); } public bool VerifyStrongHash(string key){ return BCrypt.Net.BCrypt.EnhancedVerify(key, KeyHash); } } public partial class ApiKeyResponse : ApiKeyRequest {} public partial class ApiKeyCreateResponse : ApiKeyResponse {}