feat: V2 microservices stack — backend services, gateway, JWT auth

Add full V2 architecture: identity, content, studio (.NET 10) and file,
render, notification, gateway (Go) services with vendored deps, plus DB
migrations, event/API contracts, and an init-db script.

Wire the Next.js frontend to the gateway: server-side JWT auth routes
(login/register/refresh/logout/me), gateway fetch helper, and session/
cookie/jwt helpers under src/lib.

Containerize the stack via docker-compose.v2.yml and per-service
Dockerfiles. Base images resolve through a Nexus mirror (Docker Hub) and
MCR directly; npm/NuGet pull from Nexus groups. Self-host fonts via
next/font/local to avoid Google Fonts (geo-blocked).

Add CI workflow and ignore .env.v2, *.stackdump, and .NET bin/obj.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
soroush.asadi
2026-05-29 23:29:31 +03:30
parent 53ea78a00d
commit 90ac0b81d1
7636 changed files with 3707504 additions and 240 deletions
+3 -11
View File
@@ -1,7 +1,7 @@
import { redirect } from "next/navigation";
import { DashboardShell } from "@/components/dashboard/DashboardShell";
import { createClient } from "@/lib/supabase/server";
import { getCurrentUser } from "@/lib/auth/session";
export const dynamic = "force-dynamic";
@@ -10,24 +10,16 @@ export default async function DashboardLayout({
}: Readonly<{
children: React.ReactNode;
}>) {
const supabase = await createClient();
const {
data: { user },
} = await supabase.auth.getUser();
const user = await getCurrentUser();
if (!user) {
redirect("/auth");
}
const userName =
typeof user.user_metadata?.full_name === "string"
? user.user_metadata.full_name
: null;
return (
<DashboardShell
userEmail={user.email ?? ""}
userName={userName}
userName={user.full_name ?? null}
userId={user.id}
>
{children}
+14 -15
View File
@@ -1,5 +1,5 @@
import type { Metadata } from "next";
import { Inter, Plus_Jakarta_Sans, Vazirmatn } from "next/font/google";
import localFont from "next/font/local";
import { notFound } from "next/navigation";
import { getMessages, getTranslations } from "next-intl/server";
import { NextIntlClientProvider } from "next-intl";
@@ -10,23 +10,28 @@ import type { Locale } from "@/i18n/routing";
import "../globals.css";
/* ── Fonts ─────────────────────────────────────────────────────── */
/* ── Fonts (self-hosted via @fontsource — no Google CDN required) ── */
const vazirmatn = Vazirmatn({
subsets: ["arabic"],
const vazirmatn = localFont({
src: [
{ path: "../../../node_modules/@fontsource/vazirmatn/files/vazirmatn-arabic-400-normal.woff2", weight: "400" },
{ path: "../../../node_modules/@fontsource/vazirmatn/files/vazirmatn-arabic-500-normal.woff2", weight: "500" },
{ path: "../../../node_modules/@fontsource/vazirmatn/files/vazirmatn-arabic-600-normal.woff2", weight: "600" },
{ path: "../../../node_modules/@fontsource/vazirmatn/files/vazirmatn-arabic-700-normal.woff2", weight: "700" },
{ path: "../../../node_modules/@fontsource/vazirmatn/files/vazirmatn-arabic-800-normal.woff2", weight: "800" },
],
variable: "--font-vazirmatn",
display: "swap",
weight: ["400", "500", "600", "700", "800"],
});
const plusJakartaSans = Plus_Jakarta_Sans({
subsets: ["latin"],
const plusJakartaSans = localFont({
src: "../../../node_modules/@fontsource-variable/plus-jakarta-sans/files/plus-jakarta-sans-latin-wght-normal.woff2",
variable: "--font-heading",
display: "swap",
});
const inter = Inter({
subsets: ["latin"],
const inter = localFont({
src: "../../../node_modules/@fontsource-variable/inter/files/inter-latin-wght-normal.woff2",
variable: "--font-body",
display: "swap",
});
@@ -97,12 +102,6 @@ export default async function LocaleLayout({
>
<head>
<link rel="icon" href="/favicon.svg" type="image/svg+xml" />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link
rel="preconnect"
href="https://fonts.gstatic.com"
crossOrigin="anonymous"
/>
<link rel="preconnect" href="https://picsum.photos" />
</head>
<body
+3 -6
View File
@@ -1,6 +1,6 @@
import { redirect } from "next/navigation";
import { createClient } from "@/lib/supabase/server";
import { getSession } from "@/lib/auth/session";
export const dynamic = "force-dynamic";
@@ -9,12 +9,9 @@ export default async function VideoProjectNewLayout({
}: Readonly<{
children: React.ReactNode;
}>) {
const supabase = await createClient();
const {
data: { user },
} = await supabase.auth.getUser();
const session = await getSession();
if (!user) {
if (!session) {
redirect("/auth");
}
+51
View File
@@ -0,0 +1,51 @@
import { NextResponse } from "next/server";
import { gatewayFetch } from "@/lib/api/gateway";
import { DEFAULT_TENANT_SLUG } from "@/lib/auth/constants";
import { setAuthCookies } from "@/lib/auth/cookies";
export const dynamic = "force-dynamic";
export async function POST(req: Request) {
const body = await req.json().catch(() => null);
const email = body?.email?.trim();
const password = body?.password;
if (!email || !password) {
return NextResponse.json(
{ error: "Email and password are required." },
{ status: 400 }
);
}
const res = await gatewayFetch("/v1/auth/login", {
method: "POST",
body: JSON.stringify({
tenant_slug: DEFAULT_TENANT_SLUG,
email,
password,
}),
});
const data = await res.json().catch(() => null);
if (!res.ok) {
// 403 from Identity means MFA is required.
if (res.status === 403 && data?.mfa_required) {
return NextResponse.json(
{ error: "MFA is required for this account.", mfaRequired: true },
{ status: 403 }
);
}
return NextResponse.json(
{ error: data?.message ?? "Invalid email or password." },
{ status: res.status === 401 ? 401 : res.status }
);
}
const out = NextResponse.json({ user: data.user, tenant: data.tenant });
return setAuthCookies(
out,
data.access_token,
data.refresh_token,
data.expires_in ?? 900
);
}
+24
View File
@@ -0,0 +1,24 @@
import { cookies } from "next/headers";
import { NextResponse } from "next/server";
import { gatewayFetch } from "@/lib/api/gateway";
import { ACCESS_TOKEN_COOKIE } from "@/lib/auth/constants";
import { clearAuthCookies } from "@/lib/auth/cookies";
export const dynamic = "force-dynamic";
export async function POST() {
const token = (await cookies()).get(ACCESS_TOKEN_COOKIE)?.value;
if (token) {
// Best-effort server-side session revoke; ignore failures.
try {
await gatewayFetch("/v1/auth/logout", {
method: "POST",
headers: { Authorization: `Bearer ${token}` },
});
} catch {
/* noop */
}
}
return clearAuthCookies(NextResponse.json({ ok: true }));
}
+25
View File
@@ -0,0 +1,25 @@
import { cookies } from "next/headers";
import { NextResponse } from "next/server";
import { gatewayFetch } from "@/lib/api/gateway";
import { ACCESS_TOKEN_COOKIE } from "@/lib/auth/constants";
export const dynamic = "force-dynamic";
/** Returns the current user profile from Identity, or { user: null } if signed out. */
export async function GET() {
const token = (await cookies()).get(ACCESS_TOKEN_COOKIE)?.value;
if (!token) {
return NextResponse.json({ user: null });
}
const res = await gatewayFetch("/v1/users/me", {
headers: { Authorization: `Bearer ${token}` },
});
if (!res.ok) {
return NextResponse.json({ user: null });
}
const user = await res.json().catch(() => null);
return NextResponse.json({ user });
}
+36
View File
@@ -0,0 +1,36 @@
import { cookies } from "next/headers";
import { NextResponse } from "next/server";
import { gatewayFetch } from "@/lib/api/gateway";
import { REFRESH_TOKEN_COOKIE } from "@/lib/auth/constants";
import { clearAuthCookies, setAuthCookies } from "@/lib/auth/cookies";
export const dynamic = "force-dynamic";
export async function POST() {
const refreshToken = (await cookies()).get(REFRESH_TOKEN_COOKIE)?.value;
if (!refreshToken) {
return NextResponse.json({ error: "Not authenticated." }, { status: 401 });
}
const res = await gatewayFetch("/v1/auth/refresh", {
method: "POST",
body: JSON.stringify({ refresh_token: refreshToken }),
});
const data = await res.json().catch(() => null);
if (!res.ok || !data?.access_token) {
// Refresh token invalid/expired/rotated — force re-login.
return clearAuthCookies(
NextResponse.json({ error: "Session expired." }, { status: 401 })
);
}
const out = NextResponse.json({ ok: true, user: data.user });
return setAuthCookies(
out,
data.access_token,
data.refresh_token,
data.expires_in ?? 900
);
}
+66
View File
@@ -0,0 +1,66 @@
import { NextResponse } from "next/server";
import { gatewayFetch } from "@/lib/api/gateway";
import { DEFAULT_TENANT_SLUG } from "@/lib/auth/constants";
import { setAuthCookies } from "@/lib/auth/cookies";
export const dynamic = "force-dynamic";
export async function POST(req: Request) {
const body = await req.json().catch(() => null);
const email = body?.email?.trim();
const password = body?.password;
const fullName = body?.full_name ?? body?.fullName ?? null;
if (!email || !password) {
return NextResponse.json(
{ error: "Email and password are required." },
{ status: 400 }
);
}
const reg = await gatewayFetch("/v1/auth/register", {
method: "POST",
body: JSON.stringify({
tenant_slug: DEFAULT_TENANT_SLUG,
email,
password,
full_name: fullName,
}),
});
const regData = await reg.json().catch(() => null);
if (!reg.ok) {
// Surface the first ASP.NET validation error if present.
const firstError =
regData?.errors && typeof regData.errors === "object"
? (Object.values(regData.errors)[0] as string[])?.[0]
: undefined;
return NextResponse.json(
{ error: regData?.message ?? firstError ?? "Registration failed." },
{ status: reg.status }
);
}
// Registration succeeded — log in immediately for a seamless flow.
const login = await gatewayFetch("/v1/auth/login", {
method: "POST",
body: JSON.stringify({ tenant_slug: DEFAULT_TENANT_SLUG, email, password }),
});
const loginData = await login.json().catch(() => null);
if (!login.ok) {
// Account created but auto-login failed (e.g. verification gate) — let them sign in.
return NextResponse.json({
registered: true,
verificationRequired: regData?.verification_required ?? false,
});
}
const out = NextResponse.json({ user: loginData.user, tenant: loginData.tenant });
return setAuthCookies(
out,
loginData.access_token,
loginData.refresh_token,
loginData.expires_in ?? 900
);
}
+17 -4
View File
@@ -1,11 +1,24 @@
import { cookies } from "next/headers";
import { NextResponse } from "next/server";
import { createClient } from "@/lib/supabase/server";
import { gatewayFetch } from "@/lib/api/gateway";
import { ACCESS_TOKEN_COOKIE } from "@/lib/auth/constants";
import { clearAuthCookies } from "@/lib/auth/cookies";
export async function POST(request: Request) {
const supabase = await createClient();
await supabase.auth.signOut();
const token = (await cookies()).get(ACCESS_TOKEN_COOKIE)?.value;
if (token) {
try {
await gatewayFetch("/v1/auth/logout", {
method: "POST",
headers: { Authorization: `Bearer ${token}` },
});
} catch {
/* best-effort revoke */
}
}
const { origin } = new URL(request.url);
return NextResponse.redirect(`${origin}/auth`, { status: 303 });
const res = NextResponse.redirect(`${origin}/auth`, { status: 303 });
return clearAuthCookies(res);
}
+53 -128
View File
@@ -1,6 +1,6 @@
"use client";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { zodResolver } from "@hookform/resolvers/zod";
@@ -8,18 +8,22 @@ import { Loader2 } from "lucide-react";
import { useForm } from "react-hook-form";
import { AuthLoadingSpinner } from "@/components/auth/AuthLoadingSpinner";
import { SupabaseSetupNotice } from "@/components/auth/SupabaseSetupNotice";
import { authFormSchema, type AuthFormValues } from "@/components/auth/auth-schemas";
import { Button } from "@/components/ui/button";
import { createClient } from "@/lib/supabase";
import { cn } from "@/lib/utils";
type AuthTab = "sign-in" | "sign-up";
/** Only allow same-origin relative redirects to avoid open-redirect issues. */
function safeNext(next: string | null): string {
if (next && next.startsWith("/") && !next.startsWith("//")) return next;
return "/dashboard";
}
export function AuthPageContent() {
const router = useRouter();
const searchParams = useSearchParams();
const supabase = useMemo(() => createClient(), []);
const nextPath = safeNext(searchParams.get("next"));
const initialTab =
searchParams.get("tab") === "sign-up" ? "sign-up" : "sign-in";
@@ -27,7 +31,6 @@ export function AuthPageContent() {
const [activeTab, setActiveTab] = useState<AuthTab>(initialTab);
const [authLoading, setAuthLoading] = useState(true);
const [submitting, setSubmitting] = useState(false);
const [oauthLoading, setOauthLoading] = useState(false);
const [formError, setFormError] = useState<string | null>(null);
const [formMessage, setFormMessage] = useState<string | null>(null);
@@ -41,58 +44,30 @@ export function AuthPageContent() {
defaultValues: { email: "", password: "" },
});
const redirectIfAuthenticated = useCallback(async () => {
if (!supabase) return false;
const {
data: { session },
} = await supabase.auth.getSession();
if (session) {
router.replace("/dashboard");
return true;
// Redirect away if already authenticated.
const checkSession = useCallback(async () => {
try {
const res = await fetch("/api/auth/me", { cache: "no-store" });
const data = await res.json().catch(() => null);
if (data?.user) {
router.replace(nextPath);
return true;
}
} catch {
/* not signed in */
}
return false;
}, [router, supabase]);
}, [router, nextPath]);
useEffect(() => {
if (!supabase) {
setAuthLoading(false);
return;
}
let mounted = true;
const init = async () => {
const redirected = await redirectIfAuthenticated();
if (mounted && !redirected) {
setAuthLoading(false);
}
};
init();
const {
data: { subscription },
} = supabase.auth.onAuthStateChange((_event, session) => {
if (session) {
router.replace("/dashboard");
}
checkSession().then((redirected) => {
if (mounted && !redirected) setAuthLoading(false);
});
return () => {
mounted = false;
subscription.unsubscribe();
};
}, [redirectIfAuthenticated, router, supabase]);
useEffect(() => {
const error = searchParams.get("error");
if (error === "auth_callback_failed") {
setFormError("Authentication failed. Please try again.");
}
}, [searchParams]);
}, [checkSession]);
const handleTabChange = (tab: AuthTab) => {
setActiveTab(tab);
@@ -102,66 +77,46 @@ export function AuthPageContent() {
};
const onSubmit = async (values: AuthFormValues) => {
if (!supabase) return;
setSubmitting(true);
setFormError(null);
setFormMessage(null);
if (activeTab === "sign-in") {
const { error } = await supabase.auth.signInWithPassword({
email: values.email,
password: values.password,
});
const endpoint =
activeTab === "sign-in" ? "/api/auth/login" : "/api/auth/register";
if (error) {
setFormError(error.message);
try {
const res = await fetch(endpoint, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email: values.email, password: values.password }),
});
const data = await res.json().catch(() => null);
if (!res.ok) {
setFormError(data?.error ?? "Something went wrong. Please try again.");
setSubmitting(false);
return;
}
router.replace("/dashboard");
} else {
const { data, error } = await supabase.auth.signUp({
email: values.email,
password: values.password,
});
if (error) {
setFormError(error.message);
setSubmitting(false);
return;
}
if (data.session) {
router.replace("/dashboard");
} else {
// Registered but not auto-logged-in (verification gate) — prompt sign-in.
if (data?.registered && !data?.user) {
setFormMessage(
"Check your email to confirm your account, then sign in."
data.verificationRequired
? "Account created. Check your email to verify, then sign in."
: "Account created. Please sign in."
);
setActiveTab("sign-in");
reset();
setSubmitting(false);
return;
}
}
setSubmitting(false);
};
const handleGoogleSignIn = async () => {
if (!supabase) return;
setOauthLoading(true);
setFormError(null);
const { error } = await supabase.auth.signInWithOAuth({
provider: "google",
options: {
redirectTo: `${window.location.origin}/auth/callback?next=/dashboard`,
},
});
if (error) {
setFormError(error.message);
setOauthLoading(false);
// Logged in — cookies are set; refresh server components and go.
router.replace(nextPath);
router.refresh();
} catch {
setFormError("Network error. Please try again.");
setSubmitting(false);
}
};
@@ -173,19 +128,11 @@ export function AuthPageContent() {
);
}
if (!supabase) {
return (
<SupabaseSetupNotice nextPath={searchParams.get("next")} />
);
}
const isBusy = submitting || oauthLoading;
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-3xl font-bold text-neutral-900">
Welcome to CreatorStudio
Welcome to FlatRender
</h1>
<p className="mt-2 text-sm text-neutral-600">
{activeTab === "sign-in"
@@ -213,28 +160,6 @@ export function AuthPageContent() {
</div>
<div className="mt-6 rounded-xl border border-gray-100 bg-white p-6 shadow-sm">
<Button
type="button"
variant="outline"
className="w-full"
disabled={isBusy}
onClick={handleGoogleSignIn}
>
{oauthLoading ? (
<Loader2 className="h-4 w-4 animate-spin" aria-hidden />
) : null}
Continue with Google
</Button>
<div className="relative my-6">
<div className="absolute inset-0 flex items-center">
<span className="w-full border-t border-gray-100" />
</div>
<p className="relative mx-auto w-fit bg-white px-3 text-xs text-neutral-500">
or continue with email
</p>
</div>
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4" noValidate>
<div>
<label
@@ -247,7 +172,7 @@ export function AuthPageContent() {
id="email"
type="email"
autoComplete="email"
disabled={isBusy}
disabled={submitting}
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",
errors.email ? "border-red-300" : "border-gray-100"
@@ -272,7 +197,7 @@ export function AuthPageContent() {
autoComplete={
activeTab === "sign-in" ? "current-password" : "new-password"
}
disabled={isBusy}
disabled={submitting}
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",
errors.password ? "border-red-300" : "border-gray-100"
@@ -298,7 +223,7 @@ export function AuthPageContent() {
</p>
)}
<Button type="submit" className="w-full" disabled={isBusy}>
<Button type="submit" className="w-full" disabled={submitting}>
{submitting ? (
<Loader2 className="h-4 w-4 animate-spin" aria-hidden />
) : null}
+33
View File
@@ -0,0 +1,33 @@
/**
* Server-side helper for calling the FlatRender V2 API gateway.
*
* The gateway is the single public entrypoint to all microservices. All .NET service
* payloads are snake_case, so callers send/receive snake_case JSON.
*
* Local dev: http://localhost:8088 (see GATEWAY_PORT in .env.v2).
* In Docker: set API_GATEWAY_URL=http://gateway:8080.
*/
const GATEWAY_URL = (process.env.API_GATEWAY_URL ?? "http://localhost:8088").replace(
/\/$/,
""
);
export function gatewayUrl(path: string): string {
return `${GATEWAY_URL}${path.startsWith("/") ? path : `/${path}`}`;
}
export async function gatewayFetch(
path: string,
init?: RequestInit
): Promise<Response> {
return fetch(gatewayUrl(path), {
...init,
// Never cache auth/data calls that flow through here.
cache: "no-store",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
...(init?.headers ?? {}),
},
});
}
+14
View File
@@ -0,0 +1,14 @@
// Auth constants shared across route handlers, middleware, and server helpers.
/** httpOnly cookie holding the short-lived (15 min) Identity access JWT. */
export const ACCESS_TOKEN_COOKIE = "fr_access";
/** httpOnly cookie holding the long-lived (30 day) rotating refresh token. */
export const REFRESH_TOKEN_COOKIE = "fr_refresh";
/**
* Tenant the public site authenticates against. FlatRender's own users live in the
* default tenant (slug `flatrender`). Overridable for white-label deployments.
*/
export const DEFAULT_TENANT_SLUG =
process.env.NEXT_PUBLIC_TENANT_SLUG ?? "flatrender";
+33
View File
@@ -0,0 +1,33 @@
import { type NextResponse } from "next/server";
import { ACCESS_TOKEN_COOKIE, REFRESH_TOKEN_COOKIE } from "@/lib/auth/constants";
const REFRESH_MAX_AGE = 60 * 60 * 24 * 30; // 30 days, matches Identity refresh TTL
/** Write the Identity access + refresh tokens as httpOnly cookies on a response. */
export function setAuthCookies(
res: NextResponse,
accessToken: string,
refreshToken: string,
accessExpiresIn: number
): NextResponse {
const secure = process.env.NODE_ENV === "production";
const base = { httpOnly: true, sameSite: "lax", secure, path: "/" } as const;
res.cookies.set(ACCESS_TOKEN_COOKIE, accessToken, {
...base,
maxAge: accessExpiresIn,
});
res.cookies.set(REFRESH_TOKEN_COOKIE, refreshToken, {
...base,
maxAge: REFRESH_MAX_AGE,
});
return res;
}
/** Expire both auth cookies (logout / failed refresh). */
export function clearAuthCookies(res: NextResponse): NextResponse {
for (const name of [ACCESS_TOKEN_COOKIE, REFRESH_TOKEN_COOKIE]) {
res.cookies.set(name, "", { httpOnly: true, path: "/", maxAge: 0 });
}
return res;
}
+46
View File
@@ -0,0 +1,46 @@
// Edge-safe JWT payload decoding. We never verify the signature here — these helpers
// only read claims from our own httpOnly cookie (presence/expiry for route guards).
// The gateway verifies the signature on every real API call.
export interface JwtClaims {
sub?: string;
email?: string;
tenant_id?: string;
tenant_slug?: string;
is_admin?: string | boolean;
is_tenant_admin?: string | boolean;
exp?: number;
[key: string]: unknown;
}
function base64UrlDecode(input: string): string {
const b64 = input.replace(/-/g, "+").replace(/_/g, "/");
const pad = b64.length % 4 === 0 ? "" : "=".repeat(4 - (b64.length % 4));
const raw =
typeof atob === "function"
? atob(b64 + pad)
: Buffer.from(b64 + pad, "base64").toString("binary");
// Reinterpret the binary string as UTF-8 so non-ASCII claims (names) survive.
return decodeURIComponent(
raw
.split("")
.map((c) => "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2))
.join("")
);
}
export function decodeJwt(token: string): JwtClaims | null {
try {
const part = token.split(".")[1];
if (!part) return null;
return JSON.parse(base64UrlDecode(part)) as JwtClaims;
} catch {
return null;
}
}
/** True when the token is missing an exp or is at/past expiry. */
export function isJwtExpired(claims: JwtClaims | null): boolean {
if (!claims?.exp) return true;
return claims.exp * 1000 <= Date.now();
}
+62
View File
@@ -0,0 +1,62 @@
import { cookies } from "next/headers";
import { gatewayFetch } from "@/lib/api/gateway";
import { ACCESS_TOKEN_COOKIE } from "@/lib/auth/constants";
import { decodeJwt, isJwtExpired, type JwtClaims } from "@/lib/auth/jwt";
export interface Session {
userId: string;
email?: string;
tenantId?: string;
isAdmin: boolean;
claims: JwtClaims;
}
/** Raw access token from the httpOnly cookie (for proxying to the gateway). */
export async function getAccessToken(): Promise<string | null> {
const store = await cookies();
return store.get(ACCESS_TOKEN_COOKIE)?.value ?? null;
}
/**
* Decode the current session from the access-token cookie. Returns null when there is
* no token, it is malformed, or it has expired. Use in server components / layouts to
* guard rendering; the gateway is still the authority on every API call.
*/
export async function getSession(): Promise<Session | null> {
const token = await getAccessToken();
if (!token) return null;
const claims = decodeJwt(token);
if (!claims || isJwtExpired(claims) || !claims.sub) return null;
return {
userId: String(claims.sub),
email: claims.email ? String(claims.email) : undefined,
tenantId: claims.tenant_id ? String(claims.tenant_id) : undefined,
isAdmin: String(claims.is_admin) === "true",
claims,
};
}
export interface IdentityUser {
id: string;
email?: string | null;
full_name?: string | null;
avatar_url?: string | null;
is_admin?: boolean;
[key: string]: unknown;
}
/**
* Fetch the full current-user profile from Identity (`/v1/users/me`) using the access
* cookie. Returns null when signed out or the token is rejected — use this as the
* authoritative server-side guard (it validates the token against the service).
*/
export async function getCurrentUser(): Promise<IdentityUser | null> {
const token = await getAccessToken();
if (!token) return null;
const res = await gatewayFetch("/v1/users/me", {
headers: { Authorization: `Bearer ${token}` },
});
if (!res.ok) return null;
return (await res.json().catch(() => null)) as IdentityUser | null;
}
+23 -16
View File
@@ -1,31 +1,38 @@
import { type NextRequest } from "next/server";
import { type NextRequest, NextResponse } from "next/server";
import createIntlMiddleware from "next-intl/middleware";
import { routing } from "@/i18n/routing";
import { updateSession } from "@/lib/supabase/middleware";
import { ACCESS_TOKEN_COOKIE } from "@/lib/auth/constants";
import { decodeJwt, isJwtExpired } from "@/lib/auth/jwt";
const handleI18n = createIntlMiddleware(routing);
export async function middleware(request: NextRequest) {
// 1. Run i18n locale detection / redirect
const i18nResponse = handleI18n(request);
// Routes that require an authenticated Identity session (optionally /en/-prefixed).
const PROTECTED = /^\/(?:en\/)?(?:dashboard|studio)(?:\/|$)/;
// If next-intl redirected (e.g. to add /en/ prefix), honour it immediately
if (i18nResponse.status !== 200 || i18nResponse.headers.has("location")) {
export async function middleware(request: NextRequest) {
// 1. Locale detection / redirect (next-intl)
const i18nResponse = handleI18n(request);
if (
i18nResponse.status !== 200 ||
i18nResponse.headers.has("location")
) {
return i18nResponse;
}
// 2. Run Supabase session refresh on the (possibly rewritten) request
const supabaseResponse = await updateSession(request);
// Carry over any locale cookies/headers set by next-intl
i18nResponse.headers.forEach((value, key) => {
if (!supabaseResponse.headers.has(key)) {
supabaseResponse.headers.set(key, value);
// 2. Auth guard for protected sections
const { pathname } = request.nextUrl;
if (PROTECTED.test(pathname)) {
const token = request.cookies.get(ACCESS_TOKEN_COOKIE)?.value;
if (!token || isJwtExpired(decodeJwt(token))) {
const url = request.nextUrl.clone();
url.pathname = pathname.startsWith("/en") ? "/en/auth" : "/auth";
url.searchParams.set("next", pathname);
return NextResponse.redirect(url);
}
});
}
return supabaseResponse;
return i18nResponse;
}
export const config = {