50 lines
1.4 KiB
C#
50 lines
1.4 KiB
C#
using System.Security.Cryptography;
|
|
using System.Text;
|
|
using License.Api.Data;
|
|
using License.Api.Models;
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
namespace License.Api.Services;
|
|
|
|
public class IdempotencyService
|
|
{
|
|
private readonly AppDbContext _db;
|
|
|
|
public IdempotencyService(AppDbContext db)
|
|
{
|
|
_db = db;
|
|
}
|
|
|
|
public async Task<IdempotencyKeyRecord?> GetAsync(string key)
|
|
{
|
|
return await _db.IdempotencyKeys
|
|
.FirstOrDefaultAsync(x => x.IdempotencyKey == key && x.ExpiresAt > DateTime.UtcNow);
|
|
}
|
|
|
|
public async Task<IdempotencyKeyRecord> StoreAsync(string key, string path, string requestBodyHash, int responseCode, string responseBody)
|
|
{
|
|
var record = new IdempotencyKeyRecord
|
|
{
|
|
IdempotencyKey = key,
|
|
RequestPath = path,
|
|
RequestHash = requestBodyHash,
|
|
ResponseCode = responseCode,
|
|
ResponseBody = responseBody,
|
|
CreatedAt = DateTime.UtcNow,
|
|
ExpiresAt = DateTime.UtcNow.AddHours(24)
|
|
};
|
|
|
|
_db.IdempotencyKeys.Add(record);
|
|
await _db.SaveChangesAsync();
|
|
return record;
|
|
}
|
|
|
|
public static string ComputeRequestHash(string? body)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(body))
|
|
return string.Empty;
|
|
var hash = SHA256.HashData(Encoding.UTF8.GetBytes(body));
|
|
return Convert.ToHexString(hash).ToLowerInvariant();
|
|
}
|
|
}
|