Kurs Next.js · Moduł 7: Uwierzytelnianie i autoryzacja
Context Provider dla autentykacji
W tej lekcji12
W poprzednich modułach poznaliśmy podstawy uwierzytelniania, podłączanie zewnętrznych dostawców, zarządzanie sesjami, system ról i uprawnień oraz middleware do ochrony tras. Teraz zajmiemy się tworzeniem Context Providera dla autentykacji, który ułatwi dostęp do danych i funkcji uwierzytelniania w całej aplikacji React.
Context API w React pozwala na przekazywanie danych przez drzewo komponentów bez konieczności przekazywania props na każdym poziomie. Jest to idealne rozwiązanie dla funkcjonalności, która jest potrzebna w wielu miejscach aplikacji - dokładnie tak jak autentykacja.
Dlaczego warto stworzyć własny Context Provider dla autentykacji?
NextAuth.js dostarcza już SessionProvider, który udostępnia podstawowe informacje o sesji. Jednak często warto rozszerzyć tę funkcjonalność o dodatkowe możliwości:
- Centralizacja logiki uwierzytelniania - wszystkie funkcje związane z uwierzytelnianiem w jednym miejscu
- Dodatkowe metody - np. sprawdzanie uprawnień, obsługa rejestracji, resetowania hasła
- Stan ładowania - łatwiejsze zarządzanie stanem ładowania sesji
- Obsługa błędów - spójne zarządzanie błędami uwierzytelniania
- Kontrakt typowania - jasno zdefiniowany interfejs dla TypeScript
Implementacja AuthContext i AuthProvider
Zacznijmy od zdefiniowania podstawowego kontekstu uwierzytelniania:
// lib/authContext.tsx
import { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { Session } from 'next-auth';
import { useSession, signIn, signOut } from 'next-auth/react';
// Definiowanie typu dla kontekstu uwierzytelniania
type AuthContextType = {
session: Session | null;
status: 'loading' | 'authenticated' | 'unauthenticated';
isLoading: boolean;
isAuthenticated: boolean;
user: Session['user'] | null;
hasRole: (role: string | string[]) => boolean;
hasPermission: (permission: string | string[]) => boolean;
signIn: (provider?: string, options?: any) => Promise<any>;
signOut: (options?: any) => Promise<any>;
error: string | null;
};
// Tworzenie kontekstu z wartością domyślną (null)
const AuthContext = createContext<AuthContextType | null>(null);
// Hook pozwalający na łatwy dostęp do kontekstu
export function useAuth() {
const context = useContext(AuthContext);
if (!context) {
throw new Error('useAuth must be used within an AuthProvider');
}
return context;
}
// Komponent dostawcy (provider)
interface AuthProviderProps {
children: ReactNode;
}
export function AuthProvider({ children }: AuthProviderProps) {
// Używamy useSession z NextAuth.js do pobierania danych sesji
const { data: session, status } = useSession();
const [error, setError] = useState<string | null>(null);
// Sprawdź, czy użytkownik ma określoną rolę
const hasRole = (role: string | string[]): boolean => {
if (!session?.user?.role) return false;
if (Array.isArray(role)) {
return role.includes(session.user.role as string);
}
return session.user.role === role;
};
// Sprawdź, czy użytkownik ma określone uprawnienie
const hasPermission = (permission: string | string[]): boolean => {
if (!session?.user?.permissions) return false;
const userPermissions = session.user.permissions as string[];
if (Array.isArray(permission)) {
return permission.some(p => userPermissions.includes(p));
}
return userPermissions.includes(permission as string);
};
// Prosłupa funkcja opakowująca signIn z obsługą błędów
const handleSignIn = async (provider?: string, options?: any) => {
try {
setError(null);
return await signIn(provider, options);
} catch (err) {
console.error('Login error:', err);
setError('Wystąpił problem podczas logowania. Spróbuj ponownie.');
throw err;
}
};
// Prosta funkcja opakowująca signOut
const handleSignOut = async (options?: any) => {
try {
return await signOut(options);
} catch (err) {
console.error('Logout error:', err);
setError('Wystąpił problem podczas wylogowywania.');
throw err;
}
};
// Wartość kontekstu, która będzie udostępniana
const value: AuthContextType = {
session,
status,
isLoading: status === 'loading',
isAuthenticated: status === 'authenticated',
user: session?.user || null,
hasRole,
hasPermission,
signIn: handleSignIn,
signOut: handleSignOut,
error,
};
return (
<AuthContext.Provider value={value}>
{children}
</AuthContext.Provider>
);
}Integracja AuthProvider z aplikacją
Autoryzacja jest funkcjonalnością całej aplikacji, więc najlepiej dodać AuthProvider na wysokim poziomie w drzewie komponentów, najlepiej w głównym layoucie aplikacji, opakowując nim SessionProvider z NextAuth.js:
// app/providers.tsx
'use client';
import { SessionProvider } from 'next-auth/react';
import { AuthProvider } from '@/lib/authContext';
import { ReactNode } from 'react';
export function Providers({ children }: { children: ReactNode }) {
return (
<SessionProvider>
<AuthProvider>
{children}
</AuthProvider>
</SessionProvider>
);
}
// app/layout.tsx
import { Providers } from "./providers";
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="pl">
<body>
<Providers>
{children}
</Providers>
</body>
</html>
);
}Tworzenie PasswordResetProvider jako przykład wyspecjalizowanego providera
Często potrzebujemy również wyspecjalizowanych kontekstów dla konkretnych funkcjonalności uwierzytelniania, jak na przykład resetowanie hasła. Oto przykład takiego providera:
// lib/passwordResetContext.tsx
import { createContext, useContext, useState, ReactNode } from 'react';
type PasswordResetContextType = {
isLoading: boolean;
error: string | null;
message: string | null;
requestPasswordReset: (email: string) => Promise<boolean>;
resetPassword: (token: string, newPassword: string) => Promise<boolean>;
};
const PasswordResetContext = createContext<PasswordResetContextType | null>(null);
export function usePasswordReset() {
const context = useContext(PasswordResetContext);
if (!context) {
throw new Error('usePasswordReset must be used within a PasswordResetProvider');
}
return context;
}
interface PasswordResetProviderProps {
children: ReactNode;
}
export function PasswordResetProvider({ children }: PasswordResetProviderProps) {
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [message, setMessage] = useState<string | null>(null);
// Funkcja do wysyłania żądania resetowania hasła
const requestPasswordReset = async (email: string): Promise<boolean> => {
setIsLoading(true);
setError(null);
setMessage(null);
try {
const response = await fetch('/api/auth/reset-password', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email }),
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.message || 'Wystąpił problem podczas wysyłania linku resetującego');
}
setMessage('Instrukcje resetowania hasła zostały wysłane na podany adres email.');
return true;
} catch (err) {
setError(err instanceof Error ? err.message : 'Wystąpił nieznany błąd');
return false;
} finally {
setIsLoading(false);
}
};
// Funkcja do ustawiania nowego hasła
const resetPassword = async (token: string, newPassword: string): Promise<boolean> => {
setIsLoading(true);
setError(null);
setMessage(null);
try {
const response = await fetch('/api/auth/reset-password/confirm', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token, newPassword }),
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.message || 'Wystąpił problem podczas resetowania hasła');
}
setMessage('Hasło zostało pomyślnie zmienione. Możesz się teraz zalogować.');
return true;
} catch (err) {
setError(err instanceof Error ? err.message : 'Wystąpił nieznany błąd');
return false;
} finally {
setIsLoading(false);
}
};
const value: PasswordResetContextType = {
isLoading,
error,
message,
requestPasswordReset,
resetPassword,
};
return (
<PasswordResetContext.Provider value={value}>
{children}
</PasswordResetContext.Provider>
);
}Rozszerzenie AuthProvider o dodatkowe funkcjonalności
Nasz AuthProvider możemy rozszerzyć o dodatkowe funkcjonalności, które często będą potrzebne w aplikacjach:
1. Rejestracja użytkownika
// Rozszerzone metody w AuthContext
type AuthContextType = {
// ... istniejące pola
registerUser: (userData: RegisterUserData) => Promise<boolean>;
};
// Dane do rejestracji
type RegisterUserData = {
name: string;
email: string;
password: string;
};
// Implementacja w AuthProvider
export function AuthProvider({ children }: AuthProviderProps) {
// ... istniejący kod
const registerUser = async (userData: RegisterUserData): Promise<boolean> => {
try {
setError(null);
const response = await fetch('/api/auth/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(userData),
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.message || 'Wystąpił problem podczas rejestracji');
}
return true;
} catch (err) {
console.error('Registration error:', err);
setError(err instanceof Error ? err.message : 'Wystąpił nieznany błąd podczas rejestracji');
return false;
}
};
const value: AuthContextType = {
// ... istniejące pola
registerUser,
};
// ... istniejący kod
}2. Aktualizacja profilu użytkownika
// Rozszerzone metody w AuthContext
type AuthContextType = {
// ... istniejące pola
updateUserProfile: (profileData: UpdateProfileData) => Promise<boolean>;
};
// Dane do aktualizacji profilu
type UpdateProfileData = {
name?: string;
email?: string;
currentPassword?: string;
newPassword?: string;
image?: string;
};
// Implementacja w AuthProvider
export function AuthProvider({ children }: AuthProviderProps) {
// ... istniejący kod
const updateUserProfile = async (profileData: UpdateProfileData): Promise<boolean> => {
try {
setError(null);
const response = await fetch('/api/user/profile', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(profileData),
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.message || 'Wystąpił problem podczas aktualizacji profilu');
}
// Wymuś odświeżenie sesji, aby pobrać zaktualizowane dane
await refreshSession();
return true;
} catch (err) {
console.error('Profile update error:', err);
setError(err instanceof Error ? err.message : 'Wystąpił nieznany błąd podczas aktualizacji profilu');
return false;
}
};
// Funkcja odświeżająca sesję
const refreshSession = async () => {
// Obecnie w Next.js 13+ z App Router możemy użyć:
const event = new Event('visibilitychange');
document.dispatchEvent(event);
// Alternatywnie, możemy sami zaimplementować odświeżanie sesji
// np. poprzez re-render providera
};
const value: AuthContextType = {
// ... istniejące pola
updateUserProfile,
};
// ... istniejący kod
}3. Obsługa uwierzytelniania dwuskładnikowego (2FA)
// Rozszerzone metody w AuthContext
type AuthContextType = {
// ... istniejące pola
enable2FA: () => Promise<{ secret: string; qrCodeUrl: string }>;
verify2FA: (token: string) => Promise<boolean>;
disable2FA: (token: string) => Promise<boolean>;
is2FAEnabled: boolean;
};
// Implementacja w AuthProvider
export function AuthProvider({ children }: AuthProviderProps) {
// ... istniejący kod
const [is2FAEnabled, setIs2FAEnabled] = useState(false);
// Aktualizuj stan 2FA na podstawie sesji
useEffect(() => {
if (session?.user?.twoFactorEnabled) {
setIs2FAEnabled(true);
} else {
setIs2FAEnabled(false);
}
}, [session]);
// Włącz 2FA
const enable2FA = async () => {
try {
setError(null);
const response = await fetch('/api/auth/2fa/enable', {
method: 'POST',
});
if (!response.ok) {
const data = await response.json();
throw new Error(data.message || 'Wystąpił problem podczas włączania 2FA');
}
const { secret, qrCodeUrl } = await response.json();
return { secret, qrCodeUrl };
} catch (err) {
console.error('Enable 2FA error:', err);
setError(err instanceof Error ? err.message : 'Wystąpił nieznany błąd');
throw err;
}
};
// Weryfikuj token 2FA
const verify2FA = async (token: string) => {
try {
setError(null);
const response = await fetch('/api/auth/2fa/verify', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token }),
});
if (!response.ok) {
const data = await response.json();
throw new Error(data.message || 'Nieprawidłowy kod weryfikacyjny');
}
// Odśwież sesję, aby zaktualizować stan 2FA
await refreshSession();
setIs2FAEnabled(true);
return true;
} catch (err) {
console.error('Verify 2FA error:', err);
setError(err instanceof Error ? err.message : 'Wystąpił nieznany błąd');
return false;
}
};
// Wyłącz 2FA
const disable2FA = async (token: string) => {
try {
setError(null);
const response = await fetch('/api/auth/2fa/disable', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token }),
});
if (!response.ok) {
const data = await response.json();
throw new Error(data.message || 'Nieprawidłowy kod weryfikacyjny');
}
// Odśwież sesję, aby zaktualizować stan 2FA
await refreshSession();
setIs2FAEnabled(false);
return true;
} catch (err) {
console.error('Disable 2FA error:', err);
setError(err instanceof Error ? err.message : 'Wystąpił nieznany błąd');
return false;
}
};
const value: AuthContextType = {
// ... istniejące pola
enable2FA,
verify2FA,
disable2FA,
is2FAEnabled,
};
// ... istniejący kod
}Użycie AuthContext w komponentach
Teraz możemy użyć naszego AuthContext w komponentach aplikacji:
1. Komponent przycisku logowania/wylogowania
// components/AuthButton.tsx
'use client';
import { useAuth } from '@/lib/authContext';
export function AuthButton() {
const { isAuthenticated, isLoading, signIn, signOut, user } = useAuth();
if (isLoading) {
return <button className="btn btn-ghost animate-pulse">Ładowanie...</button>;
}
if (isAuthenticated) {
return (
<button
onClick={() => signOut({ callbackUrl: '/' })}
className="btn btn-outline"
>
Wyloguj {user?.name}
</button>
);
}
return (
<button
onClick={() => signIn()}
className="btn btn-primary"
>
Zaloguj się
</button>
);
}2. Komponent strony chronionej
// app/dashboard/page.tsx
'use client';
import { useAuth } from '@/lib/authContext';
import { useEffect } from 'react';
import { useRouter } from 'next/navigation';
export default function DashboardPage() {
const { isAuthenticated, isLoading, user, hasRole } = useAuth();
const router = useRouter();
// Przekieruj do strony logowania, jeśli użytkownik nie jest zalogowany
useEffect(() => {
if (!isLoading && !isAuthenticated) {
router.push('/auth/login?callbackUrl=/dashboard');
}
}, [isLoading, isAuthenticated, router]);
if (isLoading) {
return <div className="flex justify-center p-8">Ładowanie...</div>;
}
if (!isAuthenticated) {
return null; // Unikaj migotania przed przekierowaniem
}
return (
<div className="container mx-auto p-6">
<h1 className="text-2xl font-bold mb-6">Witaj, {user?.name}!</h1>
<div className="bg-white shadow rounded-lg p-6">
<h2 className="text-xl font-semibold mb-4">Dashboard</h2>
{/* Zawartość dostępna dla wszystkich zalogowanych użytkowników */}
<div className="mb-6">
<h3 className="text-lg font-medium mb-2">Twój profil</h3>
<p>Email: {user?.email}</p>
<p>Rola: {user?.role}</p>
</div>
{/* Zawartość widoczna tylko dla administratorów */}
{hasRole('admin') && (
<div className="p-4 bg-purple-50 rounded-lg">
<h3 className="text-lg font-medium mb-2 text-purple-800">Panel administratora</h3>
<p className="text-purple-700">Ta sekcja jest widoczna tylko dla administratorów.</p>
<button className="mt-2 px-4 py-2 bg-purple-600 text-white rounded">Zarządzaj użytkownikami</button>
</div>
)}
{/* Zawartość widoczna tylko dla określonych ról */}
{hasRole(['admin', 'editor']) && (
<div className="mt-4 p-4 bg-blue-50 rounded-lg">
<h3 className="text-lg font-medium mb-2 text-blue-800">Zarządzanie treścią</h3>
<p className="text-blue-700">Ta sekcja jest dostępna dla administratorów i edytorów.</p>
</div>
)}
</div>
</div>
);
}3. Formularz rejestracji z walidacją
// app/auth/register/page.tsx
'use client';
import { useAuth } from '@/lib/authContext';
import { useState, FormEvent } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
export default function RegisterPage() {
const { registerUser, error: authError, isAuthenticated } = useAuth();
const router = useRouter();
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
const [isLoading, setIsLoading] = useState(false);
const [formError, setFormError] = useState<string | null>(null);
const [successMessage, setSuccessMessage] = useState<string | null>(null);
// Jeśli użytkownik jest już zalogowany, przekieruj do dashboardu
if (isAuthenticated) {
router.push('/dashboard');
return null;
}
const handleSubmit = async (e: FormEvent) => {
e.preventDefault();
setFormError(null);
setSuccessMessage(null);
// Walidacja formularza
if (password !== confirmPassword) {
setFormError('Hasła nie są identyczne');
return;
}
if (password.length < 8) {
setFormError('Hasło musi mieć co najmniej 8 znaków');
return;
}
setIsLoading(true);
try {
const success = await registerUser({ name, email, password });
if (success) {
setSuccessMessage('Rejestracja zakończona pomyślnie! Możesz się teraz zalogować.');
// Opcjonalnie: przekieruj do strony logowania po krótkim opóźnieniu
setTimeout(() => {
router.push('/auth/login');
}, 2000);
}
} catch (err) {
console.error('Registration error:', err);
// Błąd jest już obsługiwany przez AuthProvider
} finally {
setIsLoading(false);
}
};
return (
<div className="max-w-md mx-auto mt-10 p-6 bg-white rounded-lg shadow-md">
<h1 className="text-2xl font-bold mb-6 text-center">Rejestracja</h1>
{/* Wyświetl błędy */}
{(formError || authError) && (
<div className="mb-4 p-3 bg-red-100 text-red-700 rounded-md">
{formError || authError}
</div>
)}
{/* Wyświetl komunikat o sukcesie */}
{successMessage && (
<div className="mb-4 p-3 bg-green-100 text-green-700 rounded-md">
{successMessage}
</div>
)}
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label htmlFor="name" className="block text-sm font-medium mb-1">
Imię i nazwisko
</label>
<input
id="name"
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
required
/>
</div>
<div>
<label htmlFor="email" className="block text-sm font-medium mb-1">
Email
</label>
<input
id="email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
required
/>
</div>
<div>
<label htmlFor="password" className="block text-sm font-medium mb-1">
Hasło
</label>
<input
id="password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
required
minLength={8}
/>
</div>
<div>
<label htmlFor="confirmPassword" className="block text-sm font-medium mb-1">
Potwierdź hasło
</label>
<input
id="confirmPassword"
type="password"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
required
/>
</div>
<button
type="submit"
disabled={isLoading}
className="w-full bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:opacity-50"
>
{isLoading ? 'Przetwarzanie...' : 'Zarejestruj się'}
</button>
</form>
<div className="mt-6 text-center">
<p className="text-sm text-gray-600">
Masz już konto?{' '}
<Link href="/auth/login" className="text-blue-600 hover:underline">
Zaloguj się
</Link>
</p>
</div>
</div>
);
}4. Formularz resetowania hasła
// app/auth/reset-password/page.tsx
'use client';
import { useState, FormEvent } from 'react';
import { usePasswordReset } from '@/lib/passwordResetContext';
import Link from 'next/link';
export default function PasswordResetPage() {
const [email, setEmail] = useState('');
const { requestPasswordReset, isLoading, error, message } = usePasswordReset();
const handleSubmit = async (e: FormEvent) => {
e.preventDefault();
await requestPasswordReset(email);
};
return (
<div className="max-w-md mx-auto mt-10 p-6 bg-white rounded-lg shadow-md">
<h1 className="text-2xl font-bold mb-6 text-center">Resetowanie hasła</h1>
{error && (
<div className="mb-4 p-3 bg-red-100 text-red-700 rounded-md">
{error}
</div>
)}
{message && (
<div className="mb-4 p-3 bg-green-100 text-green-700 rounded-md">
{message}
</div>
)}
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label htmlFor="email" className="block text-sm font-medium mb-1">
Email
</label>
<input
id="email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
required
disabled={isLoading || !!message} // Zablokuj po pomyślnym wysłaniu
/>
</div>
<button
type="submit"
disabled={isLoading || !!message}
className="w-full bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:opacity-50"
>
{isLoading ? 'Wysyłanie...' : 'Resetuj hasło'}
</button>
</form>
<div className="mt-6 text-center">
<p className="text-sm text-gray-600">
<Link href="/auth/login" className="text-blue-600 hover:underline">
Powrót do strony logowania
</Link>
</p>
</div>
</div>
);
}Tworzenie komponentów wysokiego poziomu (HOC) do ochrony stron
Możemy również stworzyć komponenty wysokiego poziomu (Higher-Order Components, HOC), które będą chronić dostęp do stron na podstawie stanu uwierzytelniania:
// components/withAuth.tsx
'use client';
import { useAuth } from '@/lib/authContext';
import { useRouter } from 'next/navigation';
import { useEffect, ComponentType } from 'react';
// HOC do wymagania uwierzytelnienia
export function withAuth<P extends object>(Component: ComponentType<P>) {
return function AuthProtected(props: P) {
const { isAuthenticated, isLoading } = useAuth();
const router = useRouter();
useEffect(() => {
if (!isLoading && !isAuthenticated) {
router.push(`/auth/login?callbackUrl=${encodeURIComponent(window.location.pathname)}`);
}
}, [isLoading, isAuthenticated, router]);
if (isLoading) {
return <div className="flex justify-center p-8">Ładowanie...</div>;
}
if (!isAuthenticated) {
return null; // Unikaj migotania przed przekierowaniem
}
return <Component {...props} />;
};
}
// HOC do wymagania określonej roli
export function withRole<P extends object>(Component: ComponentType<P>, requiredRole: string | string[]) {
return function RoleProtected(props: P) {
const { isAuthenticated, isLoading, hasRole, user } = useAuth();
const router = useRouter();
useEffect(() => {
if (!isLoading) {
if (!isAuthenticated) {
router.push(`/auth/login?callbackUrl=${encodeURIComponent(window.location.pathname)}`);
} else if (!hasRole(requiredRole)) {
router.push('/auth/unauthorized');
}
}
}, [isLoading, isAuthenticated, hasRole, router]);
if (isLoading) {
return <div className="flex justify-center p-8">Ładowanie...</div>;
}
if (!isAuthenticated || !hasRole(requiredRole)) {
return null; // Unikaj migotania przed przekierowaniem
}
return <Component {...props} />;
};
}
// HOC do wymagania określonego uprawnienia
export function withPermission<P extends object>(Component: ComponentType<P>, requiredPermission: string | string[]) {
return function PermissionProtected(props: P) {
const { isAuthenticated, isLoading, hasPermission } = useAuth();
const router = useRouter();
useEffect(() => {
if (!isLoading) {
if (!isAuthenticated) {
router.push(`/auth/login?callbackUrl=${encodeURIComponent(window.location.pathname)}`);
} else if (!hasPermission(requiredPermission)) {
router.push('/auth/unauthorized');
}
}
}, [isLoading, isAuthenticated, hasPermission, router]);
if (isLoading) {
return <div className="flex justify-center p-8">Ładowanie...</div>;
}
if (!isAuthenticated || !hasPermission(requiredPermission)) {
return null; // Unikaj migotania przed przekierowaniem
}
return <Component {...props} />;
};
}Przykład użycia HOC:
// app/admin/settings/page.tsx
'use client';
import { withRole } from '@/components/withAuth';
function AdminSettingsPage() {
return (
<div className="container mx-auto p-6">
<h1 className="text-2xl font-bold mb-6">Ustawienia administratora</h1>
{/* Zawartość strony */}
</div>
);
}
// Eksportujemy komponent chroniony przez HOC
export default withRole(AdminSettingsPage, 'admin');
// app/content/edit/page.tsx
'use client';
import { withPermission } from '@/components/withAuth';
function EditContentPage() {
return (
<div className="container mx-auto p-6">
<h1 className="text-2xl font-bold mb-6">Edycja zawartości</h1>
{/* Zawartość strony */}
</div>
);
}
// Eksportujemy komponent chroniony przez HOC
export default withPermission(EditContentPage, 'content:edit');Integracja z systemem zarządzania stanem aplikacji
Nasz AuthContext może być również zintegrowany z bardziej złożonym systemem zarządzania stanem aplikacji, takim jak Redux, Zustand czy Jotai. Na przykład, integracja z Zustand mogłaby wyglądać następująco:
// lib/authStore.ts
import { create } from 'zustand';
import { Session } from 'next-auth';
type AuthState = {
session: Session | null;
status: 'loading' | 'authenticated' | 'unauthenticated';
error: string | null;
user: Session['user'] | null;
setSession: (session: Session | null) => void;
setStatus: (status: 'loading' | 'authenticated' | 'unauthenticated') => void;
setError: (error: string | null) => void;
hasRole: (role: string | string[]) => boolean;
hasPermission: (permission: string | string[]) => boolean;
reset: () => void;
};
export const useAuthStore = create<AuthState>((set, get) => ({
session: null,
status: 'loading',
error: null,
user: null,
setSession: (session) => set({
session,
user: session?.user || null,
status: session ? 'authenticated' : 'unauthenticated'
}),
setStatus: (status) => set({ status }),
setError: (error) => set({ error }),
hasRole: (role) => {
const { user } = get();
if (!user?.role) return false;
if (Array.isArray(role)) {
return role.includes(user.role as string);
}
return user.role === role;
},
hasPermission: (permission) => {
const { user } = get();
if (!user?.permissions) return false;
const userPermissions = user.permissions as string[];
if (Array.isArray(permission)) {
return permission.some(p => userPermissions.includes(p));
}
return userPermissions.includes(permission as string);
},
reset: () => set({
session: null,
status: 'unauthenticated',
error: null,
user: null
}),
}));
// Zmodyfikowany AuthProvider używający Zustand
export function AuthProvider({ children }: { children: ReactNode }) {
const { data: session, status } = useSession();
const { setSession, setStatus, setError } = useAuthStore();
// Aktualizuj store przy zmianie sesji
useEffect(() => {
setSession(session);
setStatus(status);
}, [session, status, setSession, setStatus]);
return <>{children}</>;
}Testowanie AuthContext
Testowanie Auth Context jest kluczowe dla zapewnienia niezawodności systemu uwierzytelniania. Poniżej przedstawiono przykład testów z wykorzystaniem React Testing Library i Jest:
// __tests__/authContext.test.tsx
import { render, screen, waitFor, fireEvent } from '@testing-library/react';
import { AuthProvider, useAuth } from '@/lib/authContext';
import { SessionProvider } from 'next-auth/react';
// Mock next-auth
jest.mock('next-auth/react', () => ({
useSession: jest.fn(),
signIn: jest.fn(),
signOut: jest.fn(),
}));
// Komponent testowy używający useAuth
function TestComponent() {
const { isAuthenticated, user, hasRole, hasPermission } = useAuth();
return (
<div>
<div data-testid="auth-status">
{isAuthenticated ? 'Authenticated' : 'Not authenticated'}
</div>
{user && <div data-testid="user-name">{user.name}</div>}
<div data-testid="admin-role">
{hasRole('admin') ? 'Has admin role' : 'No admin role'}
</div>
<div data-testid="edit-permission">
{hasPermission('content:edit') ? 'Can edit content' : 'Cannot edit content'}
</div>
</div>
);
}
// Wrapper dla testów
function renderWithAuth(ui: React.ReactNode, sessionData: any = null) {
const useSessionMock = require('next-auth/react').useSession;
// Ustaw mock dla useSession
useSessionMock.mockReturnValue(sessionData);
return render(
<SessionProvider>
<AuthProvider>{ui}</AuthProvider>
</SessionProvider>
);
}
describe('AuthContext', () => {
it('should show unauthenticated state when no session exists', () => {
renderWithAuth(<TestComponent />, {
data: null,
status: 'unauthenticated'
});
expect(screen.getByTestId('auth-status')).toHaveTextContent('Not authenticated');
expect(screen.getByTestId('admin-role')).toHaveTextContent('No admin role');
expect(screen.getByTestId('edit-permission')).toHaveTextContent('Cannot edit content');
});
it('should show authenticated state with user data when session exists', () => {
renderWithAuth(<TestComponent />, {
data: {
user: {
name: 'Test User',
email: 'test@example.com',
role: 'user',
permissions: ['content:read']
}
},
status: 'authenticated'
});
expect(screen.getByTestId('auth-status')).toHaveTextContent('Authenticated');
expect(screen.getByTestId('user-name')).toHaveTextContent('Test User');
expect(screen.getByTestId('admin-role')).toHaveTextContent('No admin role');
expect(screen.getByTestId('edit-permission')).toHaveTextContent('Cannot edit content');
});
it('should correctly check for admin role', () => {
renderWithAuth(<TestComponent />, {
data: {
user: {
name: 'Admin User',
email: 'admin@example.com',
role: 'admin',
permissions: ['content:read', 'content:edit', 'user:manage']
}
},
status: 'authenticated'
});
expect(screen.getByTestId('auth-status')).toHaveTextContent('Authenticated');
expect(screen.getByTestId('admin-role')).toHaveTextContent('Has admin role');
expect(screen.getByTestId('edit-permission')).toHaveTextContent('Can edit content');
});
it('should correctly check for permissions', () => {
renderWithAuth(<TestComponent />, {
data: {
user: {
name: 'Editor User',
email: 'editor@example.com',
role: 'editor',
permissions: ['content:read', 'content:edit']
}
},
status: 'authenticated'
});
expect(screen.getByTestId('auth-status')).toHaveTextContent('Authenticated');
expect(screen.getByTestId('admin-role')).toHaveTextContent('No admin role');
expect(screen.getByTestId('edit-permission')).toHaveTextContent('Can edit content');
});
});Zaawansowane przypadki użycia AuthContext
1. Wykrywanie nieaktywności i automatyczne wylogowywanie
// lib/useIdleTimer.ts
import { useState, useEffect, useCallback } from 'react';
type UseIdleTimerProps = {
timeout: number; // Czas w milisekundach
onIdle: () => void;
onActive?: () => void;
events?: string[];
};
export function useIdleTimer({
timeout,
onIdle,
onActive,
events = ['mousedown', 'mousemove', 'keypress', 'scroll', 'touchstart']
}: UseIdleTimerProps) {
const [isIdle, setIsIdle] = useState(false);
const [lastActive, setLastActive] = useState(Date.now());
const [timeoutId, setTimeoutId] = useState<NodeJS.Timeout | null>(null);
// Resetuj timer nieaktywności
const resetTimer = useCallback(() => {
if (isIdle) {
setIsIdle(false);
onActive?.();
}
setLastActive(Date.now());
if (timeoutId) {
clearTimeout(timeoutId);
}
const id = setTimeout(() => {
setIsIdle(true);
onIdle();
}, timeout);
setTimeoutId(id);
}, [isIdle, onActive, onIdle, timeout, timeoutId]);
// Inicjalizacja timera przy montowaniu
useEffect(() => {
resetTimer();
// Dodaj nasłuchiwanie zdarzeń
events.forEach(event => {
window.addEventListener(event, resetTimer);
});
// Wyczyść przy odmontowaniu
return () => {
if (timeoutId) {
clearTimeout(timeoutId);
}
events.forEach(event => {
window.removeEventListener(event, resetTimer);
});
};
}, [events, resetTimer, timeoutId]);
return {
isIdle,
lastActive,
resetTimer
};
}
// Rozszerzenie AuthProvider o obsługę automatycznego wylogowywania
export function AuthProvider({ children }: AuthProviderProps) {
// ... istniejący kod
// Czas bezczynności: 30 minut
const idleTimeout = 30 * 60 * 1000;
const [showIdleWarning, setShowIdleWarning] = useState(false);
// Obsługa wylogowania po czasie nieaktywności
const handleIdle = () => {
// Pokaż ostrzeżenie o zbliżającym się wylogowaniu
setShowIdleWarning(true);
// Daj użytkownikowi 1 minutę na reakcję, zanim zostanie wylogowany
setTimeout(() => {
if (showIdleWarning) {
handleSignOut({ callbackUrl: '/' });
}
}, 60 * 1000);
};
// Obsługa powrotu do aktywności
const handleActive = () => {
setShowIdleWarning(false);
};
// Użyj hooka idle timer
useIdleTimer({
timeout: idleTimeout,
onIdle: handleIdle,
onActive: handleActive
});
// ... istniejący kod
// Dodaj modal ostrzeżenia o nieaktywności
return (
<AuthContext.Provider value={value}>
{children}
{/* Modal ostrzeżenia o nieaktywności */}
{showIdleWarning && (
<div className="fixed inset-0 flex items-center justify-center bg-black/50 z-50">
<div className="bg-white p-6 rounded-lg shadow-lg max-w-md">
<h2 className="text-xl font-bold mb-4">Wykryto bezczynność</h2>
<p className="mb-4">Zostaniesz automatycznie wylogowany za 1 minutę z powodu braku aktywności.</p>
<div className="flex justify-end space-x-4">
<button
onClick={() => handleSignOut({ callbackUrl: '/' })}
className="px-4 py-2 bg-gray-300 rounded hover:bg-gray-400"
>
Wyloguj teraz
</button>
<button
onClick={handleActive}
className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
>
Pozostań zalogowany
</button>
</div>
</div>
</div>
)}
</AuthContext.Provider>
);
}2. Wdrażanie mechanizmu delegacji dostępu (token swapping)
// lib/delegatedAuth.ts
import { useAuth } from './authContext';
import { useState } from 'react';
type DelegatedToken = {
token: string;
expiresAt: number;
service: string;
};
export function useDelegatedAuth() {
const { isAuthenticated } = useAuth();
const [delegatedTokens, setDelegatedTokens] = useState<Record<string, DelegatedToken>>({});
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
// Pozyskaj token dla usługi zewnętrznej
const getDelegatedToken = async (service: string): Promise<string | null> => {
// Jeśli użytkownik nie jest zalogowany, nie można pozyskać tokenu
if (!isAuthenticated) {
setError('Musisz być zalogowany, aby uzyskać dostęp do usługi zewnętrznej');
return null;
}
// Sprawdź, czy mamy ważny token w cache
const cachedToken = delegatedTokens[service];
if (cachedToken && cachedToken.expiresAt > Date.now()) {
return cachedToken.token;
}
// Pozyskaj nowy token
setIsLoading(true);
setError(null);
try {
const response = await fetch(`/api/auth/delegate/${service}`, {
method: 'POST',
});
if (!response.ok) {
const data = await response.json();
throw new Error(data.message || 'Błąd podczas pozyskiwania tokenu dostępu');
}
const { token, expiresIn } = await response.json();
const expiresAt = Date.now() + expiresIn * 1000;
// Zapisz token w cache
const newToken = { token, expiresAt, service };
setDelegatedTokens(prev => ({ ...prev, [service]: newToken }));
return token;
} catch (err) {
setError(err instanceof Error ? err.message : 'Wystąpił nieznany błąd');
return null;
} finally {
setIsLoading(false);
}
};
// Wyczyść wszystkie tokeny delegowane
const clearDelegatedTokens = () => {
setDelegatedTokens({});
};
return {
getDelegatedToken,
clearDelegatedTokens,
isLoading,
error,
};
}
// Przykład użycia w komponencie
// components/ExternalServiceWidget.tsx
'use client';
import { useDelegatedAuth } from '@/lib/delegatedAuth';
import { useState, useEffect } from 'react';
export function ExternalServiceWidget() {
const { getDelegatedToken, isLoading, error } = useDelegatedAuth();
const [data, setData] = useState(null);
const fetchData = async () => {
// Pozyskaj token dla usługi zewnętrznej
const token = await getDelegatedToken('external-api');
if (!token) return;
try {
// Użyj tokenu do wywołania API zewnętrznej usługi
const response = await fetch('https://api.external-service.com/data', {
headers: {
Authorization: `Bearer ${token}`
}
});
const result = await response.json();
setData(result);
} catch (err) {
console.error('Error fetching from external service:', err);
}
};
useEffect(() => {
fetchData();
}, []);
return (
<div className="bg-white p-4 rounded shadow">
<h2 className="text-lg font-bold mb-2">Dane z usługi zewnętrznej</h2>
{isLoading && <p>Ładowanie danych...</p>}
{error && <p className="text-red-600">{error}</p>}
{data && (
<div className="mt-2">
{/* Wyświetl dane */}
</div>
)}
<button
onClick={fetchData}
disabled={isLoading}
className="mt-4 px-4 py-2 bg-blue-600 text-white rounded disabled:opacity-50"
>
Odśwież dane
</button>
</div>
);
}Bezpieczeństwo kontekstu uwierzytelniania
Przy implementacji AuthContext należy pamiętać o kilku kluczowych aspektach bezpieczeństwa:
Nie przechowuj wrażliwych danych w stanie - unikaj przechowywania haseł, pełnych tokenów JWT czy kluczy API w kontekście dostępnym po stronie klienta.
Waliduj dane po stronie serwera - zawsze weryfikuj uprawnienia użytkownika na serwerze, nigdy nie polegaj wyłącznie na walidacji po stronie klienta.
Używaj HTTPS - wszystkie żądania związane z uwierzytelnianiem muszą być przesyłane przez HTTPS.
Obsługuj tokeny bezpiecznie - przechowuj tokeny w httpOnly cookies, nie w localStorage czy sessionStorage.
Implementuj CSRF protection - używaj tokenów CSRF do ochrony przed atakami Cross-Site Request Forgery.
Unikaj wycieków informacji - nie ujawniaj szczegółowych informacji o błędach uwierzytelniania, które mogłyby pomóc atakującym.
Regularnie odświeżaj i rotuj tokeny - implementuj mechanizmy odświeżania i rotacji tokenów.
Podsumowanie
W tym module omówiliśmy projektowanie i implementację Context Providera dla uwierzytelniania w aplikacjach Next.js, a w szczególności:
- Tworzenie AuthContext i AuthProvider - centralizacja logiki uwierzytelniania w jednym miejscu
- Integracja z NextAuth.js - wykorzystanie istniejących mechanizmów uwierzytelniania
- Rozszerzanie o dodatkowe funkcjonalności - rejestracja, zarządzanie profilem, 2FA
- Wyspecjalizowane providery - obsługa konkretnych przypadków użycia, jak resetowanie hasła
- Komponenty wysokiego poziomu (HOC) - ochrona stron na podstawie ról i uprawnień
- Integracja z systemami zarządzania stanem - łączenie z Zustand i innymi bibliotekami
- Testowanie - pisanie testów dla AuthContext
- Zaawansowane przypadki użycia - automatyczne wylogowywanie i delegacja dostępu
Dobrze zaprojektowany Context Provider dla uwierzytelniania znacząco upraszcza zarządzanie stanem uwierzytelniania w całej aplikacji, centralizuje logikę i zapewnia spójny interfejs do korzystania z funkcji związanych z bezpieczeństwem.
W kolejnym module przyjrzymy się aspektom bezpieczeństwa aplikacji i najlepszym praktykom OWASP, które pomogą nam stworzyć bardziej bezpieczne i odporne na ataki aplikacje Next.js.
Kod do tej lekcji: App.tsx
import React, { useState, createContext, useContext, ReactNode } from 'react';
// Demo: Context Provider dla autentykacji
interface User { id: string; name: string; email: string; role: 'admin' | 'user'; }
interface AuthContextType {
user: User | null;
isAuthenticated: boolean;
isLoading: boolean;
login: (email: string) => void;
logout: () => void;
}
const AuthContext = createContext<AuthContextType | undefined>(undefined);
function useAuth(): AuthContextType {
const ctx = useContext(AuthContext);
if (!ctx) throw new Error('useAuth must be used within AuthProvider');
return ctx;
}
const mockUsers: Record<string, User> = {
'admin@quantum.city': { id: '1', name: 'Admin', email: 'admin@quantum.city', role: 'admin' },
'user@quantum.city': { id: '2', name: 'Uzytkownik', email: 'user@quantum.city', role: 'user' },
};
function AuthProvider({ children }: { children: ReactNode }) {
const [user, setUser] = useState<User | null>(null);
const [isLoading, setIsLoading] = useState(false);
const login = async (email: string) => {
setIsLoading(true);
await new Promise(r => setTimeout(r, 600));
setUser(mockUsers[email] || null);
setIsLoading(false);
};
return (
<AuthContext.Provider value={{ user, isAuthenticated: !!user, isLoading, login, logout: () => setUser(null) }}>
{children}
</AuthContext.Provider>
);
}
function Navbar() {
const { user, isAuthenticated, logout } = useAuth();
return (
<nav style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 20px', background: '#1a1a2e', borderRadius: '8px', marginBottom: '20px' }}>
<span style={{ color: '#64ffda', fontWeight: 'bold' }}>QuantumAuth</span>
{isAuthenticated ? (
<div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
<span>{user?.name} ({user?.role})</span>
<button onClick={logout} style={{ padding: '6px 12px', borderRadius: '6px', background: '#ef4444', color: '#fff', border: 'none', cursor: 'pointer', fontSize: '12px' }}>Wyloguj</button>
</div>
) : <span style={{ color: '#8892b0' }}>Niezalogowany</span>}
</nav>
);
}
function LoginForm() {
const { login, isLoading, isAuthenticated } = useAuth();
const [email, setEmail] = useState('');
if (isAuthenticated) return null;
return (
<div style={{ background: '#1a1a2e', padding: '24px', borderRadius: '12px', border: '1px solid #333', maxWidth: '400px', margin: '0 auto' }}>
<h3 style={{ color: '#64ffda', marginTop: 0 }}>Logowanie</h3>
<input value={email} onChange={e => setEmail(e.target.value)} placeholder="Email" style={{ width: '100%', padding: '10px', borderRadius: '6px', background: '#0f0f23', color: '#fff', border: '1px solid #333', marginBottom: '12px', boxSizing: 'border-box' }} />
<button onClick={() => login(email)} disabled={isLoading} style={{ width: '100%', padding: '10px', borderRadius: '6px', background: '#64ffda', color: '#0f0f23', border: 'none', cursor: 'pointer', fontWeight: 'bold' }}>
{isLoading ? 'Logowanie...' : 'Zaloguj sie'}
</button>
<div style={{ marginTop: '12px', fontSize: '12px', color: '#8892b0' }}>
{Object.keys(mockUsers).map(e => (
<button key={e} onClick={() => { setEmail(e); login(e); }} style={{ display: 'block', background: 'none', border: 'none', color: '#64ffda', cursor: 'pointer', padding: '2px 0', fontSize: '12px' }}>{e}</button>
))}
</div>
</div>
);
}
function ProtectedContent() {
const { isAuthenticated, user } = useAuth();
if (!isAuthenticated) return <p style={{ textAlign: 'center', color: '#555' }}>Zaloguj sie</p>;
return (
<div style={{ background: '#1a1a2e', padding: '24px', borderRadius: '12px', border: '1px solid #10b981', marginTop: '20px' }}>
<h3 style={{ color: '#10b981', marginTop: 0 }}>Chroniona tresc</h3>
<p>Witaj, {user?.name}! Rola: {user?.role}</p>
{user?.role === 'admin' && (
<div style={{ padding: '12px', background: '#ef444420', borderRadius: '8px', border: '1px solid #ef4444', marginTop: '12px' }}>
<strong style={{ color: '#ef4444' }}>Panel Admin</strong>
<p style={{ fontSize: '14px', margin: '4px 0 0' }}>Widoczny tylko dla admina</p>
</div>
)}
</div>
);
}
function App() {
return (
<AuthProvider>
<div style={{ background: '#0f0f23', minHeight: '100vh', padding: '20px', color: '#e0e0e0', fontFamily: 'system-ui' }}>
<h1 style={{ color: '#64ffda', marginBottom: '20px' }}>Auth Context Provider</h1>
<Navbar />
<LoginForm />
<ProtectedContent />
<div style={{ marginTop: '24px', background: '#1a1a2e', padding: '16px', borderRadius: '8px', border: '1px solid #333' }}>
<h4 style={{ color: '#f59e0b', margin: '0 0 8px' }}>Struktura:</h4>
<pre style={{ fontSize: '12px', color: '#8892b0', margin: 0 }}>{'<AuthProvider>\n <Navbar /> // useAuth() -> user, logout\n <LoginForm /> // useAuth() -> login\n <Protected /> // useAuth() -> isAuthenticated\n</AuthProvider>'}</pre>
</div>
</div>
</AuthProvider>
);
}
export default App;Hasła z dokumentacji w tej lekcji
Widzisz błąd w tej lekcji?
Sprawdź się
Odpowiedz na pytania z tej lekcji. Wybierz odpowiedź, a od razu zobaczysz, czy jest poprawna.
1. Dlaczego w Next.js tworzy się osobny AuthProvider jako Client Component opakowujący aplikację?