feat(02-02): auth infrastructure -- route groups, middleware, session, auth-actions, auth store
- Create (auth) route group with standalone layout (no sidebar/header, D-04) - Create (portal) route group wrapping children with AppShell - Move dashboard page into (portal) route group - Add Next.js middleware for JWT-based route protection using jose - Create session.ts with verifySession/getSessionFromCookies helpers - Create auth-actions.ts server actions: login, logout, fetchCurrentUser - Create Zustand auth-store for client-side user state - Install jose and zod dependencies Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -9,11 +9,13 @@
|
|||||||
"type-check": "tsc --noEmit"
|
"type-check": "tsc --noEmit"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"jose": "^6.2.3",
|
||||||
"next": "^15.3.0",
|
"next": "^15.3.0",
|
||||||
"next-intl": "^4.13.0",
|
"next-intl": "^4.13.0",
|
||||||
"next-themes": "^0.4.6",
|
"next-themes": "^0.4.6",
|
||||||
"react": "^19.0.0",
|
"react": "^19.0.0",
|
||||||
"react-dom": "^19.0.0",
|
"react-dom": "^19.0.0",
|
||||||
|
"zod": "^4.4.3",
|
||||||
"zustand": "^5.0.14"
|
"zustand": "^5.0.14"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
/**
|
||||||
|
* Auth layout - standalone, no sidebar/header (D-04).
|
||||||
|
* Used for /login, /reset-password, etc.
|
||||||
|
*/
|
||||||
|
export default function AuthLayout({
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
children: React.ReactNode;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen bg-background">
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import { AppShell } from '@/components/layout/app-shell';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Portal layout - wraps all authenticated pages with AppShell (header + sidebar).
|
||||||
|
* All routes under (portal)/ get the full portal chrome.
|
||||||
|
*/
|
||||||
|
export default function PortalLayout({
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
children: React.ReactNode;
|
||||||
|
}) {
|
||||||
|
return <AppShell>{children}</AppShell>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useTranslations } from 'next-intl';
|
||||||
|
|
||||||
|
export default function DashboardPage() {
|
||||||
|
const t = useTranslations('dashboard');
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col items-center justify-center min-h-[60vh] gap-4">
|
||||||
|
{/* Grid icon */}
|
||||||
|
<div className="rounded-lg bg-muted p-4">
|
||||||
|
<svg
|
||||||
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
|
width="48"
|
||||||
|
height="48"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth="1.5"
|
||||||
|
strokeLinecap="round"
|
||||||
|
strokeLinejoin="round"
|
||||||
|
className="text-muted-foreground"
|
||||||
|
>
|
||||||
|
<rect x="3" y="3" width="7" height="7" rx="1" />
|
||||||
|
<rect x="14" y="3" width="7" height="7" rx="1" />
|
||||||
|
<rect x="14" y="14" width="7" height="7" rx="1" />
|
||||||
|
<rect x="3" y="14" width="7" height="7" rx="1" />
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Empty state text (D-16) */}
|
||||||
|
<p className="text-lg text-muted-foreground">
|
||||||
|
{t('empty')}
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{/* Add widget button */}
|
||||||
|
<button className="mt-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:opacity-90 transition-opacity">
|
||||||
|
{t('addWidget')}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,45 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import { useTranslations } from 'next-intl';
|
|
||||||
import { AppShell } from '@/components/layout/app-shell';
|
|
||||||
|
|
||||||
export default function DashboardPage() {
|
|
||||||
const t = useTranslations('dashboard');
|
|
||||||
|
|
||||||
return (
|
|
||||||
<AppShell>
|
|
||||||
<div className="flex flex-col items-center justify-center min-h-[60vh] gap-4">
|
|
||||||
{/* Grid icon */}
|
|
||||||
<div className="rounded-lg bg-muted p-4">
|
|
||||||
<svg
|
|
||||||
xmlns="http://www.w3.org/2000/svg"
|
|
||||||
width="48"
|
|
||||||
height="48"
|
|
||||||
viewBox="0 0 24 24"
|
|
||||||
fill="none"
|
|
||||||
stroke="currentColor"
|
|
||||||
strokeWidth="1.5"
|
|
||||||
strokeLinecap="round"
|
|
||||||
strokeLinejoin="round"
|
|
||||||
className="text-muted-foreground"
|
|
||||||
>
|
|
||||||
<rect x="3" y="3" width="7" height="7" rx="1" />
|
|
||||||
<rect x="14" y="3" width="7" height="7" rx="1" />
|
|
||||||
<rect x="14" y="14" width="7" height="7" rx="1" />
|
|
||||||
<rect x="3" y="14" width="7" height="7" rx="1" />
|
|
||||||
</svg>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Empty state text (D-16) */}
|
|
||||||
<p className="text-lg text-muted-foreground">
|
|
||||||
{t('empty')}
|
|
||||||
</p>
|
|
||||||
|
|
||||||
{/* Add widget button */}
|
|
||||||
<button className="mt-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:opacity-90 transition-opacity">
|
|
||||||
{t('addWidget')}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</AppShell>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
'use server';
|
||||||
|
|
||||||
|
import { cookies } from 'next/headers';
|
||||||
|
import { redirect } from 'next/navigation';
|
||||||
|
|
||||||
|
const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001';
|
||||||
|
|
||||||
|
export interface AuthUser {
|
||||||
|
id: string;
|
||||||
|
username: string;
|
||||||
|
displayName: string | null;
|
||||||
|
role: 'SUPER_ADMIN' | 'ADMIN' | 'USER';
|
||||||
|
tenantId: string;
|
||||||
|
mustChangePassword: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LoginResult {
|
||||||
|
success: boolean;
|
||||||
|
error?: string;
|
||||||
|
user?: AuthUser;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Login action: POST credentials to API, forward session cookie.
|
||||||
|
* In development, the API runs on a different port (3001) so we
|
||||||
|
* must manually forward the Set-Cookie header from the API response.
|
||||||
|
*/
|
||||||
|
export async function login(formData: FormData): Promise<LoginResult> {
|
||||||
|
const username = formData.get('username') as string;
|
||||||
|
const password = formData.get('password') as string;
|
||||||
|
const rememberMe = formData.get('rememberMe') === 'on';
|
||||||
|
|
||||||
|
if (!username || !password) {
|
||||||
|
return { success: false, error: 'invalidCredentials' };
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${API_URL}/auth/login`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ username, password }),
|
||||||
|
credentials: 'include',
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
return { success: false, error: 'invalidCredentials' };
|
||||||
|
}
|
||||||
|
|
||||||
|
const user: AuthUser = await response.json();
|
||||||
|
|
||||||
|
// Forward the session cookie from the API response to the browser
|
||||||
|
const setCookieHeader = response.headers.get('set-cookie');
|
||||||
|
if (setCookieHeader) {
|
||||||
|
// Parse the session cookie value from the API response
|
||||||
|
const sessionMatch = setCookieHeader.match(/session=([^;]+)/);
|
||||||
|
if (sessionMatch) {
|
||||||
|
const cookieStore = await cookies();
|
||||||
|
cookieStore.set('session', sessionMatch[1], {
|
||||||
|
httpOnly: true,
|
||||||
|
secure: process.env.NODE_ENV === 'production',
|
||||||
|
sameSite: 'lax',
|
||||||
|
// D-02: 30 days if rememberMe, otherwise session cookie (browser close)
|
||||||
|
...(rememberMe
|
||||||
|
? { maxAge: 30 * 24 * 60 * 60 }
|
||||||
|
: {}),
|
||||||
|
path: '/',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { success: true, user };
|
||||||
|
} catch {
|
||||||
|
return { success: false, error: 'networkError' };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Logout action: POST to API, clear local cookie, redirect to /login.
|
||||||
|
*/
|
||||||
|
export async function logout(): Promise<void> {
|
||||||
|
const cookieStore = await cookies();
|
||||||
|
const session = cookieStore.get('session')?.value;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await fetch(`${API_URL}/auth/logout`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
...(session ? { Cookie: `session=${session}` } : {}),
|
||||||
|
},
|
||||||
|
credentials: 'include',
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
// Logout should still clear the cookie even if API call fails
|
||||||
|
}
|
||||||
|
|
||||||
|
cookieStore.delete('session');
|
||||||
|
redirect('/login');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetch the current authenticated user from the API.
|
||||||
|
* Uses the session cookie for authentication.
|
||||||
|
*/
|
||||||
|
export async function fetchCurrentUser(): Promise<AuthUser | null> {
|
||||||
|
const cookieStore = await cookies();
|
||||||
|
const session = cookieStore.get('session')?.value;
|
||||||
|
|
||||||
|
if (!session) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${API_URL}/auth/me`, {
|
||||||
|
headers: {
|
||||||
|
Cookie: `session=${session}`,
|
||||||
|
},
|
||||||
|
credentials: 'include',
|
||||||
|
cache: 'no-store',
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return await response.json();
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import { jwtVerify } from 'jose';
|
||||||
|
import type { RequestCookies } from 'next/dist/compiled/@edge-runtime/cookies';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* JWT secret for verifying session tokens.
|
||||||
|
* Must match the secret used by the NestJS API to sign JWTs.
|
||||||
|
*/
|
||||||
|
function getSecret() {
|
||||||
|
const secret = process.env.JWT_SECRET || process.env.SESSION_SECRET;
|
||||||
|
if (!secret) {
|
||||||
|
throw new Error('JWT_SECRET or SESSION_SECRET environment variable is required');
|
||||||
|
}
|
||||||
|
return new TextEncoder().encode(secret);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verify a JWT session token using jose (Edge-compatible).
|
||||||
|
* Returns the decoded payload or null if verification fails.
|
||||||
|
*/
|
||||||
|
export async function verifySession(token: string) {
|
||||||
|
try {
|
||||||
|
const { payload } = await jwtVerify(token, getSecret(), {
|
||||||
|
algorithms: ['HS256'],
|
||||||
|
});
|
||||||
|
return payload;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Read the "session" cookie value from a cookies object.
|
||||||
|
* Works with Next.js middleware request cookies.
|
||||||
|
*/
|
||||||
|
export function getSessionFromCookies(
|
||||||
|
cookies: RequestCookies | { get: (name: string) => { value: string } | undefined },
|
||||||
|
) {
|
||||||
|
return cookies.get('session')?.value ?? null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import { create } from 'zustand';
|
||||||
|
|
||||||
|
export interface AuthUser {
|
||||||
|
id: string;
|
||||||
|
username: string;
|
||||||
|
displayName: string | null;
|
||||||
|
role: 'SUPER_ADMIN' | 'ADMIN' | 'USER';
|
||||||
|
tenantId: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface AuthState {
|
||||||
|
user: AuthUser | null;
|
||||||
|
setUser: (user: AuthUser) => void;
|
||||||
|
clearUser: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Zustand store for client-side auth state.
|
||||||
|
* No persist middleware -- user state comes from API, not localStorage.
|
||||||
|
* Populated on portal load via fetchCurrentUser().
|
||||||
|
*/
|
||||||
|
export const useAuthStore = create<AuthState>()((set) => ({
|
||||||
|
user: null,
|
||||||
|
setUser: (user) => set({ user }),
|
||||||
|
clearUser: () => set({ user: null }),
|
||||||
|
}));
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
import { NextRequest, NextResponse } from 'next/server';
|
||||||
|
import { jwtVerify } from 'jose';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Next.js middleware for frontend route protection (Pattern 4).
|
||||||
|
*
|
||||||
|
* Validates JWT session cookie on every request. Redirects to /login
|
||||||
|
* if missing or invalid. This is an optimistic check -- the API still
|
||||||
|
* validates the JWT independently on every request.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const publicRoutes = ['/login', '/reset-password'];
|
||||||
|
|
||||||
|
function getSecret() {
|
||||||
|
const secret = process.env.JWT_SECRET || process.env.SESSION_SECRET;
|
||||||
|
if (!secret) {
|
||||||
|
// In development, allow a fallback to prevent startup crashes
|
||||||
|
// when env vars are not yet configured
|
||||||
|
return new TextEncoder().encode('development-secret-change-me');
|
||||||
|
}
|
||||||
|
return new TextEncoder().encode(secret);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function middleware(req: NextRequest) {
|
||||||
|
const path = req.nextUrl.pathname;
|
||||||
|
|
||||||
|
// Allow public routes without authentication
|
||||||
|
if (publicRoutes.some((route) => path.startsWith(route))) {
|
||||||
|
return NextResponse.next();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Skip static assets and API routes (handled by NestJS)
|
||||||
|
if (
|
||||||
|
path.startsWith('/_next/static') ||
|
||||||
|
path.startsWith('/_next/image') ||
|
||||||
|
path.startsWith('/favicon.ico') ||
|
||||||
|
path.startsWith('/api')
|
||||||
|
) {
|
||||||
|
return NextResponse.next();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read session cookie
|
||||||
|
const session = req.cookies.get('session')?.value;
|
||||||
|
|
||||||
|
if (!session) {
|
||||||
|
return NextResponse.redirect(new URL('/login', req.nextUrl));
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { payload } = await jwtVerify(session, getSecret(), {
|
||||||
|
algorithms: ['HS256'],
|
||||||
|
});
|
||||||
|
|
||||||
|
// D-06: Force password change redirect
|
||||||
|
if (
|
||||||
|
payload.mustChangePassword === true &&
|
||||||
|
!path.startsWith('/change-password')
|
||||||
|
) {
|
||||||
|
return NextResponse.redirect(new URL('/change-password', req.nextUrl));
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.next();
|
||||||
|
} catch {
|
||||||
|
// JWT verification failed -- clear stale cookie and redirect to login
|
||||||
|
const response = NextResponse.redirect(new URL('/login', req.nextUrl));
|
||||||
|
response.cookies.delete('session');
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const config = {
|
||||||
|
matcher: ['/((?!api|_next/static|_next/image|.*\\.png$).*)'],
|
||||||
|
};
|
||||||
Generated
+16
@@ -99,6 +99,9 @@ importers:
|
|||||||
|
|
||||||
apps/web:
|
apps/web:
|
||||||
dependencies:
|
dependencies:
|
||||||
|
jose:
|
||||||
|
specifier: ^6.2.3
|
||||||
|
version: 6.2.3
|
||||||
next:
|
next:
|
||||||
specifier: ^15.3.0
|
specifier: ^15.3.0
|
||||||
version: 15.5.19(react-dom@19.2.7(react@19.2.7))(react@19.2.7)
|
version: 15.5.19(react-dom@19.2.7(react@19.2.7))(react@19.2.7)
|
||||||
@@ -114,6 +117,9 @@ importers:
|
|||||||
react-dom:
|
react-dom:
|
||||||
specifier: ^19.0.0
|
specifier: ^19.0.0
|
||||||
version: 19.2.7(react@19.2.7)
|
version: 19.2.7(react@19.2.7)
|
||||||
|
zod:
|
||||||
|
specifier: ^4.4.3
|
||||||
|
version: 4.4.3
|
||||||
zustand:
|
zustand:
|
||||||
specifier: ^5.0.14
|
specifier: ^5.0.14
|
||||||
version: 5.0.14(@types/react@19.2.17)(react@19.2.7)
|
version: 5.0.14(@types/react@19.2.17)(react@19.2.7)
|
||||||
@@ -1745,6 +1751,9 @@ packages:
|
|||||||
resolution: {integrity: sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==}
|
resolution: {integrity: sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==}
|
||||||
hasBin: true
|
hasBin: true
|
||||||
|
|
||||||
|
jose@6.2.3:
|
||||||
|
resolution: {integrity: sha512-YYVDInQKFJfR/xa3ojUTl8c2KoTwiL1R5Wg9YCydwH0x0B9grbzlg5HC7mMjCtUJjbQ/YnGEZIhI5tCgfTb4Hw==}
|
||||||
|
|
||||||
js-tokens@4.0.0:
|
js-tokens@4.0.0:
|
||||||
resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==}
|
resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==}
|
||||||
|
|
||||||
@@ -2559,6 +2568,9 @@ packages:
|
|||||||
resolution: {integrity: sha512-U/PBtDf35ff0D8X8D0jfdzHYEPFxAI7jJlxZXwCSez5M3190m+QobIfh+sWDWSHMCWWJN2AWamkegn6vr6YBTw==}
|
resolution: {integrity: sha512-U/PBtDf35ff0D8X8D0jfdzHYEPFxAI7jJlxZXwCSez5M3190m+QobIfh+sWDWSHMCWWJN2AWamkegn6vr6YBTw==}
|
||||||
engines: {node: '>=18'}
|
engines: {node: '>=18'}
|
||||||
|
|
||||||
|
zod@4.4.3:
|
||||||
|
resolution: {integrity: sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==}
|
||||||
|
|
||||||
zustand@5.0.14:
|
zustand@5.0.14:
|
||||||
resolution: {integrity: sha512-/8tAspM5LMPr28b3fwLYrtdj77ECpfZviaP75CMTnwO8ISyaE4GDIG/9rDDYq/cH9D2Xw2A2RXglLInmVBQB/g==}
|
resolution: {integrity: sha512-/8tAspM5LMPr28b3fwLYrtdj77ECpfZviaP75CMTnwO8ISyaE4GDIG/9rDDYq/cH9D2Xw2A2RXglLInmVBQB/g==}
|
||||||
engines: {node: '>=12.20.0'}
|
engines: {node: '>=12.20.0'}
|
||||||
@@ -4119,6 +4131,8 @@ snapshots:
|
|||||||
|
|
||||||
jiti@2.7.0: {}
|
jiti@2.7.0: {}
|
||||||
|
|
||||||
|
jose@6.2.3: {}
|
||||||
|
|
||||||
js-tokens@4.0.0: {}
|
js-tokens@4.0.0: {}
|
||||||
|
|
||||||
js-yaml@4.2.0:
|
js-yaml@4.2.0:
|
||||||
@@ -4906,6 +4920,8 @@ snapshots:
|
|||||||
|
|
||||||
yoctocolors-cjs@2.1.3: {}
|
yoctocolors-cjs@2.1.3: {}
|
||||||
|
|
||||||
|
zod@4.4.3: {}
|
||||||
|
|
||||||
zustand@5.0.14(@types/react@19.2.17)(react@19.2.7):
|
zustand@5.0.14(@types/react@19.2.17)(react@19.2.7):
|
||||||
optionalDependencies:
|
optionalDependencies:
|
||||||
'@types/react': 19.2.17
|
'@types/react': 19.2.17
|
||||||
|
|||||||
Reference in New Issue
Block a user