using DeluxeBackend.Controllers.Auth; // Added to access ConnectController explicitly using DeluxeBackend.Models; using DeluxeBackend.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; using System.ComponentModel.DataAnnotations; using System.Security.Claims; using System.Threading.Tasks; namespace DeluxeBackend.Controllers.Auth { [Route("Auth/account")] [ApiController] [Authorize] public class AccountController(IJwtService jwt, ILiteDbService db, DiscordBotService discord) : ControllerBase { [HttpPost("me/remoteauth")] public async Task RemoteAuth([FromForm(Name = "code"), Required] string code) { if (string.IsNullOrWhiteSpace(code)) { return BadRequest(new { error = "invalid_request", description = "Authorization code cannot be empty." }); } Account? account = await jwt.GetLogin(User); if (account == null) { return Unauthorized(new { error = "unauthorized", description = "Session expired or invalid user profile." }); } string? matchingServerCode = null; string upperUserCode = code.Trim().ToUpperInvariant(); DateTime cachedCreatedAt = DateTime.UtcNow; foreach (var kvp in ConnectController.DeviceAuthorizationKeys) { if (kvp.Value.UserCode == upperUserCode) { matchingServerCode = kvp.Key; cachedCreatedAt = kvp.Value.CreatedAt; break; } } if (matchingServerCode == null) { return BadRequest(new { error = "invalid_code", description = "The authorization code is invalid or has expired." }); } if (DateTime.UtcNow - cachedCreatedAt > TimeSpan.FromMinutes(15)) { ConnectController.DeviceAuthorizationKeys.TryRemove(matchingServerCode, out _); return BadRequest(new { error = "code_expired", description = "The authorization code has expired." }); } var updatedTuple = (UserCode: upperUserCode, AccId: account.Id, CreatedAt: cachedCreatedAt); if (!ConnectController.DeviceAuthorizationKeys.TryUpdate(matchingServerCode, updatedTuple, (upperUserCode, -1, cachedCreatedAt))) { return BadRequest(new { error = "transaction_conflict", description = "Authorization signature was modified or consumed." }); } return Ok(new { Success = true, message = "Device authorized successfully. Your studio instance will resume shortly." }); } } }