From c8cd483d20c12f71d02f52304fa44ff8c3c2dcf9 Mon Sep 17 00:00:00 2001 From: sam Date: Sun, 24 Nov 2024 15:40:12 +0100 Subject: [PATCH] feat: sid redirect controller --- Foxnouns.Backend/Controllers/SidController.cs | 51 ++++++++++++++++++- 1 file changed, 50 insertions(+), 1 deletion(-) diff --git a/Foxnouns.Backend/Controllers/SidController.cs b/Foxnouns.Backend/Controllers/SidController.cs index 26c66ef..b8f5948 100644 --- a/Foxnouns.Backend/Controllers/SidController.cs +++ b/Foxnouns.Backend/Controllers/SidController.cs @@ -1,3 +1,52 @@ +using System.Diagnostics.CodeAnalysis; +using Foxnouns.Backend.Database; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; + namespace Foxnouns.Backend.Controllers; -public class SidController { } +[Route("/sid")] +[SuppressMessage( + "Performance", + "CA1862:Use the \'StringComparison\' method overloads to perform case-insensitive string comparisons", + Justification = "Not usable with EFCore" +)] +public class SidController(Config config, DatabaseContext db) : ApiControllerBase +{ + [HttpGet("{**id}")] + public async Task ResolveSidAsync(string id, CancellationToken ct = default) => + id.Length switch + { + 5 => await ResolveUserSidAsync(id, ct), + 6 => await ResolveMemberSidAsync(id, ct), + _ => Redirect(config.BaseUrl), + }; + + private async Task ResolveUserSidAsync(string id, CancellationToken ct = default) + { + var username = await db + .Users.Where(u => u.Sid == id.ToLowerInvariant() && !u.Deleted) + .Select(u => u.Username) + .FirstOrDefaultAsync(ct); + if (username == null) + return Redirect(config.BaseUrl); + + return Redirect($"{config.BaseUrl}/@{username}"); + } + + private async Task ResolveMemberSidAsync( + string id, + CancellationToken ct = default + ) + { + var member = await db + .Members.Include(m => m.User) + .Where(m => m.Sid == id.ToLowerInvariant() && !m.User.Deleted) + .Select(m => new { m.Name, m.User.Username }) + .FirstOrDefaultAsync(ct); + if (member == null) + return Redirect(config.BaseUrl); + + return Redirect($"{config.BaseUrl}/@{member.Username}/{member.Name}"); + } +}