Files
Swarm/DysonNetwork.Pass/Affiliation/AffiliationSpellService.cs
2025-12-01 23:33:48 +08:00

45 lines
1.4 KiB
C#

using System.Security.Cryptography;
using DysonNetwork.Shared.Models;
using Microsoft.EntityFrameworkCore;
namespace DysonNetwork.Pass.Affiliation;
public class AffiliationSpellService(AppDatabase db)
{
public async Task<SnAffiliationSpell> CreateAffiliationSpell(Guid accountId, string? spellWord)
{
spellWord ??= _GenerateRandomString(8);
var hasTaken = await db.AffiliationSpells.AnyAsync(s => s.Spell == spellWord);
if (hasTaken) throw new InvalidOperationException("The spell has been taken.");
var spell = new SnAffiliationSpell
{
AccountId = accountId,
Spell = spellWord
};
db.AffiliationSpells.Add(spell);
await db.SaveChangesAsync();
return spell;
}
public async Task<SnAffiliationSpell?> GetAffiliationSpell(string spellWord)
{
var spell = await db.AffiliationSpells.FirstOrDefaultAsync(s => s.Spell == spellWord);
return spell;
}
private static string _GenerateRandomString(int length)
{
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var result = new char[length];
using var rng = RandomNumberGenerator.Create();
for (var i = 0; i < length; i++)
{
var bytes = new byte[1];
rng.GetBytes(bytes);
result[i] = chars[bytes[0] % chars.Length];
}
return new string(result);
}
}