feat: complete node-agent pipeline, TLS proxy, billing cancel, password reset
Node-agent — full render pipeline (items 1-3):
- render-svc: ClaimedJob now includes aep_download_url (presigned MinIO GET,
2h TTL, path=templates/{original_project_id}/template.aep)
- render-svc: POST /v1/internal/render/jobs/:id/output-upload-url
allocates Export row + returns presigned MinIO PUT URL + export_id
- render-svc: db.CreateExportForJob() inserts export row with 30-day retention
- render-svc: InternalHandler now owns minio client (templatesBucket + exportsBucket)
MINIO_TEMPLATES_BUCKET env var (default flatrender-templates)
- node-agent: runner/download.go — DownloadFile() + UploadFile() (stdlib only)
- node-agent: client.GetOutputUploadURL() + ClaimedJob.AEPDownloadURL field
- node-agent: runJob() full flow: download AEP → render → get upload URL →
PUT output to MinIO → Complete(export_id)
All steps are non-fatal with fallback (AEP miss → mock, upload fail → no export)
TLS reverse proxy (item 15):
- Caddyfile: three virtual hosts (DOMAIN, API_DOMAIN, STORAGE_DOMAIN)
auto-TLS via Let's Encrypt; security headers; 512MB upload limit on API
- docker-compose.v2.yml: caddy:2-alpine service, ports 80/443/443udp,
caddy_data + caddy_config volumes; env vars DOMAIN/API_DOMAIN/STORAGE_DOMAIN/ACME_EMAIL
- .env.v2.example: new Caddy + MINIO_TEMPLATES_BUCKET entries
Billing portal (item 5):
- Identity: POST /v1/users/me/plan/cancel — sets cancelled_at, auto_renew=false
(access continues to expiry); 404 when no active plan
- POST /api/billing/cancel — frontend proxy, validates auth
- GET /api/billing/portal — redirects to /dashboard/settings?tab=billing
- SettingsBilling: "Cancel plan" button with confirm dialog + optimistic UI,
"Change plan" button; becomes "use client" component
Password reset UI (item 7):
- POST /api/auth/password-reset — proxies /v1/auth/password/reset/request
(always 200, anti-enumeration)
- POST /api/auth/password-reset-confirm — proxies /v1/auth/password/reset/confirm
- AuthPageContent: "Forgot password?" link on sign-in tab opens 2-step reset flow
(email → OTP+new-password) without leaving the auth page
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -56,3 +56,15 @@ TARA_CALLBACK_URL=https://yourdomain.com/v1/payments/callback/tara
|
|||||||
# Get keys from https://dashboard.stripe.com/apikeys
|
# Get keys from https://dashboard.stripe.com/apikeys
|
||||||
STRIPE_SECRET_KEY=sk_test_...
|
STRIPE_SECRET_KEY=sk_test_...
|
||||||
STRIPE_PUBLISHABLE_KEY=pk_test_...
|
STRIPE_PUBLISHABLE_KEY=pk_test_...
|
||||||
|
|
||||||
|
# ── Caddy TLS reverse proxy ───────────────────────────────────────────────────
|
||||||
|
# Public-facing domains (Let's Encrypt will provision certs automatically).
|
||||||
|
# Leave as localhost for local dev (Caddy uses self-signed cert).
|
||||||
|
DOMAIN=flatrender.io
|
||||||
|
API_DOMAIN=api.flatrender.io
|
||||||
|
STORAGE_DOMAIN=storage.flatrender.io
|
||||||
|
ACME_EMAIL=admin@flatrender.io
|
||||||
|
|
||||||
|
# ── MinIO templates bucket ────────────────────────────────────────────────────
|
||||||
|
# Bucket where .aep template files are stored (uploaded via admin panel).
|
||||||
|
MINIO_TEMPLATES_BUCKET=flatrender-templates
|
||||||
|
|||||||
@@ -0,0 +1,57 @@
|
|||||||
|
# FlatRender V2 — Caddy reverse proxy
|
||||||
|
#
|
||||||
|
# Domains are injected via environment variables so this file is environment-agnostic.
|
||||||
|
# Set in .env.v2:
|
||||||
|
# DOMAIN e.g. flatrender.io (→ https://flatrender.io)
|
||||||
|
# API_DOMAIN e.g. api.flatrender.io (→ https://api.flatrender.io)
|
||||||
|
# STORAGE_DOMAIN e.g. storage.flatrender.io (→ https://storage.flatrender.io)
|
||||||
|
#
|
||||||
|
# Caddy auto-provisions Let's Encrypt TLS for all three. For local dev without
|
||||||
|
# real domains, replace with http:// blocks and remove the ACME config.
|
||||||
|
|
||||||
|
{env.DOMAIN} {
|
||||||
|
# Frontend (Next.js standalone, port 3000 inside Docker)
|
||||||
|
reverse_proxy frontend:3000
|
||||||
|
|
||||||
|
# Security headers
|
||||||
|
header {
|
||||||
|
Strict-Transport-Security "max-age=31536000; includeSubDomains"
|
||||||
|
X-Content-Type-Options "nosniff"
|
||||||
|
X-Frame-Options "SAMEORIGIN"
|
||||||
|
Referrer-Policy "strict-origin-when-cross-origin"
|
||||||
|
-Server
|
||||||
|
}
|
||||||
|
|
||||||
|
encode gzip
|
||||||
|
}
|
||||||
|
|
||||||
|
{env.API_DOMAIN} {
|
||||||
|
# V2 API gateway (port 8080 inside Docker)
|
||||||
|
reverse_proxy gateway:8080
|
||||||
|
|
||||||
|
header {
|
||||||
|
Strict-Transport-Security "max-age=31536000; includeSubDomains"
|
||||||
|
X-Content-Type-Options "nosniff"
|
||||||
|
-Server
|
||||||
|
}
|
||||||
|
|
||||||
|
# Allow large body for file uploads routed through the gateway
|
||||||
|
request_body {
|
||||||
|
max_size 512MB
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
{env.STORAGE_DOMAIN} {
|
||||||
|
# MinIO S3 API (port 9000 inside Docker) — used for presigned URL downloads
|
||||||
|
reverse_proxy minio:9000
|
||||||
|
|
||||||
|
header {
|
||||||
|
Strict-Transport-Security "max-age=31536000; includeSubDomains"
|
||||||
|
X-Content-Type-Options "nosniff"
|
||||||
|
-Server
|
||||||
|
}
|
||||||
|
|
||||||
|
# Pre-flight (CORS) passthrough — MinIO handles its own CORS headers
|
||||||
|
@options method OPTIONS
|
||||||
|
respond @options 204
|
||||||
|
}
|
||||||
@@ -296,6 +296,41 @@ services:
|
|||||||
retries: 3
|
retries: 3
|
||||||
start_period: 30s
|
start_period: 30s
|
||||||
|
|
||||||
|
# ── Caddy (TLS reverse proxy) ───────────────────────────────────────────────
|
||||||
|
# Handles Let's Encrypt certificates and terminates HTTPS for all three
|
||||||
|
# public domains: frontend, API gateway, and MinIO storage.
|
||||||
|
#
|
||||||
|
# Required .env.v2 vars: DOMAIN, API_DOMAIN, STORAGE_DOMAIN
|
||||||
|
# Set ACME_EMAIL to a real address so Let's Encrypt can contact you.
|
||||||
|
#
|
||||||
|
# For local dev (no real domain), comment out this block and access
|
||||||
|
# services directly on their host ports (:3000, :8088, :9000).
|
||||||
|
caddy:
|
||||||
|
image: caddy:2-alpine
|
||||||
|
container_name: fr2-caddy
|
||||||
|
restart: unless-stopped
|
||||||
|
ports:
|
||||||
|
- "80:80"
|
||||||
|
- "443:443"
|
||||||
|
- "443:443/udp" # HTTP/3 QUIC
|
||||||
|
volumes:
|
||||||
|
- ./Caddyfile:/etc/caddy/Caddyfile:ro
|
||||||
|
- caddy_data:/data
|
||||||
|
- caddy_config:/config
|
||||||
|
environment:
|
||||||
|
DOMAIN: "${DOMAIN:-localhost}"
|
||||||
|
API_DOMAIN: "${API_DOMAIN:-api.localhost}"
|
||||||
|
STORAGE_DOMAIN: "${STORAGE_DOMAIN:-storage.localhost}"
|
||||||
|
ACME_EMAIL: "${ACME_EMAIL:-admin@example.com}"
|
||||||
|
depends_on:
|
||||||
|
- frontend
|
||||||
|
- gateway
|
||||||
|
- minio
|
||||||
|
networks:
|
||||||
|
- default
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
pgdata:
|
pgdata:
|
||||||
|
caddy_data:
|
||||||
|
caddy_config:
|
||||||
miniodata:
|
miniodata:
|
||||||
|
|||||||
+3
@@ -9,4 +9,7 @@ public interface IPlanService
|
|||||||
Task<PlanResponse> GetByIdAsync(Guid planId);
|
Task<PlanResponse> GetByIdAsync(Guid planId);
|
||||||
Task<UserPlanResponse?> GetCurrentPlanAsync(Guid userId);
|
Task<UserPlanResponse?> GetCurrentPlanAsync(Guid userId);
|
||||||
Task<PurchasePlanResponse> PurchasePlanAsync(Guid userId, Guid tenantId, PurchasePlanRequest request);
|
Task<PurchasePlanResponse> PurchasePlanAsync(Guid userId, Guid tenantId, PurchasePlanRequest request);
|
||||||
|
/// <summary>Cancel the current active plan. The subscription is marked cancelled
|
||||||
|
/// and will not auto-renew. Access continues until the expiry date.</summary>
|
||||||
|
Task CancelPlanAsync(Guid userId);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -161,6 +161,19 @@ public class PlanService(IdentityDbContext db) : IPlanService
|
|||||||
await Task.CompletedTask; // placeholder for future async work
|
await Task.CompletedTask; // placeholder for future async work
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task CancelPlanAsync(Guid userId)
|
||||||
|
{
|
||||||
|
var userPlan = await db.UserPlans
|
||||||
|
.Where(up => up.UserId == userId && up.CancelledAt == null && up.ExpiresAt > DateTime.UtcNow)
|
||||||
|
.OrderByDescending(up => up.StartsAt)
|
||||||
|
.FirstOrDefaultAsync()
|
||||||
|
?? throw new KeyNotFoundException("No active plan to cancel");
|
||||||
|
|
||||||
|
userPlan.CancelledAt = DateTime.UtcNow;
|
||||||
|
userPlan.AutoRenew = false;
|
||||||
|
await db.SaveChangesAsync();
|
||||||
|
}
|
||||||
|
|
||||||
private static PlanResponse MapPlanResponse(Plan p) => new(
|
private static PlanResponse MapPlanResponse(Plan p) => new(
|
||||||
p.Id, p.Code, p.Name, p.Description,
|
p.Id, p.Code, p.Name, p.Description,
|
||||||
p.PriceMinor, p.BeforePriceMinor, p.Currency, p.BillingPeriod.ToString(),
|
p.PriceMinor, p.BeforePriceMinor, p.Currency, p.BillingPeriod.ToString(),
|
||||||
|
|||||||
@@ -39,6 +39,26 @@ public class PlansController(IPlanService planService) : ControllerBase
|
|||||||
return Ok(result);
|
return Ok(result);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Cancel the current active subscription. The plan stays active until its
|
||||||
|
/// expiry date but will not auto-renew. Returns 404 when no active plan exists.
|
||||||
|
/// </summary>
|
||||||
|
[HttpPost("users/me/plan/cancel")]
|
||||||
|
[ProducesResponseType(204)]
|
||||||
|
[ProducesResponseType(404)]
|
||||||
|
public async Task<IActionResult> Cancel()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await planService.CancelPlanAsync(GetUserId());
|
||||||
|
return NoContent();
|
||||||
|
}
|
||||||
|
catch (KeyNotFoundException ex)
|
||||||
|
{
|
||||||
|
return NotFound(new { error = ex.Message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private Guid GetUserId() => Guid.Parse(User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value
|
private Guid GetUserId() => Guid.Parse(User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value
|
||||||
?? User.FindFirst("sub")?.Value ?? throw new UnauthorizedAccessException());
|
?? User.FindFirst("sub")?.Value ?? throw new UnauthorizedAccessException());
|
||||||
|
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"os/signal"
|
"os/signal"
|
||||||
|
"path/filepath"
|
||||||
"runtime"
|
"runtime"
|
||||||
"sync"
|
"sync"
|
||||||
"syscall"
|
"syscall"
|
||||||
@@ -227,12 +228,20 @@ func (a *Agent) tryClaimAndRun(ctx context.Context) {
|
|||||||
func (a *Agent) runJob(ctx context.Context, job *client.ClaimedJob) {
|
func (a *Agent) runJob(ctx context.Context, job *client.ClaimedJob) {
|
||||||
log.Printf("[job %s] starting render", job.JobID)
|
log.Printf("[job %s] starting render", job.JobID)
|
||||||
|
|
||||||
// In a full implementation, the agent would:
|
// ── Step 1: Download .aep template ───────────────────────────────────────
|
||||||
// 1. Fetch the saved project from the studio service
|
aepPath := ""
|
||||||
// 2. Download the .aep template from MinIO
|
if job.AEPDownloadURL != "" && a.cfg.AEPath != "" {
|
||||||
// 3. Inject user customisations into the composition via JSXB/AE scripting
|
localAEP := filepath.Join(a.cfg.WorkDir, "templates", job.JobID, "template.aep")
|
||||||
// Then call runner.Run().
|
dlCtx, dlCancel := context.WithTimeout(ctx, 10*time.Minute)
|
||||||
// For the skeleton we pass an empty AEPFilePath, which triggers mock mode.
|
n, dlErr := runner.DownloadFile(dlCtx, job.AEPDownloadURL, localAEP)
|
||||||
|
dlCancel()
|
||||||
|
if dlErr != nil {
|
||||||
|
log.Printf("[job %s] AEP download failed (%v) — falling back to mock", job.JobID, dlErr)
|
||||||
|
} else {
|
||||||
|
log.Printf("[job %s] AEP downloaded (%d bytes) → %s", job.JobID, n, localAEP)
|
||||||
|
aepPath = localAEP
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
rJob := &runner.Job{
|
rJob := &runner.Job{
|
||||||
JobID: job.JobID,
|
JobID: job.JobID,
|
||||||
@@ -242,7 +251,7 @@ func (a *Agent) runJob(ctx context.Context, job *client.ClaimedJob) {
|
|||||||
FrameRate: job.FrameRate,
|
FrameRate: job.FrameRate,
|
||||||
HasMusic: job.HasMusic,
|
HasMusic: job.HasMusic,
|
||||||
HasVoiceover: job.HasVoiceover,
|
HasVoiceover: job.HasVoiceover,
|
||||||
AEPFilePath: "", // TODO: download from MinIO
|
AEPFilePath: aepPath,
|
||||||
}
|
}
|
||||||
|
|
||||||
onProgress := func(ctx context.Context, pct int, msg string) error {
|
onProgress := func(ctx context.Context, pct int, msg string) error {
|
||||||
@@ -259,6 +268,7 @@ func (a *Agent) runJob(ctx context.Context, job *client.ClaimedJob) {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Step 2: Render ───────────────────────────────────────────────────────
|
||||||
outputPath, err := runner.Run(ctx, a.cfg.AEPath, a.cfg.WorkDir, rJob, onProgress, onPreview)
|
outputPath, err := runner.Run(ctx, a.cfg.AEPath, a.cfg.WorkDir, rJob, onProgress, onPreview)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if ctx.Err() != nil {
|
if ctx.Err() != nil {
|
||||||
@@ -273,17 +283,33 @@ func (a *Agent) runJob(ctx context.Context, job *client.ClaimedJob) {
|
|||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Printf("[job %s] render done → %s", job.JobID, outputPath)
|
log.Printf("[job %s] render done → %s", job.JobID, outputPath)
|
||||||
|
|
||||||
// In full production: upload outputPath to MinIO, create an Export record,
|
// ── Step 3: Get presigned upload URL + upload output to MinIO ─────────────
|
||||||
// pass the export UUID to Complete(). Skeleton passes nil (no export yet).
|
var exportID *string
|
||||||
completeCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
uploadCtx, uploadCancel := context.WithTimeout(context.Background(), 5*time.Minute)
|
||||||
defer cancel()
|
defer uploadCancel()
|
||||||
if err := a.orch.Complete(completeCtx, job.JobID, nil); err != nil {
|
|
||||||
|
uploadInfo, urlErr := a.orch.GetOutputUploadURL(uploadCtx, job.JobID)
|
||||||
|
if urlErr != nil {
|
||||||
|
log.Printf("[job %s] get upload URL failed: %v — completing without export", job.JobID, urlErr)
|
||||||
|
} else {
|
||||||
|
log.Printf("[job %s] uploading output to %s", job.JobID, uploadInfo.ObjectKey)
|
||||||
|
if _, upErr := runner.UploadFile(uploadCtx, uploadInfo.UploadURL, outputPath); upErr != nil {
|
||||||
|
log.Printf("[job %s] upload failed: %v — completing without export", job.JobID, upErr)
|
||||||
|
} else {
|
||||||
|
log.Printf("[job %s] upload complete (export %s)", job.JobID, uploadInfo.ExportID)
|
||||||
|
exportID = &uploadInfo.ExportID
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Step 4: Report complete ───────────────────────────────────────────────
|
||||||
|
completeCtx, completeCancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
defer completeCancel()
|
||||||
|
if err := a.orch.Complete(completeCtx, job.JobID, exportID); err != nil {
|
||||||
log.Printf("[job %s] complete report error: %v", job.JobID, err)
|
log.Printf("[job %s] complete report error: %v", job.JobID, err)
|
||||||
} else {
|
} else {
|
||||||
log.Printf("[job %s] reported as completed", job.JobID)
|
log.Printf("[job %s] reported as completed (export=%v)", job.JobID, exportID)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -106,6 +106,16 @@ type ClaimedJob struct {
|
|||||||
FrameRate int `json:"frame_rate"`
|
FrameRate int `json:"frame_rate"`
|
||||||
HasMusic bool `json:"has_music"`
|
HasMusic bool `json:"has_music"`
|
||||||
HasVoiceover bool `json:"has_voiceover"`
|
HasVoiceover bool `json:"has_voiceover"`
|
||||||
|
// AEPDownloadURL is a presigned MinIO GET URL for the .aep template file.
|
||||||
|
// Empty when the template has not been uploaded yet — triggers mock render.
|
||||||
|
AEPDownloadURL string `json:"aep_download_url,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// OutputUploadURLResponse is returned by GetOutputUploadURL.
|
||||||
|
type OutputUploadURLResponse struct {
|
||||||
|
ExportID string `json:"export_id"`
|
||||||
|
UploadURL string `json:"upload_url"`
|
||||||
|
ObjectKey string `json:"object_key"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// ProgressRequest reports render progress (frame-level) for a job.
|
// ProgressRequest reports render progress (frame-level) for a job.
|
||||||
@@ -204,6 +214,25 @@ func (c *Client) UpdatePreview(ctx context.Context, jobID, imageB64 string) erro
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetOutputUploadURL asks the orchestrator to allocate an Export row and
|
||||||
|
// return a presigned MinIO PUT URL for the rendered output file.
|
||||||
|
func (c *Client) GetOutputUploadURL(ctx context.Context, jobID string) (*OutputUploadURLResponse, error) {
|
||||||
|
resp, err := c.do(ctx, http.MethodPost,
|
||||||
|
fmt.Sprintf("/v1/internal/render/jobs/%s/output-upload-url", jobID), nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
if resp.StatusCode >= 300 {
|
||||||
|
return nil, fmt.Errorf("output-upload-url: HTTP %d", resp.StatusCode)
|
||||||
|
}
|
||||||
|
var out OutputUploadURLResponse
|
||||||
|
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
|
||||||
|
return nil, fmt.Errorf("decode: %w", err)
|
||||||
|
}
|
||||||
|
return &out, nil
|
||||||
|
}
|
||||||
|
|
||||||
// Complete marks a render job as Done.
|
// Complete marks a render job as Done.
|
||||||
func (c *Client) Complete(ctx context.Context, jobID string, exportID *string) error {
|
func (c *Client) Complete(ctx context.Context, jobID string, exportID *string) error {
|
||||||
resp, err := c.do(ctx, http.MethodPost,
|
resp, err := c.do(ctx, http.MethodPost,
|
||||||
|
|||||||
@@ -0,0 +1,82 @@
|
|||||||
|
// download.go fetches a remote file (presigned MinIO URL or any HTTP URL) and
|
||||||
|
// saves it to a local path. Uses stdlib only — no external HTTP client needed.
|
||||||
|
package runner
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
)
|
||||||
|
|
||||||
|
// DownloadFile fetches the resource at rawURL and writes it to destPath,
|
||||||
|
// creating parent directories as needed. Returns the number of bytes written.
|
||||||
|
func DownloadFile(ctx context.Context, rawURL, destPath string) (int64, error) {
|
||||||
|
if err := os.MkdirAll(filepath.Dir(destPath), 0o755); err != nil {
|
||||||
|
return 0, fmt.Errorf("mkdir: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
|
||||||
|
if err != nil {
|
||||||
|
return 0, fmt.Errorf("new request: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
resp, err := http.DefaultClient.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return 0, fmt.Errorf("GET: %w", err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
return 0, fmt.Errorf("server returned %d", resp.StatusCode)
|
||||||
|
}
|
||||||
|
|
||||||
|
f, err := os.Create(destPath)
|
||||||
|
if err != nil {
|
||||||
|
return 0, fmt.Errorf("create file: %w", err)
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
|
||||||
|
n, err := io.Copy(f, resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
return 0, fmt.Errorf("write: %w", err)
|
||||||
|
}
|
||||||
|
return n, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// UploadFile PUTs a local file to a presigned MinIO/S3 URL.
|
||||||
|
// MinIO presigned PUT expects the raw bytes in the request body with
|
||||||
|
// Content-Type application/octet-stream.
|
||||||
|
func UploadFile(ctx context.Context, rawURL, filePath string) (int64, error) {
|
||||||
|
f, err := os.Open(filePath)
|
||||||
|
if err != nil {
|
||||||
|
return 0, fmt.Errorf("open: %w", err)
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
|
||||||
|
stat, err := f.Stat()
|
||||||
|
if err != nil {
|
||||||
|
return 0, fmt.Errorf("stat: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
req, err := http.NewRequestWithContext(ctx, http.MethodPut, rawURL, f)
|
||||||
|
if err != nil {
|
||||||
|
return 0, fmt.Errorf("new request: %w", err)
|
||||||
|
}
|
||||||
|
req.ContentLength = stat.Size()
|
||||||
|
req.Header.Set("Content-Type", "application/octet-stream")
|
||||||
|
|
||||||
|
resp, err := http.DefaultClient.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return 0, fmt.Errorf("PUT: %w", err)
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
// MinIO returns 200 on successful PUT of presigned objects
|
||||||
|
if resp.StatusCode >= 300 {
|
||||||
|
return 0, fmt.Errorf("upload server returned %d", resp.StatusCode)
|
||||||
|
}
|
||||||
|
return stat.Size(), nil
|
||||||
|
}
|
||||||
@@ -32,7 +32,8 @@ func main() {
|
|||||||
minioAccessKey := getEnv("MINIO_ACCESS_KEY", "minioadmin")
|
minioAccessKey := getEnv("MINIO_ACCESS_KEY", "minioadmin")
|
||||||
minioSecretKey := getEnv("MINIO_SECRET_KEY", "minioadmin")
|
minioSecretKey := getEnv("MINIO_SECRET_KEY", "minioadmin")
|
||||||
minioUseSSL := getEnv("MINIO_USE_SSL", "false") == "true"
|
minioUseSSL := getEnv("MINIO_USE_SSL", "false") == "true"
|
||||||
minioBucket := getEnv("MINIO_BUCKET", "flatrender-exports")
|
minioBucket := getEnv("MINIO_BUCKET", "flatrender-exports")
|
||||||
|
minioTemplatesBucket := getEnv("MINIO_TEMPLATES_BUCKET", "flatrender-templates")
|
||||||
notificationURL := getEnv("NOTIFICATION_URL", "http://localhost:8080")
|
notificationURL := getEnv("NOTIFICATION_URL", "http://localhost:8080")
|
||||||
serviceToken := getEnv("SERVICE_TOKEN", "internal-service-secret")
|
serviceToken := getEnv("SERVICE_TOKEN", "internal-service-secret")
|
||||||
port := getEnv("PORT", "8080")
|
port := getEnv("PORT", "8080")
|
||||||
@@ -63,7 +64,7 @@ func main() {
|
|||||||
snapH := handlers.NewSnapshotHandler(store)
|
snapH := handlers.NewSnapshotHandler(store)
|
||||||
exportH := handlers.NewExportHandler(store, mc, minioBucket)
|
exportH := handlers.NewExportHandler(store, mc, minioBucket)
|
||||||
nodeH := handlers.NewNodeHandler(store)
|
nodeH := handlers.NewNodeHandler(store)
|
||||||
internalH := handlers.NewInternalHandler(store, notifyClient)
|
internalH := handlers.NewInternalHandler(store, notifyClient, mc, minioTemplatesBucket, minioBucket)
|
||||||
|
|
||||||
// ── Router ────────────────────────────────────────────────────────────────
|
// ── Router ────────────────────────────────────────────────────────────────
|
||||||
r := gin.Default()
|
r := gin.Default()
|
||||||
@@ -138,6 +139,7 @@ func main() {
|
|||||||
internal.POST("/nodes/:node_id/cache-update", internalH.CacheUpdate)
|
internal.POST("/nodes/:node_id/cache-update", internalH.CacheUpdate)
|
||||||
internal.POST("/render/jobs/claim", internalH.Claim)
|
internal.POST("/render/jobs/claim", internalH.Claim)
|
||||||
internal.POST("/render/jobs/:job_id/preview", internalH.Preview)
|
internal.POST("/render/jobs/:job_id/preview", internalH.Preview)
|
||||||
|
internal.POST("/render/jobs/:job_id/output-upload-url", internalH.OutputUploadURL)
|
||||||
internal.POST("/render/jobs/:job_id/frames", internalH.FrameProgress)
|
internal.POST("/render/jobs/:job_id/frames", internalH.FrameProgress)
|
||||||
internal.POST("/render/jobs/:job_id/complete", internalH.Complete)
|
internal.POST("/render/jobs/:job_id/complete", internalH.Complete)
|
||||||
internal.POST("/render/jobs/:job_id/fail", internalH.Fail)
|
internal.POST("/render/jobs/:job_id/fail", internalH.Fail)
|
||||||
|
|||||||
@@ -519,6 +519,57 @@ func (s *Store) ClaimJob(ctx context.Context, nodeID uuid.UUID, region string) (
|
|||||||
return s.getJobByIDInternal(ctx, jobID)
|
return s.getJobByIDInternal(ctx, jobID)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// CreateExportForJob allocates a new Export row for a completed render job.
|
||||||
|
// The export starts with a placeholder path `exports/{export_id}/output.mp4`.
|
||||||
|
// The node agent uploads the MP4 to that MinIO path, then calls CompleteJob
|
||||||
|
// with the returned export_id.
|
||||||
|
func (s *Store) CreateExportForJob(ctx context.Context, jobID uuid.UUID) (*models.Export, error) {
|
||||||
|
// Look up the job to get tenant/user/project context
|
||||||
|
job, err := s.getJobByIDInternal(ctx, jobID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("job not found: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
exportID := uuid.New()
|
||||||
|
path := fmt.Sprintf("exports/%s/output.mp4", exportID)
|
||||||
|
now := time.Now()
|
||||||
|
autoDelete := now.AddDate(0, 0, 30) // 30-day retention
|
||||||
|
|
||||||
|
_, err = s.pool.Exec(ctx, `
|
||||||
|
INSERT INTO render.exports
|
||||||
|
(id, tenant_id, user_id, saved_project_id, original_project_id,
|
||||||
|
render_job_id, path, file_extension, file_type, render_quality,
|
||||||
|
create_type, size_bytes, produce_date, auto_delete_date,
|
||||||
|
delete_notified, created_at)
|
||||||
|
VALUES
|
||||||
|
($1, $2, $3, $4, $5,
|
||||||
|
$6, $7, 'mp4', 'video', $8,
|
||||||
|
'render', 0, $9, $10,
|
||||||
|
false, $9)`,
|
||||||
|
exportID, job.TenantID, job.UserID, job.SavedProjectID, job.OriginalProjectID,
|
||||||
|
job.ID, path, job.Quality,
|
||||||
|
now, autoDelete,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("create export: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &models.Export{
|
||||||
|
ID: exportID,
|
||||||
|
TenantID: job.TenantID,
|
||||||
|
UserID: job.UserID,
|
||||||
|
SavedProjectID: job.SavedProjectID,
|
||||||
|
Path: path,
|
||||||
|
FileExtension: "mp4",
|
||||||
|
FileType: "video",
|
||||||
|
RenderQuality: job.Quality,
|
||||||
|
CreateType: "render",
|
||||||
|
ProduceDate: now,
|
||||||
|
AutoDeleteDate: autoDelete,
|
||||||
|
CreatedAt: now,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
// UpdateJobPreview stores a base64-encoded preview frame for a running job.
|
// UpdateJobPreview stores a base64-encoded preview frame for a running job.
|
||||||
// Called by the node agent every N frames to power the live preview UI.
|
// Called by the node agent every N frames to power the live preview UI.
|
||||||
func (s *Store) UpdateJobPreview(ctx context.Context, jobID uuid.UUID, imageB64 string) error {
|
func (s *Store) UpdateJobPreview(ctx context.Context, jobID uuid.UUID, imageB64 string) error {
|
||||||
|
|||||||
@@ -1,22 +1,35 @@
|
|||||||
package handlers
|
package handlers
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/flatrender/render-svc/internal/db"
|
"github.com/flatrender/render-svc/internal/db"
|
||||||
"github.com/flatrender/render-svc/internal/models"
|
"github.com/flatrender/render-svc/internal/models"
|
||||||
"github.com/flatrender/render-svc/internal/notifier"
|
"github.com/flatrender/render-svc/internal/notifier"
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
|
"github.com/minio/minio-go/v7"
|
||||||
)
|
)
|
||||||
|
|
||||||
type InternalHandler struct {
|
type InternalHandler struct {
|
||||||
store *db.Store
|
store *db.Store
|
||||||
notifier *notifier.Client // may be nil — notifications are best-effort
|
notifier *notifier.Client // may be nil — notifications are best-effort
|
||||||
|
minio *minio.Client
|
||||||
|
templatesBucket string // bucket that holds .aep project files
|
||||||
|
exportsBucket string // bucket that receives rendered MP4 outputs
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewInternalHandler(store *db.Store, n *notifier.Client) *InternalHandler {
|
func NewInternalHandler(store *db.Store, n *notifier.Client, mc *minio.Client, templatesBucket, exportsBucket string) *InternalHandler {
|
||||||
return &InternalHandler{store: store, notifier: n}
|
return &InternalHandler{
|
||||||
|
store: store,
|
||||||
|
notifier: n,
|
||||||
|
minio: mc,
|
||||||
|
templatesBucket: templatesBucket,
|
||||||
|
exportsBucket: exportsBucket,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// completeRequest is the body for POST .../complete
|
// completeRequest is the body for POST .../complete
|
||||||
@@ -241,6 +254,21 @@ func (h *InternalHandler) Claim(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Generate presigned AEP download URL. AEP files are stored at
|
||||||
|
// templates/{original_project_id}/template.aep in the templates bucket.
|
||||||
|
// Errors are non-fatal — node agent falls back to mock render when URL is empty.
|
||||||
|
aepURL := ""
|
||||||
|
if h.minio != nil {
|
||||||
|
objectKey := fmt.Sprintf("templates/%s/template.aep", job.OriginalProjectID)
|
||||||
|
purl, perr := h.minio.PresignedGetObject(
|
||||||
|
context.Background(), h.templatesBucket, objectKey,
|
||||||
|
2*time.Hour, nil,
|
||||||
|
)
|
||||||
|
if perr == nil {
|
||||||
|
aepURL = purl.String()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
c.JSON(http.StatusOK, models.ClaimedJob{
|
c.JSON(http.StatusOK, models.ClaimedJob{
|
||||||
JobID: job.ID,
|
JobID: job.ID,
|
||||||
SavedProjectID: job.SavedProjectID,
|
SavedProjectID: job.SavedProjectID,
|
||||||
@@ -249,6 +277,43 @@ func (h *InternalHandler) Claim(c *gin.Context) {
|
|||||||
FrameRate: job.FrameRate,
|
FrameRate: job.FrameRate,
|
||||||
HasMusic: job.HasMusic,
|
HasMusic: job.HasMusic,
|
||||||
HasVoiceover: job.HasVoiceover,
|
HasVoiceover: job.HasVoiceover,
|
||||||
|
AEPDownloadURL: aepURL,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// POST /v1/internal/render/jobs/:job_id/output-upload-url
|
||||||
|
// Node agent calls this after rendering to get a presigned MinIO PUT URL.
|
||||||
|
// Creates an Export record in the DB and returns the export_id + upload URL.
|
||||||
|
func (h *InternalHandler) OutputUploadURL(c *gin.Context) {
|
||||||
|
jobID, err := uuid.Parse(c.Param("job_id"))
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, models.APIError{Code: "bad_request", Message: "invalid job_id"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
export, err := h.store.CreateExportForJob(c.Request.Context(), jobID)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, models.APIError{Code: "internal_error", Message: err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
expiry := 2 * time.Hour
|
||||||
|
purl, err := h.minio.PresignedPutObject(
|
||||||
|
context.Background(), h.exportsBucket, export.Path, expiry,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, models.APIError{
|
||||||
|
Code: "presign_error",
|
||||||
|
Message: "could not generate upload URL",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, models.OutputUploadURLResponse{
|
||||||
|
ExportID: export.ID,
|
||||||
|
UploadURL: purl.String(),
|
||||||
|
ObjectKey: export.Path,
|
||||||
|
ExpiresAt: time.Now().Add(expiry),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -415,6 +415,17 @@ type ClaimedJob struct {
|
|||||||
FrameRate int `json:"frame_rate"`
|
FrameRate int `json:"frame_rate"`
|
||||||
HasMusic bool `json:"has_music"`
|
HasMusic bool `json:"has_music"`
|
||||||
HasVoiceover bool `json:"has_voiceover"`
|
HasVoiceover bool `json:"has_voiceover"`
|
||||||
|
// AEPDownloadURL is a presigned MinIO GET URL for the .aep project file.
|
||||||
|
// Valid for 2 hours. Empty when the template is not yet uploaded.
|
||||||
|
AEPDownloadURL string `json:"aep_download_url,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// OutputUploadURLResponse is returned by POST .../output-upload-url.
|
||||||
|
type OutputUploadURLResponse struct {
|
||||||
|
ExportID uuid.UUID `json:"export_id"`
|
||||||
|
UploadURL string `json:"upload_url"`
|
||||||
|
ObjectKey string `json:"object_key"`
|
||||||
|
ExpiresAt time.Time `json:"expires_at"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type CacheUpdateRequest struct {
|
type CacheUpdateRequest struct {
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { gatewayFetch } from "@/lib/api/gateway";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
/** POST /api/auth/password-reset-confirm — confirm reset with OTP + new password */
|
||||||
|
export async function POST(request: Request) {
|
||||||
|
let body: unknown;
|
||||||
|
try { body = await request.json(); } catch {
|
||||||
|
return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
|
||||||
|
}
|
||||||
|
const { email, otp, new_password } = body as { email?: string; otp?: string; new_password?: string };
|
||||||
|
if (!email || !otp || !new_password) {
|
||||||
|
return NextResponse.json({ error: "email, otp, and new_password are required" }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const res = await gatewayFetch("/v1/auth/password/reset/confirm", {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify({ email, otp, new_password }),
|
||||||
|
});
|
||||||
|
const data = await res.json().catch(() => null) as { message?: string } | null;
|
||||||
|
if (!res.ok) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: data?.message ?? "Invalid or expired code" },
|
||||||
|
{ status: res.status }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return NextResponse.json({ ok: true });
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { gatewayFetch } from "@/lib/api/gateway";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
/** POST /api/auth/password-reset — request a password reset OTP email */
|
||||||
|
export async function POST(request: Request) {
|
||||||
|
let body: unknown;
|
||||||
|
try { body = await request.json(); } catch {
|
||||||
|
return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
|
||||||
|
}
|
||||||
|
const { email } = body as { email?: string };
|
||||||
|
if (!email) return NextResponse.json({ error: "email required" }, { status: 400 });
|
||||||
|
|
||||||
|
const res = await gatewayFetch("/v1/auth/password/reset/request", {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify({ email }),
|
||||||
|
});
|
||||||
|
// Always return 200 to avoid user enumeration
|
||||||
|
if (!res.ok && res.status !== 404) {
|
||||||
|
return NextResponse.json({ error: "Request failed" }, { status: 500 });
|
||||||
|
}
|
||||||
|
return NextResponse.json({ ok: true });
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { gatewayUrl } from "@/lib/api/gateway";
|
||||||
|
import { getAccessToken } from "@/lib/auth/session";
|
||||||
|
|
||||||
|
export const runtime = "nodejs";
|
||||||
|
|
||||||
|
/** POST /api/billing/cancel — cancel the current active plan. */
|
||||||
|
export async function POST() {
|
||||||
|
const token = await getAccessToken();
|
||||||
|
if (!token) {
|
||||||
|
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const res = await fetch(gatewayUrl("/v1/users/me/plan/cancel"), {
|
||||||
|
method: "POST",
|
||||||
|
cache: "no-store",
|
||||||
|
headers: {
|
||||||
|
Accept: "application/json",
|
||||||
|
Authorization: `Bearer ${token}`,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
const err = (await res.json().catch(() => null)) as { error?: string } | null;
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: err?.error ?? "Failed to cancel plan" },
|
||||||
|
{ status: res.status }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.json({ ok: true });
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import { redirect } from "next/navigation";
|
||||||
|
|
||||||
|
export const runtime = "nodejs";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GET /api/billing/portal
|
||||||
|
*
|
||||||
|
* In the Stripe era this redirected to a Stripe-hosted portal.
|
||||||
|
* With V2 (ZarinPal / SnapPay) the portal is in-app — redirect to the
|
||||||
|
* billing tab in settings.
|
||||||
|
*/
|
||||||
|
export async function GET() {
|
||||||
|
redirect("/dashboard/settings?tab=billing");
|
||||||
|
}
|
||||||
@@ -13,6 +13,7 @@ import { Button } from "@/components/ui/button";
|
|||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
type AuthTab = "sign-in" | "sign-up";
|
type AuthTab = "sign-in" | "sign-up";
|
||||||
|
type AuthView = "main" | "forgot-password" | "reset-confirm";
|
||||||
|
|
||||||
/** Only allow same-origin relative redirects to avoid open-redirect issues. */
|
/** Only allow same-origin relative redirects to avoid open-redirect issues. */
|
||||||
function safeNext(next: string | null): string {
|
function safeNext(next: string | null): string {
|
||||||
@@ -29,11 +30,17 @@ export function AuthPageContent() {
|
|||||||
searchParams.get("tab") === "sign-up" ? "sign-up" : "sign-in";
|
searchParams.get("tab") === "sign-up" ? "sign-up" : "sign-in";
|
||||||
|
|
||||||
const [activeTab, setActiveTab] = useState<AuthTab>(initialTab);
|
const [activeTab, setActiveTab] = useState<AuthTab>(initialTab);
|
||||||
|
const [view, setView] = useState<AuthView>("main");
|
||||||
const [authLoading, setAuthLoading] = useState(true);
|
const [authLoading, setAuthLoading] = useState(true);
|
||||||
const [submitting, setSubmitting] = useState(false);
|
const [submitting, setSubmitting] = useState(false);
|
||||||
const [formError, setFormError] = useState<string | null>(null);
|
const [formError, setFormError] = useState<string | null>(null);
|
||||||
const [formMessage, setFormMessage] = useState<string | null>(null);
|
const [formMessage, setFormMessage] = useState<string | null>(null);
|
||||||
|
|
||||||
|
// Forgot-password state
|
||||||
|
const [resetEmail, setResetEmail] = useState("");
|
||||||
|
const [resetOtp, setResetOtp] = useState("");
|
||||||
|
const [resetNewPassword, setResetNewPassword] = useState("");
|
||||||
|
|
||||||
const {
|
const {
|
||||||
register,
|
register,
|
||||||
handleSubmit,
|
handleSubmit,
|
||||||
@@ -64,9 +71,7 @@ export function AuthPageContent() {
|
|||||||
checkSession().then((redirected) => {
|
checkSession().then((redirected) => {
|
||||||
if (mounted && !redirected) setAuthLoading(false);
|
if (mounted && !redirected) setAuthLoading(false);
|
||||||
});
|
});
|
||||||
return () => {
|
return () => { mounted = false; };
|
||||||
mounted = false;
|
|
||||||
};
|
|
||||||
}, [checkSession]);
|
}, [checkSession]);
|
||||||
|
|
||||||
const handleTabChange = (tab: AuthTab) => {
|
const handleTabChange = (tab: AuthTab) => {
|
||||||
@@ -76,13 +81,22 @@ export function AuthPageContent() {
|
|||||||
reset();
|
reset();
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const goBack = () => {
|
||||||
|
setView("main");
|
||||||
|
setFormError(null);
|
||||||
|
setFormMessage(null);
|
||||||
|
setResetEmail("");
|
||||||
|
setResetOtp("");
|
||||||
|
setResetNewPassword("");
|
||||||
|
};
|
||||||
|
|
||||||
|
// ── Main sign-in / sign-up submit ──────────────────────────────────────────
|
||||||
const onSubmit = async (values: AuthFormValues) => {
|
const onSubmit = async (values: AuthFormValues) => {
|
||||||
setSubmitting(true);
|
setSubmitting(true);
|
||||||
setFormError(null);
|
setFormError(null);
|
||||||
setFormMessage(null);
|
setFormMessage(null);
|
||||||
|
|
||||||
const endpoint =
|
const endpoint = activeTab === "sign-in" ? "/api/auth/login" : "/api/auth/register";
|
||||||
activeTab === "sign-in" ? "/api/auth/login" : "/api/auth/register";
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const res = await fetch(endpoint, {
|
const res = await fetch(endpoint, {
|
||||||
@@ -98,7 +112,6 @@ export function AuthPageContent() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Registered but not auto-logged-in (verification gate) — prompt sign-in.
|
|
||||||
if (data?.registered && !data?.user) {
|
if (data?.registered && !data?.user) {
|
||||||
setFormMessage(
|
setFormMessage(
|
||||||
data.verificationRequired
|
data.verificationRequired
|
||||||
@@ -111,7 +124,6 @@ export function AuthPageContent() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Logged in — cookies are set; refresh server components and go.
|
|
||||||
router.replace(nextPath);
|
router.replace(nextPath);
|
||||||
router.refresh();
|
router.refresh();
|
||||||
} catch {
|
} catch {
|
||||||
@@ -120,6 +132,54 @@ export function AuthPageContent() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// ── Forgot password — step 1: request OTP ─────────────────────────────────
|
||||||
|
const handleForgotRequest = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!resetEmail) return;
|
||||||
|
setSubmitting(true);
|
||||||
|
setFormError(null);
|
||||||
|
try {
|
||||||
|
await fetch("/api/auth/password-reset", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ email: resetEmail }),
|
||||||
|
});
|
||||||
|
// Always succeed (anti-enumeration)
|
||||||
|
setView("reset-confirm");
|
||||||
|
setFormMessage("If that email is registered, we sent a reset code.");
|
||||||
|
} catch {
|
||||||
|
setFormError("Network error. Please try again.");
|
||||||
|
} finally {
|
||||||
|
setSubmitting(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// ── Forgot password — step 2: confirm OTP + new password ──────────────────
|
||||||
|
const handleResetConfirm = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!resetOtp || !resetNewPassword) return;
|
||||||
|
setSubmitting(true);
|
||||||
|
setFormError(null);
|
||||||
|
try {
|
||||||
|
const res = await fetch("/api/auth/password-reset-confirm", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ email: resetEmail, otp: resetOtp, new_password: resetNewPassword }),
|
||||||
|
});
|
||||||
|
const data = await res.json().catch(() => null) as { error?: string } | null;
|
||||||
|
if (!res.ok) {
|
||||||
|
setFormError(data?.error ?? "Invalid or expired code.");
|
||||||
|
} else {
|
||||||
|
setFormMessage("Password updated. You can now sign in.");
|
||||||
|
goBack();
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
setFormError("Network error. Please try again.");
|
||||||
|
} finally {
|
||||||
|
setSubmitting(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
if (authLoading) {
|
if (authLoading) {
|
||||||
return (
|
return (
|
||||||
<div className="flex min-h-[calc(100vh-4rem)] items-center justify-center py-20">
|
<div className="flex min-h-[calc(100vh-4rem)] items-center justify-center py-20">
|
||||||
@@ -128,6 +188,96 @@ export function AuthPageContent() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Forgot password views ──────────────────────────────────────────────────
|
||||||
|
if (view === "forgot-password" || view === "reset-confirm") {
|
||||||
|
return (
|
||||||
|
<div className="mx-auto w-full max-w-md px-4 py-12 sm:py-16">
|
||||||
|
<div className="text-center">
|
||||||
|
<h1 className="font-heading text-2xl font-bold text-neutral-900">
|
||||||
|
{view === "forgot-password" ? "Reset your password" : "Enter reset code"}
|
||||||
|
</h1>
|
||||||
|
<p className="mt-2 text-sm text-neutral-600">
|
||||||
|
{view === "forgot-password"
|
||||||
|
? "We'll send a one-time code to your email."
|
||||||
|
: `Check your email for the code sent to ${resetEmail}`}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-8 rounded-xl border border-gray-100 bg-white p-6 shadow-sm">
|
||||||
|
{view === "forgot-password" ? (
|
||||||
|
<form onSubmit={handleForgotRequest} className="space-y-4" noValidate>
|
||||||
|
<div>
|
||||||
|
<label htmlFor="reset-email" className="block text-sm font-medium text-neutral-700">
|
||||||
|
Email address
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
id="reset-email"
|
||||||
|
type="email"
|
||||||
|
value={resetEmail}
|
||||||
|
onChange={(e) => setResetEmail(e.target.value)}
|
||||||
|
disabled={submitting}
|
||||||
|
required
|
||||||
|
className="mt-1.5 w-full rounded-lg border border-gray-100 bg-white px-3 py-2.5 text-sm text-neutral-900 shadow-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-600 disabled:opacity-50"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{formError && <p className="rounded-lg bg-red-50 px-3 py-2 text-sm text-red-700">{formError}</p>}
|
||||||
|
<Button type="submit" className="w-full" disabled={submitting || !resetEmail}>
|
||||||
|
{submitting && <Loader2 className="h-4 w-4 animate-spin" />}
|
||||||
|
Send reset code
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
) : (
|
||||||
|
<form onSubmit={handleResetConfirm} className="space-y-4" noValidate>
|
||||||
|
<div>
|
||||||
|
<label htmlFor="reset-otp" className="block text-sm font-medium text-neutral-700">
|
||||||
|
Reset code
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
id="reset-otp"
|
||||||
|
type="text"
|
||||||
|
inputMode="numeric"
|
||||||
|
value={resetOtp}
|
||||||
|
onChange={(e) => setResetOtp(e.target.value)}
|
||||||
|
disabled={submitting}
|
||||||
|
required
|
||||||
|
placeholder="6-digit code"
|
||||||
|
className="mt-1.5 w-full rounded-lg border border-gray-100 bg-white px-3 py-2.5 text-sm text-neutral-900 shadow-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-600 disabled:opacity-50"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label htmlFor="new-password" className="block text-sm font-medium text-neutral-700">
|
||||||
|
New password
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
id="new-password"
|
||||||
|
type="password"
|
||||||
|
autoComplete="new-password"
|
||||||
|
value={resetNewPassword}
|
||||||
|
onChange={(e) => setResetNewPassword(e.target.value)}
|
||||||
|
disabled={submitting}
|
||||||
|
required
|
||||||
|
minLength={8}
|
||||||
|
className="mt-1.5 w-full rounded-lg border border-gray-100 bg-white px-3 py-2.5 text-sm text-neutral-900 shadow-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-600 disabled:opacity-50"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{formError && <p className="rounded-lg bg-red-50 px-3 py-2 text-sm text-red-700">{formError}</p>}
|
||||||
|
{formMessage && <p className="rounded-lg bg-primary-50 px-3 py-2 text-sm text-primary-700">{formMessage}</p>}
|
||||||
|
<Button type="submit" className="w-full" disabled={submitting || !resetOtp || !resetNewPassword}>
|
||||||
|
{submitting && <Loader2 className="h-4 w-4 animate-spin" />}
|
||||||
|
Set new password
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button type="button" onClick={goBack} className="mt-4 block w-full text-center text-sm text-neutral-500 hover:text-neutral-700 transition-colors">
|
||||||
|
← Back to sign in
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Main sign-in / sign-up view ────────────────────────────────────────────
|
||||||
return (
|
return (
|
||||||
<div className="mx-auto w-full max-w-md px-4 py-12 sm:py-16">
|
<div className="mx-auto w-full max-w-md px-4 py-12 sm:py-16">
|
||||||
<div className="text-center">
|
<div className="text-center">
|
||||||
@@ -162,10 +312,7 @@ export function AuthPageContent() {
|
|||||||
<div className="mt-6 rounded-xl border border-gray-100 bg-white p-6 shadow-sm">
|
<div className="mt-6 rounded-xl border border-gray-100 bg-white p-6 shadow-sm">
|
||||||
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4" noValidate>
|
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4" noValidate>
|
||||||
<div>
|
<div>
|
||||||
<label
|
<label htmlFor="email" className="block text-sm font-medium text-neutral-700">
|
||||||
htmlFor="email"
|
|
||||||
className="block text-sm font-medium text-neutral-700"
|
|
||||||
>
|
|
||||||
Email
|
Email
|
||||||
</label>
|
</label>
|
||||||
<input
|
<input
|
||||||
@@ -185,18 +332,24 @@ export function AuthPageContent() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<label
|
<div className="flex items-center justify-between">
|
||||||
htmlFor="password"
|
<label htmlFor="password" className="block text-sm font-medium text-neutral-700">
|
||||||
className="block text-sm font-medium text-neutral-700"
|
Password
|
||||||
>
|
</label>
|
||||||
Password
|
{activeTab === "sign-in" && (
|
||||||
</label>
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => { setView("forgot-password"); setFormError(null); setFormMessage(null); }}
|
||||||
|
className="text-xs text-primary-600 hover:underline focus-visible:outline-none"
|
||||||
|
>
|
||||||
|
Forgot password?
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
<input
|
<input
|
||||||
id="password"
|
id="password"
|
||||||
type="password"
|
type="password"
|
||||||
autoComplete={
|
autoComplete={activeTab === "sign-in" ? "current-password" : "new-password"}
|
||||||
activeTab === "sign-in" ? "current-password" : "new-password"
|
|
||||||
}
|
|
||||||
disabled={submitting}
|
disabled={submitting}
|
||||||
className={cn(
|
className={cn(
|
||||||
"mt-1.5 w-full rounded-lg border bg-white px-3 py-2.5 text-sm text-neutral-900 shadow-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-600 focus-visible:ring-offset-2 disabled:opacity-50",
|
"mt-1.5 w-full rounded-lg border bg-white px-3 py-2.5 text-sm text-neutral-900 shadow-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-600 focus-visible:ring-offset-2 disabled:opacity-50",
|
||||||
@@ -205,28 +358,19 @@ export function AuthPageContent() {
|
|||||||
{...register("password")}
|
{...register("password")}
|
||||||
/>
|
/>
|
||||||
{errors.password && (
|
{errors.password && (
|
||||||
<p className="mt-1.5 text-xs text-red-600">
|
<p className="mt-1.5 text-xs text-red-600">{errors.password.message}</p>
|
||||||
{errors.password.message}
|
|
||||||
</p>
|
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{formError && (
|
{formError && (
|
||||||
<p className="rounded-lg bg-red-50 px-3 py-2 text-sm text-red-700">
|
<p className="rounded-lg bg-red-50 px-3 py-2 text-sm text-red-700">{formError}</p>
|
||||||
{formError}
|
|
||||||
</p>
|
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{formMessage && (
|
{formMessage && (
|
||||||
<p className="rounded-lg bg-primary-50 px-3 py-2 text-sm text-primary-700">
|
<p className="rounded-lg bg-primary-50 px-3 py-2 text-sm text-primary-700">{formMessage}</p>
|
||||||
{formMessage}
|
|
||||||
</p>
|
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<Button type="submit" className="w-full" disabled={submitting}>
|
<Button type="submit" className="w-full" disabled={submitting}>
|
||||||
{submitting ? (
|
{submitting ? <Loader2 className="h-4 w-4 animate-spin" aria-hidden /> : null}
|
||||||
<Loader2 className="h-4 w-4 animate-spin" aria-hidden />
|
|
||||||
) : null}
|
|
||||||
{activeTab === "sign-in" ? "Sign In" : "Create Account"}
|
{activeTab === "sign-in" ? "Sign In" : "Create Account"}
|
||||||
</Button>
|
</Button>
|
||||||
</form>
|
</form>
|
||||||
@@ -234,14 +378,9 @@ export function AuthPageContent() {
|
|||||||
|
|
||||||
<p className="mt-6 text-center text-xs text-neutral-500">
|
<p className="mt-6 text-center text-xs text-neutral-500">
|
||||||
By continuing, you agree to our{" "}
|
By continuing, you agree to our{" "}
|
||||||
<Link href="/terms" className="text-primary-600 hover:underline">
|
<Link href="/terms" className="text-primary-600 hover:underline">Terms</Link>{" "}
|
||||||
Terms
|
|
||||||
</Link>{" "}
|
|
||||||
and{" "}
|
and{" "}
|
||||||
<Link href="/privacy" className="text-primary-600 hover:underline">
|
<Link href="/privacy" className="text-primary-600 hover:underline">Privacy Policy</Link>.
|
||||||
Privacy Policy
|
|
||||||
</Link>
|
|
||||||
.
|
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,5 +1,9 @@
|
|||||||
import { CreditCard, ExternalLink, Zap } from "lucide-react";
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import { CreditCard, Loader2, Zap } from "lucide-react";
|
||||||
|
|
||||||
|
import { apiFetch } from "@/lib/api/fetch";
|
||||||
import type { PlanId } from "@/lib/plans";
|
import type { PlanId } from "@/lib/plans";
|
||||||
|
|
||||||
interface SettingsBillingProps {
|
interface SettingsBillingProps {
|
||||||
@@ -26,6 +30,28 @@ const PLAN_FEATURES: Record<PlanId, string[]> = {
|
|||||||
|
|
||||||
export function SettingsBilling({ plan }: SettingsBillingProps) {
|
export function SettingsBilling({ plan }: SettingsBillingProps) {
|
||||||
const isPaid = plan !== "free";
|
const isPaid = plan !== "free";
|
||||||
|
const [cancelling, setCancelling] = useState(false);
|
||||||
|
const [cancelled, setCancelled] = useState(false);
|
||||||
|
const [cancelError, setCancelError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const handleCancel = async () => {
|
||||||
|
if (!confirm("Cancel your plan? You'll keep access until the current period ends.")) return;
|
||||||
|
setCancelling(true);
|
||||||
|
setCancelError(null);
|
||||||
|
try {
|
||||||
|
const res = await apiFetch("/api/billing/cancel", { method: "POST" });
|
||||||
|
if (!res.ok) {
|
||||||
|
const data = (await res.json().catch(() => null)) as { error?: string } | null;
|
||||||
|
setCancelError(data?.error ?? "Failed to cancel plan. Please try again.");
|
||||||
|
} else {
|
||||||
|
setCancelled(true);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
setCancelError("Network error. Please try again.");
|
||||||
|
} finally {
|
||||||
|
setCancelling(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="rounded-xl border border-gray-100 bg-white p-6">
|
<div className="rounded-xl border border-gray-100 bg-white p-6">
|
||||||
@@ -44,21 +70,12 @@ export function SettingsBilling({ plan }: SettingsBillingProps) {
|
|||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<p className="font-heading text-lg font-bold text-neutral-900">{PLAN_LABELS[plan]}</p>
|
<p className="font-heading text-lg font-bold text-neutral-900">{PLAN_LABELS[plan]}</p>
|
||||||
<span className={`rounded-full px-2 py-0.5 text-xs font-semibold ${PLAN_COLORS[plan]}`}>
|
<span className={`rounded-full px-2 py-0.5 text-xs font-semibold ${PLAN_COLORS[plan]}`}>
|
||||||
{isPaid ? "Active" : "Free tier"}
|
{cancelled ? "Cancels at period end" : isPaid ? "Active" : "Free tier"}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{isPaid ? (
|
{!isPaid && (
|
||||||
<a
|
|
||||||
href="/api/billing/portal"
|
|
||||||
className="inline-flex items-center gap-1.5 rounded-lg border border-gray-200 bg-white px-3 py-1.5 text-sm font-medium text-neutral-700 transition-colors hover:bg-neutral-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500"
|
|
||||||
>
|
|
||||||
<CreditCard className="h-4 w-4" aria-hidden />
|
|
||||||
Manage billing
|
|
||||||
<ExternalLink className="h-3 w-3" aria-hidden />
|
|
||||||
</a>
|
|
||||||
) : (
|
|
||||||
<a
|
<a
|
||||||
href="/#pricing"
|
href="/#pricing"
|
||||||
className="inline-flex items-center gap-1.5 rounded-lg bg-primary-600 px-3 py-1.5 text-sm font-semibold text-white transition-colors hover:bg-primary-700 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500"
|
className="inline-flex items-center gap-1.5 rounded-lg bg-primary-600 px-3 py-1.5 text-sm font-semibold text-white transition-colors hover:bg-primary-700 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500"
|
||||||
@@ -80,6 +97,40 @@ export function SettingsBilling({ plan }: SettingsBillingProps) {
|
|||||||
</ul>
|
</ul>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Paid plan actions */}
|
||||||
|
{isPaid && !cancelled && (
|
||||||
|
<div className="mt-4 flex items-center gap-3">
|
||||||
|
<a
|
||||||
|
href="/#pricing"
|
||||||
|
className="inline-flex items-center gap-1.5 rounded-lg border border-gray-200 bg-white px-3 py-1.5 text-sm font-medium text-neutral-700 transition-colors hover:bg-neutral-50"
|
||||||
|
>
|
||||||
|
<CreditCard className="h-4 w-4" aria-hidden />
|
||||||
|
Change plan
|
||||||
|
</a>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={handleCancel}
|
||||||
|
disabled={cancelling}
|
||||||
|
className="inline-flex items-center gap-1.5 rounded-lg border border-red-200 px-3 py-1.5 text-sm font-medium text-red-600 transition-colors hover:bg-red-50 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||||
|
>
|
||||||
|
{cancelling ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
|
||||||
|
{cancelling ? "Cancelling…" : "Cancel plan"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{cancelError && (
|
||||||
|
<p className="mt-3 rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-600">
|
||||||
|
{cancelError}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{cancelled && (
|
||||||
|
<p className="mt-3 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-700">
|
||||||
|
Your plan has been cancelled. You'll keep access until the end of your billing period.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
{!isPaid && (
|
{!isPaid && (
|
||||||
<p className="mt-4 text-xs text-neutral-400">
|
<p className="mt-4 text-xs text-neutral-400">
|
||||||
Upgrade to unlock unlimited projects, 4K export, and premium templates.
|
Upgrade to unlock unlimited projects, 4K export, and premium templates.
|
||||||
|
|||||||
Reference in New Issue
Block a user