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:
@@ -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 }),
|
||||
}));
|
||||
Reference in New Issue
Block a user