Files
flatrender/services/identity/FlatRender.IdentitySvc/Application/Services/TokenService.cs
T
soroush.asadi 81912cac66
Build backend images / build content-svc (push) Failing after 14s
Build backend images / build file-svc (push) Failing after 1m28s
Build backend images / build gateway (push) Failing after 1m43s
Build backend images / build identity-svc (push) Failing after 3m0s
Build backend images / build notification-svc (push) Failing after 51s
Build backend images / build render-svc (push) Failing after 1m3s
Build backend images / build studio-svc (push) Failing after 1m1s
feat(render): full-screen render page, one-active-render limit, app-wide progress
Concurrent-render ceiling (a user runs 1 render at a time unless granted more):
- Identity: TokenService emits max_renders claim from User.ParallelRenderingCeiling
- Identity: admin POST /v1/users/{id}/render-slots (AdminService.SetRenderSlotsAsync,
  clamped 1..50) — gamification or admin raises a user's ceiling
- render-svc: middleware reads max_renders (default 1); CreateJob rejects with 409
  active_render_limit when active jobs >= ceiling
- render-svc: db.CountActiveJobs + ListActiveJobs; GET /v1/renders/active returns
  in-flight renders + can_start_new

Full-screen render page (replaces the modal):
- /studio/render/[projectId]: config (resolution/fps) → live preview + progress →
  download; resumes this project's in-flight render on mount; blocks when another
  render is active; reads ?preset=
- StudioTopBar export menu now navigates to the page; RenderModal deleted (dead)

App-wide minimal progress:
- GlobalRenderProgress pill mounted in the locale layout for authed users; polls
  /api/render/active every 4s, shows thumbnail + step + % on every page, click →
  the render page; hidden on the render page and when idle

Admin: UserActions gains a "concurrent render slots" control.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-05 16:48:05 +03:30

103 lines
4.1 KiB
C#

using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using FlatRender.IdentitySvc.Application.Services.Interfaces;
using FlatRender.IdentitySvc.Domain.Entities;
using Microsoft.IdentityModel.Tokens;
namespace FlatRender.IdentitySvc.Application.Services;
public class TokenService(IConfiguration config) : ITokenService
{
private readonly string _secret = config["Jwt:Secret"]
?? throw new InvalidOperationException("Jwt:Secret not configured");
private readonly string _issuer = config["Jwt:Issuer"] ?? "flatrender-identity";
private readonly string _audience = config["Jwt:Audience"] ?? "flatrender";
private readonly int _accessTokenMinutes = int.Parse(config["Jwt:AccessTokenMinutes"] ?? "15");
public string GenerateAccessToken(User user, Tenant tenant)
{
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_secret));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
// Role claim drives [Authorize(Roles = "...")] in the other services.
var role = user.IsAdmin ? "Admin" : user.IsTenantAdmin ? "TenantAdmin" : "User";
var claims = new List<Claim>
{
new(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new("tenant_id", tenant.Id.ToString()),
new("tenant_slug", tenant.Slug),
new("is_admin", user.IsAdmin.ToString().ToLower()),
new("is_tenant_admin", user.IsTenantAdmin.ToString().ToLower()),
new("role", role),
// Concurrent-render ceiling — render-svc enforces "active renders < max_renders".
// Admin grants or gamification raise ParallelRenderingCeiling; default is 1.
new("max_renders", Math.Max(1, user.ParallelRenderingCeiling).ToString()),
};
if (!string.IsNullOrEmpty(user.Email))
claims.Add(new(JwtRegisteredClaimNames.Email, user.Email));
var token = new JwtSecurityToken(
issuer: _issuer,
audience: _audience,
claims: claims,
expires: DateTime.UtcNow.AddMinutes(_accessTokenMinutes),
signingCredentials: creds
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
public string GenerateRefreshToken()
=> Convert.ToBase64String(RandomNumberGenerator.GetBytes(64));
public string HashToken(string token)
{
var bytes = SHA256.HashData(Encoding.UTF8.GetBytes(token));
return Convert.ToHexString(bytes).ToLower();
}
public (Guid userId, Guid tenantId, bool isAdmin) ValidateAccessToken(string token)
{
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_secret));
var handler = new JwtSecurityTokenHandler();
var parameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = key,
ValidateIssuer = true,
ValidIssuer = _issuer,
ValidateAudience = true,
ValidAudience = _audience,
ValidateLifetime = true,
};
var principal = handler.ValidateToken(token, parameters, out _);
var userId = Guid.Parse(principal.FindFirstValue(JwtRegisteredClaimNames.Sub)!);
var tenantId = Guid.Parse(principal.FindFirstValue("tenant_id")!);
var isAdmin = bool.Parse(principal.FindFirstValue("is_admin") ?? "false");
return (userId, tenantId, isAdmin);
}
public string GenerateServiceToken()
{
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_secret));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: _issuer,
audience: _audience,
claims: [new("type", "service"), new("service", "identity")],
expires: DateTime.UtcNow.AddHours(24),
signingCredentials: creds
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
}