Spaces:
Running
Running
Commit ·
3c872cf
1
Parent(s): 3105a78
Auth: Implement cryptographic one-time claim token verification and ownership transfer
Browse files4 unmodified lines56789108 unmodified lines19202122232425262728293075 unmodified lines1061071081091101111121131141151161172 unmodified lines1201211221231241253 unmodified lines1291301311324 unmodified linesusing FlowAPI.Domain.Entities;using Microsoft.AspNetCore.Authorization;using Microsoft.AspNetCore.Mvc;using System;using System.Security.Claims;using System.Threading.Tasks;8 unmodified linesprivate readonly IGraphService _graphService;private readonly ITokenService _tokenService;private readonly IUserRepository _userRepo;public AgentCanvasController(IGraphService graphService, ITokenService tokenService, IUserRepository userRepo){_graphService = graphService;_tokenService = tokenService;_userRepo = userRepo;}[AllowAnonymous]75 unmodified linesreturn BadRequest(new { message = "Failed to store generated task nodes in database." });}// 4. Return successful response with the Canvas redirection URLreturn Ok(new{success = true,graphId = graphResponse.Id,canvasUrl = $"/canvas/{graphResponse.Id}"});}catch (Exception ex)2 unmodified lines}}private Guid CurrentUserId{get3 unmodified lines}}}}4 unmodified lines5678910118 unmodified lines20212223242526272829303132333435363738394075 unmodified lines1161171181191201211221231241251261271281291301311322 unmodified lines1351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292303 unmodified lines2342352362372382392402412424 unmodified linesusing FlowAPI.Domain.Entities;using Microsoft.AspNetCore.Authorization;using Microsoft.AspNetCore.Mvc;using Microsoft.Extensions.Configuration;using System;using System.Security.Claims;using System.Threading.Tasks;8 unmodified linesprivate readonly IGraphService _graphService;private readonly ITokenService _tokenService;private readonly IUserRepository _userRepo;private readonly IGraphRepository _graphRepo;private readonly IConfiguration _config;public AgentCanvasController(IGraphService graphService,ITokenService tokenService,IUserRepository userRepo,IGraphRepository graphRepo,IConfiguration config){_graphService = graphService;_tokenService = tokenService;_userRepo = userRepo;_graphRepo = graphRepo;_config = config;}[AllowAnonymous]75 unmodified linesreturn BadRequest(new { message = "Failed to store generated task nodes in database." });}// 4. Generate a secure, signed claim token valid for 24 hoursvar claimToken = GenerateClaimToken(graphResponse.Id, DateTime.UtcNow.AddHours(24));var claimUrl = $"https://danildrotik-flowweb.hf.space/claim?token={claimToken}";return Ok(new{success = true,graphId = graphResponse.Id,canvasUrl = $"/canvas/{graphResponse.Id}",claimToken = claimToken,claimUrl = claimUrl});}catch (Exception ex)2 unmodified lines}}[HttpPost("claim")]public async Task<IActionResult> ClaimCanvas([FromBody] ClaimRequestDto dto){if (CurrentUserId == Guid.Empty)return Unauthorized(new { message = "User authentication required." });if (dto == null || string.IsNullOrWhiteSpace(dto.Token))return BadRequest(new { message = "Claim token is required." });var graphId = VerifyClaimToken(dto.Token);if (graphId == null)return BadRequest(new { message = "Claim token is invalid or has expired." });try{var dbGraph = await _graphRepo.GetByIdAsync(graphId.Value);if (dbGraph == null)return NotFound(new { message = "Board not found." });// If the user already owns the board, return success immediatelyif (dbGraph.UserId == CurrentUserId){return Ok(new { success = true, graphId = graphId.Value, message = "You already own this board!" });}// Verify that the board is currently owned by the agent system user (unclaimed)var agentId = Guid.Parse("33d1ae31-bf51-4b12-89d0-8e574e7916ab");if (dbGraph.UserId != agentId){return BadRequest(new { message = "This board has already been claimed by another user." });}// Transfer ownership in the database!dbGraph.UserId = CurrentUserId;await _graphRepo.UpdateAsync(dbGraph);return Ok(new { success = true, graphId = graphId.Value });}catch (Exception ex){return BadRequest(new { message = $"Failed to claim board: {ex.Message}" });}}private string GenerateClaimToken(Guid graphId, DateTime expiry){var key = _config["Jwt:Key"] ?? "TaskFlow_Secret_Key_For_JWT_Authentication_2026_!@#";var payload = $"{graphId}|{expiry.Ticks}";using (var hmac = new System.Security.Cryptography.HMACSHA256(System.Text.Encoding.UTF8.GetBytes(key))){var hash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(payload));var signature = Convert.ToBase64String(hash);return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes($"{payload}|{signature}"));}}private Guid? VerifyClaimToken(string claimToken){try{var key = _config["Jwt:Key"] ?? "TaskFlow_Secret_Key_For_JWT_Authentication_2026_!@#";var decodedBytes = Convert.FromBase64String(claimToken);var decodedString = System.Text.Encoding.UTF8.GetString(decodedBytes);var parts = decodedString.Split('|');if (parts.Length != 3) return null;var graphIdStr = parts[0];var ticksStr = parts[1];var signature = parts[2];var payload = $"{graphIdStr}|{ticksStr}";using (var hmac = new System.Security.Cryptography.HMACSHA256(System.Text.Encoding.UTF8.GetBytes(key))){var hash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(payload));var expectedSignature = Convert.ToBase64String(hash);if (signature != expectedSignature) return null;}if (!long.TryParse(ticksStr, out var ticks)) return null;var expiry = new DateTime(ticks, DateTimeKind.Utc);if (DateTime.UtcNow > expiry) return null;return Guid.TryParse(graphIdStr, out var graphId) ? graphId : null;}catch{return null;}}private Guid CurrentUserId{get3 unmodified lines}}}public class ClaimRequestDto{public string Token { get; set; } = string.Empty;}}
FlowAPI/Controllers/AgentCanvasController.cs+113-3