feat: integrate NextAuth for authentication, refactor login and registration processes, and enhance middleware for session management
This commit is contained in:
@@ -2,9 +2,7 @@
|
||||
|
||||
import { useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { authService } from "@/lib/services/auth.service";
|
||||
import type { AppErrorType } from "@/types/global";
|
||||
import { ErrorMessage } from "@/components/ui/ErrorMessage";
|
||||
import { signIn } from "next-auth/react";
|
||||
import { useTranslate } from "@/hooks/useTranslate";
|
||||
|
||||
interface LoginFormProps {
|
||||
@@ -14,7 +12,7 @@ interface LoginFormProps {
|
||||
export function LoginForm({ from }: LoginFormProps) {
|
||||
const router = useRouter();
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<AppErrorType | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const { t } = useTranslate();
|
||||
|
||||
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
|
||||
@@ -28,11 +26,21 @@ export function LoginForm({ from }: LoginFormProps) {
|
||||
const remember = formData.get("remember") === "on";
|
||||
|
||||
try {
|
||||
await authService.login(email, password, remember);
|
||||
router.push(from || "/");
|
||||
router.refresh();
|
||||
} catch (error) {
|
||||
setError(error as AppErrorType);
|
||||
const result = await signIn("credentials", {
|
||||
email,
|
||||
password,
|
||||
remember,
|
||||
redirect: false,
|
||||
});
|
||||
|
||||
if (result?.error) {
|
||||
setError("Email ou mot de passe incorrect");
|
||||
} else {
|
||||
router.push(from || "/");
|
||||
router.refresh();
|
||||
}
|
||||
} catch (_error) {
|
||||
setError("Une erreur est survenue lors de la connexion : " + _error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
@@ -89,7 +97,11 @@ export function LoginForm({ from }: LoginFormProps) {
|
||||
{t("login.form.remember")}
|
||||
</label>
|
||||
</div>
|
||||
{error && <ErrorMessage errorCode={error.code} variant="form" />}
|
||||
{error && (
|
||||
<div className="text-red-600 text-sm">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isLoading}
|
||||
|
||||
@@ -2,18 +2,16 @@
|
||||
|
||||
import { useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { authService } from "@/lib/services/auth.service";
|
||||
import type { AppErrorType } from "@/types/global";
|
||||
import { ERROR_CODES } from "@/constants/errorCodes";
|
||||
import { signIn } from "next-auth/react";
|
||||
import { ErrorMessage } from "@/components/ui/ErrorMessage";
|
||||
import { useTranslate } from "@/hooks/useTranslate";
|
||||
import { getErrorMessage } from "@/utils/errors";
|
||||
import type { AppErrorType } from "@/types/global";
|
||||
|
||||
interface RegisterFormProps {
|
||||
from?: string;
|
||||
}
|
||||
|
||||
export function RegisterForm({ from }: RegisterFormProps) {
|
||||
export function RegisterForm({ from: _from }: RegisterFormProps) {
|
||||
const router = useRouter();
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<AppErrorType | null>(null);
|
||||
@@ -31,20 +29,57 @@ export function RegisterForm({ from }: RegisterFormProps) {
|
||||
|
||||
if (password !== confirmPassword) {
|
||||
setError({
|
||||
code: ERROR_CODES.AUTH.PASSWORD_MISMATCH,
|
||||
code: "AUTH_PASSWORD_MISMATCH",
|
||||
name: "Password mismatch",
|
||||
message: getErrorMessage(ERROR_CODES.AUTH.PASSWORD_MISMATCH),
|
||||
message: "Les mots de passe ne correspondent pas",
|
||||
});
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await authService.register(email, password);
|
||||
router.push(from || "/");
|
||||
router.refresh();
|
||||
} catch (error) {
|
||||
setError(error as AppErrorType);
|
||||
// Étape 1: Inscription via l'API
|
||||
const response = await fetch("/api/auth/register", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ email, password }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const data = await response.json();
|
||||
setError(data.error || {
|
||||
code: "AUTH_REGISTRATION_FAILED",
|
||||
name: "Registration failed",
|
||||
message: "Erreur lors de l'inscription",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Étape 2: Connexion automatique via NextAuth
|
||||
const signInResult = await signIn("credentials", {
|
||||
email,
|
||||
password,
|
||||
redirect: false,
|
||||
});
|
||||
|
||||
if (signInResult?.error) {
|
||||
setError({
|
||||
code: "AUTH_INVALID_CREDENTIALS",
|
||||
name: "Login failed",
|
||||
message: "Inscription réussie mais erreur lors de la connexion automatique",
|
||||
});
|
||||
} else {
|
||||
router.push("/");
|
||||
router.refresh();
|
||||
}
|
||||
} catch {
|
||||
setError({
|
||||
code: "AUTH_REGISTRATION_FAILED",
|
||||
name: "Registration failed",
|
||||
message: "Une erreur est survenue lors de l'inscription",
|
||||
});
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import { Home, Library, Settings, LogOut, RefreshCw, Star, Download } from "lucide-react";
|
||||
import { usePathname, useRouter } from "next/navigation";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { authService } from "@/lib/services/auth.service";
|
||||
import { signOut } from "next-auth/react";
|
||||
import { useEffect, useState, useCallback } from "react";
|
||||
import type { KomgaLibrary, KomgaSeries } from "@/types/komga";
|
||||
import { usePreferences } from "@/contexts/PreferencesContext";
|
||||
@@ -118,19 +118,15 @@ export function Sidebar({ isOpen, onClose, initialLibraries, initialFavorites }:
|
||||
|
||||
const handleLogout = async () => {
|
||||
try {
|
||||
await authService.logout();
|
||||
await signOut({ callbackUrl: "/login" });
|
||||
setLibraries([]);
|
||||
setFavorites([]);
|
||||
onClose();
|
||||
router.push("/login");
|
||||
} catch (error) {
|
||||
console.error("Erreur lors de la déconnexion:", error);
|
||||
toast({
|
||||
title: "Erreur",
|
||||
description:
|
||||
error instanceof AppError
|
||||
? error.message
|
||||
: getErrorMessage(ERROR_CODES.AUTH.LOGOUT_ERROR),
|
||||
description: "Une erreur est survenue lors de la déconnexion",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import { SeriesGrid } from "./SeriesGrid";
|
||||
import { Pagination } from "@/components/ui/Pagination";
|
||||
import { useRouter, usePathname, useSearchParams } from "next/navigation";
|
||||
import { useState, useEffect } from "react";
|
||||
import { useState, useEffect, useCallback } from "react";
|
||||
import { Loader2 } from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { KomgaSeries } from "@/types/komga";
|
||||
@@ -27,7 +27,7 @@ export function PaginatedSeriesGrid({
|
||||
series,
|
||||
currentPage,
|
||||
totalPages,
|
||||
totalElements,
|
||||
totalElements: _totalElements,
|
||||
defaultShowOnlyUnread,
|
||||
showOnlyUnread: initialShowOnlyUnread,
|
||||
}: PaginatedSeriesGridProps) {
|
||||
@@ -36,10 +36,10 @@ export function PaginatedSeriesGrid({
|
||||
const searchParams = useSearchParams();
|
||||
const [isChangingPage, setIsChangingPage] = useState(false);
|
||||
const [showOnlyUnread, setShowOnlyUnread] = useState(initialShowOnlyUnread);
|
||||
const { isCompact, itemsPerPage } = useDisplayPreferences();
|
||||
const { isCompact, itemsPerPage: _itemsPerPage } = useDisplayPreferences();
|
||||
const { t } = useTranslate();
|
||||
|
||||
const updateUrlParams = async (
|
||||
const updateUrlParams = useCallback(async (
|
||||
updates: Record<string, string | null>,
|
||||
replace: boolean = false
|
||||
) => {
|
||||
@@ -59,7 +59,7 @@ export function PaginatedSeriesGrid({
|
||||
} else {
|
||||
await router.push(`${pathname}?${params.toString()}`);
|
||||
}
|
||||
};
|
||||
}, [router, pathname, searchParams]);
|
||||
|
||||
// Reset loading state when series change
|
||||
useEffect(() => {
|
||||
@@ -76,7 +76,7 @@ export function PaginatedSeriesGrid({
|
||||
if (defaultShowOnlyUnread && !searchParams.has("unread")) {
|
||||
updateUrlParams({ page: "1", unread: "true" }, true);
|
||||
}
|
||||
}, [defaultShowOnlyUnread, pathname, router, searchParams]);
|
||||
}, [defaultShowOnlyUnread, pathname, router, searchParams, updateUrlParams]);
|
||||
|
||||
const handlePageChange = async (page: number) => {
|
||||
await updateUrlParams({ page: page.toString() });
|
||||
|
||||
12
src/components/providers/AuthProvider.tsx
Normal file
12
src/components/providers/AuthProvider.tsx
Normal file
@@ -0,0 +1,12 @@
|
||||
"use client";
|
||||
|
||||
import { SessionProvider } from "next-auth/react";
|
||||
import { ReactNode } from "react";
|
||||
|
||||
interface AuthProviderProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export function AuthProvider({ children }: AuthProviderProps) {
|
||||
return <SessionProvider>{children}</SessionProvider>;
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
import { TransformWrapper, TransformComponent } from "react-zoom-pan-pinch";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useState } from "react";
|
||||
|
||||
interface ZoomablePageProps {
|
||||
pageUrl: string | null;
|
||||
@@ -23,10 +22,7 @@ export const ZoomablePage = ({
|
||||
order = "first",
|
||||
onZoomChange,
|
||||
}: ZoomablePageProps) => {
|
||||
const [currentScale, setCurrentScale] = useState(1);
|
||||
|
||||
const handleTransform = (ref: any, state: { scale: number; positionX: number; positionY: number }) => {
|
||||
setCurrentScale(state.scale);
|
||||
onZoomChange?.(state.scale > 1.1);
|
||||
};
|
||||
return (
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import { BookGrid } from "./BookGrid";
|
||||
import { Pagination } from "@/components/ui/Pagination";
|
||||
import { useRouter, usePathname, useSearchParams } from "next/navigation";
|
||||
import { useState, useEffect } from "react";
|
||||
import { useState, useEffect, useCallback } from "react";
|
||||
import { Loader2 } from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { KomgaBook } from "@/types/komga";
|
||||
@@ -38,7 +38,7 @@ export function PaginatedBookGrid({
|
||||
const { isCompact, itemsPerPage } = useDisplayPreferences();
|
||||
const { t } = useTranslate();
|
||||
|
||||
const updateUrlParams = async (
|
||||
const updateUrlParams = useCallback(async (
|
||||
updates: Record<string, string | null>,
|
||||
replace: boolean = false
|
||||
) => {
|
||||
@@ -58,7 +58,7 @@ export function PaginatedBookGrid({
|
||||
} else {
|
||||
await router.push(`${pathname}?${params.toString()}`);
|
||||
}
|
||||
};
|
||||
}, [router, pathname, searchParams]);
|
||||
|
||||
// Reset loading state when books change
|
||||
useEffect(() => {
|
||||
@@ -75,7 +75,7 @@ export function PaginatedBookGrid({
|
||||
if (defaultShowOnlyUnread && !searchParams.has("unread")) {
|
||||
updateUrlParams({ page: "1", unread: "true" }, true);
|
||||
}
|
||||
}, [defaultShowOnlyUnread, pathname, router, searchParams]);
|
||||
}, [defaultShowOnlyUnread, pathname, router, searchParams, updateUrlParams]);
|
||||
|
||||
const handlePageChange = async (page: number) => {
|
||||
await updateUrlParams({ page: page.toString() });
|
||||
|
||||
Reference in New Issue
Block a user