feat: integrate authentication and password management features, including bcrypt for hashing and NextAuth for session handling
This commit is contained in:
1
.gitignore
vendored
1
.gitignore
vendored
@@ -20,6 +20,7 @@ dist
|
|||||||
prisma/*.db
|
prisma/*.db
|
||||||
prisma/*.db-journal
|
prisma/*.db-journal
|
||||||
prisma/backups
|
prisma/backups
|
||||||
|
prisma/password.json
|
||||||
|
|
||||||
# Debug
|
# Debug
|
||||||
npm-debug.log*
|
npm-debug.log*
|
||||||
|
|||||||
103
README.md
103
README.md
@@ -23,6 +23,9 @@ Application web moderne de gestion personnelle de comptes bancaires avec import
|
|||||||
- **Graphiques** : Recharts
|
- **Graphiques** : Recharts
|
||||||
- **Formulaires** : React Hook Form + Zod
|
- **Formulaires** : React Hook Form + Zod
|
||||||
- **Thème** : next-themes
|
- **Thème** : next-themes
|
||||||
|
- **Base de données** : Prisma + SQLite
|
||||||
|
- **Authentification** : NextAuth.js v4
|
||||||
|
- **Hashing** : bcryptjs
|
||||||
|
|
||||||
## 📋 Prérequis
|
## 📋 Prérequis
|
||||||
|
|
||||||
@@ -44,13 +47,57 @@ cd bank-account-management-app
|
|||||||
pnpm install
|
pnpm install
|
||||||
```
|
```
|
||||||
|
|
||||||
3. Lancez le serveur de développement :
|
3. Configurez les variables d'environnement :
|
||||||
|
|
||||||
|
Créez un fichier `.env.local` à la racine du projet :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# NextAuth Configuration
|
||||||
|
NEXTAUTH_URL=http://localhost:3000
|
||||||
|
NEXTAUTH_SECRET=votre-secret-genere-ici
|
||||||
|
|
||||||
|
# Database
|
||||||
|
DATABASE_URL="file:./prisma/dev.db"
|
||||||
|
```
|
||||||
|
|
||||||
|
**Génération d'un secret sécurisé** :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
openssl rand -base64 32
|
||||||
|
```
|
||||||
|
|
||||||
|
Ou en Node.js :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"
|
||||||
|
```
|
||||||
|
|
||||||
|
4. Initialisez la base de données :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pnpm prisma db push
|
||||||
|
pnpm prisma generate
|
||||||
|
```
|
||||||
|
|
||||||
|
5. Créez le fichier de mot de passe initial :
|
||||||
|
|
||||||
|
Le fichier `prisma/password.json` sera créé automatiquement au premier lancement avec le mot de passe par défaut `admin`. Vous pouvez aussi le créer manuellement :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
node -e "const bcrypt = require('bcryptjs'); bcrypt.hash('admin', 10).then(hash => { const data = { hash, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() }; require('fs').promises.writeFile('prisma/password.json', JSON.stringify(data, null, 2)).then(() => console.log('✅ password.json created')); });"
|
||||||
|
```
|
||||||
|
|
||||||
|
6. Lancez le serveur de développement :
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
pnpm dev
|
pnpm dev
|
||||||
```
|
```
|
||||||
|
|
||||||
4. Ouvrez [http://localhost:3000](http://localhost:3000) dans votre navigateur
|
7. Ouvrez [http://localhost:3000](http://localhost:3000) dans votre navigateur
|
||||||
|
|
||||||
|
8. Connectez-vous avec le mot de passe par défaut : `admin`
|
||||||
|
|
||||||
|
**⚠️ Important** : Changez le mot de passe par défaut dès la première connexion dans les paramètres !
|
||||||
|
|
||||||
## 📦 Scripts disponibles
|
## 📦 Scripts disponibles
|
||||||
|
|
||||||
@@ -58,6 +105,10 @@ pnpm dev
|
|||||||
- `pnpm build` : Compile l'application pour la production
|
- `pnpm build` : Compile l'application pour la production
|
||||||
- `pnpm start` : Lance le serveur de production
|
- `pnpm start` : Lance le serveur de production
|
||||||
- `pnpm lint` : Vérifie le code avec ESLint
|
- `pnpm lint` : Vérifie le code avec ESLint
|
||||||
|
- `pnpm db:push` : Synchronise le schéma Prisma avec la base de données
|
||||||
|
- `pnpm db:migrate` : Crée une nouvelle migration
|
||||||
|
- `pnpm db:seed` : Exécute le script de seed
|
||||||
|
- `pnpm db:studio` : Ouvre Prisma Studio pour visualiser la base de données
|
||||||
|
|
||||||
## 📁 Structure du projet
|
## 📁 Structure du projet
|
||||||
|
|
||||||
@@ -76,17 +127,45 @@ pnpm dev
|
|||||||
├── lib/ # Utilitaires et logique métier
|
├── lib/ # Utilitaires et logique métier
|
||||||
│ ├── hooks.ts # Hooks personnalisés
|
│ ├── hooks.ts # Hooks personnalisés
|
||||||
│ ├── ofx-parser.tsx # Parser de fichiers OFX
|
│ ├── ofx-parser.tsx # Parser de fichiers OFX
|
||||||
│ ├── store.ts # Gestion du stockage local
|
|
||||||
│ ├── types.ts # Types TypeScript
|
│ ├── types.ts # Types TypeScript
|
||||||
│ └── utils.ts # Fonctions utilitaires
|
│ ├── utils.ts # Fonctions utilitaires
|
||||||
|
│ ├── prisma.ts # Client Prisma
|
||||||
|
│ └── auth.ts # Configuration NextAuth
|
||||||
|
├── services/ # Services métier
|
||||||
|
│ ├── banking.service.ts
|
||||||
|
│ ├── account.service.ts
|
||||||
|
│ ├── category.service.ts
|
||||||
|
│ ├── folder.service.ts
|
||||||
|
│ ├── transaction.service.ts
|
||||||
|
│ ├── backup.service.ts
|
||||||
|
│ └── auth.service.ts
|
||||||
|
├── prisma/ # Base de données
|
||||||
|
│ ├── schema.prisma # Schéma Prisma
|
||||||
|
│ ├── dev.db # Base de données SQLite (non versionné)
|
||||||
|
│ ├── password.json # Hash du mot de passe (non versionné)
|
||||||
|
│ └── backups/ # Sauvegardes automatiques (non versionné)
|
||||||
└── public/ # Assets statiques
|
└── public/ # Assets statiques
|
||||||
```
|
```
|
||||||
|
|
||||||
## 💾 Stockage des données
|
## 💾 Stockage des données
|
||||||
|
|
||||||
L'application utilise `localStorage` pour stocker toutes les données localement dans le navigateur. Les données sont sauvegardées automatiquement à chaque modification.
|
L'application utilise **Prisma** avec **SQLite** pour stocker toutes les données dans un fichier local (`prisma/dev.db`). Les données sont sauvegardées automatiquement à chaque modification.
|
||||||
|
|
||||||
**Note** : Les données sont stockées uniquement dans votre navigateur. Si vous supprimez les données du navigateur ou changez d'appareil, vous devrez réimporter vos fichiers OFX.
|
### Base de données
|
||||||
|
|
||||||
|
- **Fichier** : `prisma/dev.db` (SQLite)
|
||||||
|
- **Schéma** : Défini dans `prisma/schema.prisma`
|
||||||
|
- **Migrations** : Gérées avec Prisma Migrate
|
||||||
|
|
||||||
|
### Authentification
|
||||||
|
|
||||||
|
L'application est protégée par un **mot de passe global** stocké dans `prisma/password.json` (hashé avec bcrypt).
|
||||||
|
|
||||||
|
- **Mot de passe par défaut** : `admin` (à changer dès la première connexion)
|
||||||
|
- **Fichier** : `prisma/password.json` (créé automatiquement au premier lancement)
|
||||||
|
- **Changement de mot de passe** : Disponible dans les paramètres
|
||||||
|
|
||||||
|
**Note** : Les fichiers `prisma/password.json` et `prisma/dev.db` sont dans `.gitignore` et ne seront pas versionnés.
|
||||||
|
|
||||||
## 📥 Import de fichiers OFX
|
## 📥 Import de fichiers OFX
|
||||||
|
|
||||||
@@ -120,9 +199,19 @@ Le thème sombre/clair peut être changé dans les paramètres. L'application d
|
|||||||
|
|
||||||
## 🔒 Sécurité et confidentialité
|
## 🔒 Sécurité et confidentialité
|
||||||
|
|
||||||
- **100% local** : Toutes vos données restent dans votre navigateur
|
- **100% local** : Toutes vos données sont stockées localement dans un fichier SQLite
|
||||||
|
- **Authentification** : Protection par mot de passe global (hashé avec bcrypt)
|
||||||
- **Aucune connexion externe** : Aucune donnée n'est envoyée à des serveurs externes
|
- **Aucune connexion externe** : Aucune donnée n'est envoyée à des serveurs externes
|
||||||
- **Pas de tracking** : Aucun service d'analytics tiers (sauf Vercel Analytics optionnel)
|
- **Pas de tracking** : Aucun service d'analytics tiers (sauf Vercel Analytics optionnel)
|
||||||
|
- **Sauvegardes automatiques** : Système de sauvegarde automatique configurable (horaire, quotidienne, hebdomadaire, mensuelle)
|
||||||
|
|
||||||
|
### Variables d'environnement
|
||||||
|
|
||||||
|
Le fichier `.env.local` contient des secrets sensibles et ne doit **jamais** être versionné. En production, configurez ces variables dans votre plateforme de déploiement :
|
||||||
|
|
||||||
|
- `NEXTAUTH_SECRET` : Secret pour signer les tokens JWT (générez un secret sécurisé)
|
||||||
|
- `NEXTAUTH_URL` : URL de base de l'application
|
||||||
|
- `DATABASE_URL` : Chemin vers la base de données SQLite
|
||||||
|
|
||||||
## 🚧 Développement
|
## 🚧 Développement
|
||||||
|
|
||||||
|
|||||||
7
app/api/auth/[...nextauth]/route.ts
Normal file
7
app/api/auth/[...nextauth]/route.ts
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
import NextAuth from "next-auth";
|
||||||
|
import { authOptions } from "@/lib/auth";
|
||||||
|
|
||||||
|
const handler = NextAuth(authOptions);
|
||||||
|
|
||||||
|
export { handler as GET, handler as POST };
|
||||||
|
|
||||||
52
app/api/auth/change-password/route.ts
Normal file
52
app/api/auth/change-password/route.ts
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { getServerSession } from "next-auth";
|
||||||
|
import { authOptions } from "@/lib/auth";
|
||||||
|
import { authService } from "@/services/auth.service";
|
||||||
|
|
||||||
|
export async function POST(request: NextRequest) {
|
||||||
|
try {
|
||||||
|
// Verify user is authenticated
|
||||||
|
const session = await getServerSession(authOptions);
|
||||||
|
if (!session) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ success: false, error: "Non authentifié" },
|
||||||
|
{ status: 401 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const body = await request.json();
|
||||||
|
const { oldPassword, newPassword } = body;
|
||||||
|
|
||||||
|
if (!oldPassword || !newPassword) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ success: false, error: "Mot de passe requis" },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (newPassword.length < 4) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ success: false, error: "Le mot de passe doit contenir au moins 4 caractères" },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await authService.changePassword(oldPassword, newPassword);
|
||||||
|
|
||||||
|
if (!result.success) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ success: false, error: result.error },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.json({ success: true });
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error changing password:", error);
|
||||||
|
return NextResponse.json(
|
||||||
|
{ success: false, error: "Erreur lors du changement de mot de passe" },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -1,10 +1,13 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { backupService } from "@/services/backup.service";
|
import { backupService } from "@/services/backup.service";
|
||||||
|
import { requireAuth } from "@/lib/auth-utils";
|
||||||
|
|
||||||
export async function POST(
|
export async function POST(
|
||||||
request: NextRequest,
|
request: NextRequest,
|
||||||
{ params }: { params: Promise<{ id: string }> | { id: string } }
|
{ params }: { params: Promise<{ id: string }> | { id: string } }
|
||||||
) {
|
) {
|
||||||
|
const authError = await requireAuth();
|
||||||
|
if (authError) return authError;
|
||||||
try {
|
try {
|
||||||
const resolvedParams = params instanceof Promise ? await params : params;
|
const resolvedParams = params instanceof Promise ? await params : params;
|
||||||
await backupService.restoreBackup(resolvedParams.id);
|
await backupService.restoreBackup(resolvedParams.id);
|
||||||
|
|||||||
@@ -1,10 +1,13 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { backupService } from "@/services/backup.service";
|
import { backupService } from "@/services/backup.service";
|
||||||
|
import { requireAuth } from "@/lib/auth-utils";
|
||||||
|
|
||||||
export async function DELETE(
|
export async function DELETE(
|
||||||
request: NextRequest,
|
request: NextRequest,
|
||||||
{ params }: { params: Promise<{ id: string }> | { id: string } }
|
{ params }: { params: Promise<{ id: string }> | { id: string } }
|
||||||
) {
|
) {
|
||||||
|
const authError = await requireAuth();
|
||||||
|
if (authError) return authError;
|
||||||
try {
|
try {
|
||||||
const resolvedParams = params instanceof Promise ? await params : params;
|
const resolvedParams = params instanceof Promise ? await params : params;
|
||||||
await backupService.deleteBackup(resolvedParams.id);
|
await backupService.deleteBackup(resolvedParams.id);
|
||||||
|
|||||||
@@ -1,7 +1,10 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { backupService } from "@/services/backup.service";
|
import { backupService } from "@/services/backup.service";
|
||||||
|
import { requireAuth } from "@/lib/auth-utils";
|
||||||
|
|
||||||
export async function POST(_request: NextRequest) {
|
export async function POST(_request: NextRequest) {
|
||||||
|
const authError = await requireAuth();
|
||||||
|
if (authError) return authError;
|
||||||
try {
|
try {
|
||||||
// Check if automatic backup should run
|
// Check if automatic backup should run
|
||||||
const shouldRun = await backupService.shouldRunAutomaticBackup();
|
const shouldRun = await backupService.shouldRunAutomaticBackup();
|
||||||
|
|||||||
@@ -1,7 +1,11 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { backupService } from "@/services/backup.service";
|
import { backupService } from "@/services/backup.service";
|
||||||
|
import { requireAuth } from "@/lib/auth-utils";
|
||||||
|
|
||||||
export async function GET() {
|
export async function GET() {
|
||||||
|
const authError = await requireAuth();
|
||||||
|
if (authError) return authError;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const backups = await backupService.getAllBackups();
|
const backups = await backupService.getAllBackups();
|
||||||
return NextResponse.json({ success: true, data: backups });
|
return NextResponse.json({ success: true, data: backups });
|
||||||
@@ -15,6 +19,9 @@ export async function GET() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function POST(request: NextRequest) {
|
export async function POST(request: NextRequest) {
|
||||||
|
const authError = await requireAuth();
|
||||||
|
if (authError) return authError;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const body = await request.json().catch(() => ({}));
|
const body = await request.json().catch(() => ({}));
|
||||||
const force = body.force === true; // Only allow force for manual backups
|
const force = body.force === true; // Only allow force for manual backups
|
||||||
|
|||||||
@@ -1,7 +1,10 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { backupService } from "@/services/backup.service";
|
import { backupService } from "@/services/backup.service";
|
||||||
|
import { requireAuth } from "@/lib/auth-utils";
|
||||||
|
|
||||||
export async function GET() {
|
export async function GET() {
|
||||||
|
const authError = await requireAuth();
|
||||||
|
if (authError) return authError;
|
||||||
try {
|
try {
|
||||||
const settings = await backupService.getSettings();
|
const settings = await backupService.getSettings();
|
||||||
return NextResponse.json({ success: true, data: settings });
|
return NextResponse.json({ success: true, data: settings });
|
||||||
@@ -15,6 +18,9 @@ export async function GET() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function PUT(request: NextRequest) {
|
export async function PUT(request: NextRequest) {
|
||||||
|
const authError = await requireAuth();
|
||||||
|
if (authError) return authError;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const body = await request.json();
|
const body = await request.json();
|
||||||
const settings = await backupService.updateSettings(body);
|
const settings = await backupService.updateSettings(body);
|
||||||
|
|||||||
@@ -1,8 +1,12 @@
|
|||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import { accountService } from "@/services/account.service";
|
import { accountService } from "@/services/account.service";
|
||||||
|
import { requireAuth } from "@/lib/auth-utils";
|
||||||
import type { Account } from "@/lib/types";
|
import type { Account } from "@/lib/types";
|
||||||
|
|
||||||
export async function POST(request: Request) {
|
export async function POST(request: Request) {
|
||||||
|
const authError = await requireAuth();
|
||||||
|
if (authError) return authError;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const data: Omit<Account, "id"> = await request.json();
|
const data: Omit<Account, "id"> = await request.json();
|
||||||
const created = await accountService.create(data);
|
const created = await accountService.create(data);
|
||||||
@@ -17,6 +21,9 @@ export async function POST(request: Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function PUT(request: Request) {
|
export async function PUT(request: Request) {
|
||||||
|
const authError = await requireAuth();
|
||||||
|
if (authError) return authError;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const account: Account = await request.json();
|
const account: Account = await request.json();
|
||||||
const updated = await accountService.update(account.id, account);
|
const updated = await accountService.update(account.id, account);
|
||||||
@@ -31,6 +38,9 @@ export async function PUT(request: Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function DELETE(request: Request) {
|
export async function DELETE(request: Request) {
|
||||||
|
const authError = await requireAuth();
|
||||||
|
if (authError) return authError;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const { searchParams } = new URL(request.url);
|
const { searchParams } = new URL(request.url);
|
||||||
const id = searchParams.get("id");
|
const id = searchParams.get("id");
|
||||||
|
|||||||
@@ -1,8 +1,11 @@
|
|||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import { categoryService } from "@/services/category.service";
|
import { categoryService } from "@/services/category.service";
|
||||||
|
import { requireAuth } from "@/lib/auth-utils";
|
||||||
import type { Category } from "@/lib/types";
|
import type { Category } from "@/lib/types";
|
||||||
|
|
||||||
export async function POST(request: Request) {
|
export async function POST(request: Request) {
|
||||||
|
const authError = await requireAuth();
|
||||||
|
if (authError) return authError;
|
||||||
try {
|
try {
|
||||||
const data: Omit<Category, "id"> = await request.json();
|
const data: Omit<Category, "id"> = await request.json();
|
||||||
const created = await categoryService.create(data);
|
const created = await categoryService.create(data);
|
||||||
@@ -17,6 +20,9 @@ export async function POST(request: Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function PUT(request: Request) {
|
export async function PUT(request: Request) {
|
||||||
|
const authError = await requireAuth();
|
||||||
|
if (authError) return authError;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const category: Category = await request.json();
|
const category: Category = await request.json();
|
||||||
const updated = await categoryService.update(category.id, category);
|
const updated = await categoryService.update(category.id, category);
|
||||||
@@ -31,6 +37,9 @@ export async function PUT(request: Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function DELETE(request: Request) {
|
export async function DELETE(request: Request) {
|
||||||
|
const authError = await requireAuth();
|
||||||
|
if (authError) return authError;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const { searchParams } = new URL(request.url);
|
const { searchParams } = new URL(request.url);
|
||||||
const id = searchParams.get("id");
|
const id = searchParams.get("id");
|
||||||
|
|||||||
@@ -1,8 +1,11 @@
|
|||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import { folderService, FolderNotFoundError } from "@/services/folder.service";
|
import { folderService, FolderNotFoundError } from "@/services/folder.service";
|
||||||
|
import { requireAuth } from "@/lib/auth-utils";
|
||||||
import type { Folder } from "@/lib/types";
|
import type { Folder } from "@/lib/types";
|
||||||
|
|
||||||
export async function POST(request: Request) {
|
export async function POST(request: Request) {
|
||||||
|
const authError = await requireAuth();
|
||||||
|
if (authError) return authError;
|
||||||
try {
|
try {
|
||||||
const data: Omit<Folder, "id"> = await request.json();
|
const data: Omit<Folder, "id"> = await request.json();
|
||||||
const created = await folderService.create(data);
|
const created = await folderService.create(data);
|
||||||
@@ -17,6 +20,9 @@ export async function POST(request: Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function PUT(request: Request) {
|
export async function PUT(request: Request) {
|
||||||
|
const authError = await requireAuth();
|
||||||
|
if (authError) return authError;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const folder: Folder = await request.json();
|
const folder: Folder = await request.json();
|
||||||
const updated = await folderService.update(folder.id, folder);
|
const updated = await folderService.update(folder.id, folder);
|
||||||
@@ -31,6 +37,9 @@ export async function PUT(request: Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function DELETE(request: Request) {
|
export async function DELETE(request: Request) {
|
||||||
|
const authError = await requireAuth();
|
||||||
|
if (authError) return authError;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const { searchParams } = new URL(request.url);
|
const { searchParams } = new URL(request.url);
|
||||||
const id = searchParams.get("id");
|
const id = searchParams.get("id");
|
||||||
|
|||||||
@@ -1,7 +1,11 @@
|
|||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import { bankingService } from "@/services/banking.service";
|
import { bankingService } from "@/services/banking.service";
|
||||||
|
import { requireAuth } from "@/lib/auth-utils";
|
||||||
|
|
||||||
export async function GET() {
|
export async function GET() {
|
||||||
|
const authError = await requireAuth();
|
||||||
|
if (authError) return authError;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const data = await bankingService.getAllData();
|
const data = await bankingService.getAllData();
|
||||||
return NextResponse.json(data);
|
return NextResponse.json(data);
|
||||||
|
|||||||
@@ -1,7 +1,10 @@
|
|||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import { prisma } from "@/lib/prisma";
|
import { prisma } from "@/lib/prisma";
|
||||||
|
import { requireAuth } from "@/lib/auth-utils";
|
||||||
|
|
||||||
export async function POST() {
|
export async function POST() {
|
||||||
|
const authError = await requireAuth();
|
||||||
|
if (authError) return authError;
|
||||||
try {
|
try {
|
||||||
const result = await prisma.transaction.updateMany({
|
const result = await prisma.transaction.updateMany({
|
||||||
where: {
|
where: {
|
||||||
|
|||||||
@@ -1,8 +1,11 @@
|
|||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import { transactionService } from "@/services/transaction.service";
|
import { transactionService } from "@/services/transaction.service";
|
||||||
|
import { requireAuth } from "@/lib/auth-utils";
|
||||||
import type { Transaction } from "@/lib/types";
|
import type { Transaction } from "@/lib/types";
|
||||||
|
|
||||||
export async function POST(request: Request) {
|
export async function POST(request: Request) {
|
||||||
|
const authError = await requireAuth();
|
||||||
|
if (authError) return authError;
|
||||||
try {
|
try {
|
||||||
const transactions: Transaction[] = await request.json();
|
const transactions: Transaction[] = await request.json();
|
||||||
const result = await transactionService.createMany(transactions);
|
const result = await transactionService.createMany(transactions);
|
||||||
@@ -17,6 +20,9 @@ export async function POST(request: Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function PUT(request: Request) {
|
export async function PUT(request: Request) {
|
||||||
|
const authError = await requireAuth();
|
||||||
|
if (authError) return authError;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const transaction: Transaction = await request.json();
|
const transaction: Transaction = await request.json();
|
||||||
const updated = await transactionService.update(
|
const updated = await transactionService.update(
|
||||||
@@ -34,6 +40,9 @@ export async function PUT(request: Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function DELETE(request: Request) {
|
export async function DELETE(request: Request) {
|
||||||
|
const authError = await requireAuth();
|
||||||
|
if (authError) return authError;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const { searchParams } = new URL(request.url);
|
const { searchParams } = new URL(request.url);
|
||||||
const id = searchParams.get("id");
|
const id = searchParams.get("id");
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import type React from "react";
|
|||||||
import type { Metadata } from "next";
|
import type { Metadata } from "next";
|
||||||
import { Geist, Geist_Mono } from "next/font/google";
|
import { Geist, Geist_Mono } from "next/font/google";
|
||||||
import "./globals.css";
|
import "./globals.css";
|
||||||
|
import { AuthSessionProvider } from "@/components/providers/session-provider";
|
||||||
|
|
||||||
const _geist = Geist({ subsets: ["latin"] });
|
const _geist = Geist({ subsets: ["latin"] });
|
||||||
const _geistMono = Geist_Mono({ subsets: ["latin"] });
|
const _geistMono = Geist_Mono({ subsets: ["latin"] });
|
||||||
@@ -20,7 +21,9 @@ export default function RootLayout({
|
|||||||
}>) {
|
}>) {
|
||||||
return (
|
return (
|
||||||
<html lang="fr">
|
<html lang="fr">
|
||||||
<body className="font-sans antialiased">{children}</body>
|
<body className="font-sans antialiased">
|
||||||
|
<AuthSessionProvider>{children}</AuthSessionProvider>
|
||||||
|
</body>
|
||||||
</html>
|
</html>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
95
app/login/page.tsx
Normal file
95
app/login/page.tsx
Normal file
@@ -0,0 +1,95 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import { signIn } from "next-auth/react";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { Label } from "@/components/ui/label";
|
||||||
|
import {
|
||||||
|
Card,
|
||||||
|
CardContent,
|
||||||
|
CardDescription,
|
||||||
|
CardHeader,
|
||||||
|
CardTitle,
|
||||||
|
} from "@/components/ui/card";
|
||||||
|
import { Lock } from "lucide-react";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
|
||||||
|
export default function LoginPage() {
|
||||||
|
const [password, setPassword] = useState("");
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const router = useRouter();
|
||||||
|
|
||||||
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setLoading(true);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await signIn("credentials", {
|
||||||
|
password,
|
||||||
|
redirect: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (result?.error) {
|
||||||
|
toast.error("Mot de passe incorrect");
|
||||||
|
setPassword("");
|
||||||
|
} else {
|
||||||
|
toast.success("Connexion réussie");
|
||||||
|
router.push("/");
|
||||||
|
router.refresh();
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
toast.error("Erreur lors de la connexion");
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen flex items-center justify-center bg-[var(--background)] p-4">
|
||||||
|
<Card className="w-full max-w-md">
|
||||||
|
<CardHeader className="space-y-1">
|
||||||
|
<div className="flex items-center justify-center mb-4">
|
||||||
|
<Lock className="w-12 h-12 text-[var(--primary)]" />
|
||||||
|
</div>
|
||||||
|
<CardTitle className="text-2xl text-center">
|
||||||
|
Accès protégé
|
||||||
|
</CardTitle>
|
||||||
|
<CardDescription className="text-center">
|
||||||
|
Entrez le mot de passe pour accéder à l'application
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<form onSubmit={handleSubmit} className="space-y-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="password">Mot de passe</Label>
|
||||||
|
<Input
|
||||||
|
id="password"
|
||||||
|
type="password"
|
||||||
|
value={password}
|
||||||
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
|
placeholder="Entrez le mot de passe"
|
||||||
|
disabled={loading}
|
||||||
|
autoFocus
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === "Enter") {
|
||||||
|
handleSubmit(e);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
type="submit"
|
||||||
|
className="w-full"
|
||||||
|
disabled={loading || !password}
|
||||||
|
>
|
||||||
|
{loading ? "Connexion..." : "Se connecter"}
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
@@ -7,6 +7,7 @@ import {
|
|||||||
DangerZoneCard,
|
DangerZoneCard,
|
||||||
OFXInfoCard,
|
OFXInfoCard,
|
||||||
BackupCard,
|
BackupCard,
|
||||||
|
PasswordCard,
|
||||||
} from "@/components/settings";
|
} from "@/components/settings";
|
||||||
import { useBankingData } from "@/lib/hooks";
|
import { useBankingData } from "@/lib/hooks";
|
||||||
import type { BankingData } from "@/lib/types";
|
import type { BankingData } from "@/lib/types";
|
||||||
@@ -107,6 +108,8 @@ export default function SettingsPage() {
|
|||||||
|
|
||||||
<BackupCard />
|
<BackupCard />
|
||||||
|
|
||||||
|
<PasswordCard />
|
||||||
|
|
||||||
<DangerZoneCard
|
<DangerZoneCard
|
||||||
categorizedCount={categorizedCount}
|
categorizedCount={categorizedCount}
|
||||||
onClearCategories={clearAllCategories}
|
onClearCategories={clearAllCategories}
|
||||||
|
|||||||
@@ -2,7 +2,8 @@
|
|||||||
|
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { usePathname } from "next/navigation";
|
import { usePathname, useRouter } from "next/navigation";
|
||||||
|
import { signOut } from "next-auth/react";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import {
|
import {
|
||||||
@@ -16,7 +17,9 @@ import {
|
|||||||
ChevronRight,
|
ChevronRight,
|
||||||
Settings,
|
Settings,
|
||||||
Wand2,
|
Wand2,
|
||||||
|
LogOut,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
|
||||||
const navItems = [
|
const navItems = [
|
||||||
{ href: "/", label: "Tableau de bord", icon: LayoutDashboard },
|
{ href: "/", label: "Tableau de bord", icon: LayoutDashboard },
|
||||||
@@ -30,8 +33,21 @@ const navItems = [
|
|||||||
|
|
||||||
export function Sidebar() {
|
export function Sidebar() {
|
||||||
const pathname = usePathname();
|
const pathname = usePathname();
|
||||||
|
const router = useRouter();
|
||||||
const [collapsed, setCollapsed] = useState(false);
|
const [collapsed, setCollapsed] = useState(false);
|
||||||
|
|
||||||
|
const handleSignOut = async () => {
|
||||||
|
try {
|
||||||
|
await signOut({ redirect: false });
|
||||||
|
toast.success("Déconnexion réussie");
|
||||||
|
router.push("/login");
|
||||||
|
router.refresh();
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error signing out:", error);
|
||||||
|
toast.error("Erreur lors de la déconnexion");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<aside
|
<aside
|
||||||
className={cn(
|
className={cn(
|
||||||
@@ -82,7 +98,7 @@ export function Sidebar() {
|
|||||||
})}
|
})}
|
||||||
</nav>
|
</nav>
|
||||||
|
|
||||||
<div className="p-2 border-t border-border">
|
<div className="p-2 border-t border-border space-y-1">
|
||||||
<Link href="/settings">
|
<Link href="/settings">
|
||||||
<Button
|
<Button
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
@@ -95,6 +111,17 @@ export function Sidebar() {
|
|||||||
{!collapsed && <span>Paramètres</span>}
|
{!collapsed && <span>Paramètres</span>}
|
||||||
</Button>
|
</Button>
|
||||||
</Link>
|
</Link>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
onClick={handleSignOut}
|
||||||
|
className={cn(
|
||||||
|
"w-full justify-start gap-3 text-destructive hover:text-destructive hover:bg-destructive/10",
|
||||||
|
collapsed && "justify-center px-2",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<LogOut className="w-5 h-5 shrink-0" />
|
||||||
|
{!collapsed && <span>Déconnexion</span>}
|
||||||
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</aside>
|
</aside>
|
||||||
);
|
);
|
||||||
|
|||||||
9
components/providers/session-provider.tsx
Normal file
9
components/providers/session-provider.tsx
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { SessionProvider } from "next-auth/react";
|
||||||
|
import type { ReactNode } from "react";
|
||||||
|
|
||||||
|
export function AuthSessionProvider({ children }: { children: ReactNode }) {
|
||||||
|
return <SessionProvider>{children}</SessionProvider>;
|
||||||
|
}
|
||||||
|
|
||||||
@@ -2,4 +2,5 @@ export { DataCard } from "./data-card";
|
|||||||
export { DangerZoneCard } from "./danger-zone-card";
|
export { DangerZoneCard } from "./danger-zone-card";
|
||||||
export { OFXInfoCard } from "./ofx-info-card";
|
export { OFXInfoCard } from "./ofx-info-card";
|
||||||
export { BackupCard } from "./backup-card";
|
export { BackupCard } from "./backup-card";
|
||||||
|
export { PasswordCard } from "./password-card";
|
||||||
|
|
||||||
|
|||||||
202
components/settings/password-card.tsx
Normal file
202
components/settings/password-card.tsx
Normal file
@@ -0,0 +1,202 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import {
|
||||||
|
Card,
|
||||||
|
CardContent,
|
||||||
|
CardDescription,
|
||||||
|
CardHeader,
|
||||||
|
CardTitle,
|
||||||
|
} from "@/components/ui/card";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { Label } from "@/components/ui/label";
|
||||||
|
import {
|
||||||
|
AlertDialog,
|
||||||
|
AlertDialogAction,
|
||||||
|
AlertDialogCancel,
|
||||||
|
AlertDialogContent,
|
||||||
|
AlertDialogDescription,
|
||||||
|
AlertDialogFooter,
|
||||||
|
AlertDialogHeader,
|
||||||
|
AlertDialogTitle,
|
||||||
|
AlertDialogTrigger,
|
||||||
|
} from "@/components/ui/alert-dialog";
|
||||||
|
import { Lock, Eye, EyeOff } from "lucide-react";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
|
||||||
|
export function PasswordCard() {
|
||||||
|
const [oldPassword, setOldPassword] = useState("");
|
||||||
|
const [newPassword, setNewPassword] = useState("");
|
||||||
|
const [confirmPassword, setConfirmPassword] = useState("");
|
||||||
|
const [showOldPassword, setShowOldPassword] = useState(false);
|
||||||
|
const [showNewPassword, setShowNewPassword] = useState(false);
|
||||||
|
const [showConfirmPassword, setShowConfirmPassword] = useState(false);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
|
||||||
|
const handleChangePassword = async () => {
|
||||||
|
if (!oldPassword || !newPassword || !confirmPassword) {
|
||||||
|
toast.error("Veuillez remplir tous les champs");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (newPassword.length < 4) {
|
||||||
|
toast.error("Le mot de passe doit contenir au moins 4 caractères");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (newPassword !== confirmPassword) {
|
||||||
|
toast.error("Les mots de passe ne correspondent pas");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setLoading(true);
|
||||||
|
try {
|
||||||
|
const response = await fetch("/api/auth/change-password", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({
|
||||||
|
oldPassword,
|
||||||
|
newPassword,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
if (data.success) {
|
||||||
|
toast.success("Mot de passe modifié avec succès");
|
||||||
|
setOldPassword("");
|
||||||
|
setNewPassword("");
|
||||||
|
setConfirmPassword("");
|
||||||
|
setOpen(false);
|
||||||
|
} else {
|
||||||
|
toast.error(data.error || "Erreur lors du changement de mot de passe");
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error changing password:", error);
|
||||||
|
toast.error("Erreur lors du changement de mot de passe");
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className="flex items-center gap-2">
|
||||||
|
<Lock className="w-5 h-5" />
|
||||||
|
Mot de passe
|
||||||
|
</CardTitle>
|
||||||
|
<CardDescription>
|
||||||
|
Modifiez le mot de passe d'accès à l'application
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<AlertDialog open={open} onOpenChange={setOpen}>
|
||||||
|
<AlertDialogTrigger asChild>
|
||||||
|
<Button variant="outline">Changer le mot de passe</Button>
|
||||||
|
</AlertDialogTrigger>
|
||||||
|
<AlertDialogContent className="sm:max-w-md">
|
||||||
|
<AlertDialogHeader>
|
||||||
|
<AlertDialogTitle>Changer le mot de passe</AlertDialogTitle>
|
||||||
|
<AlertDialogDescription>
|
||||||
|
Entrez votre mot de passe actuel et le nouveau mot de passe.
|
||||||
|
</AlertDialogDescription>
|
||||||
|
</AlertDialogHeader>
|
||||||
|
<div className="space-y-4 py-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="old-password">Mot de passe actuel</Label>
|
||||||
|
<div className="relative">
|
||||||
|
<Input
|
||||||
|
id="old-password"
|
||||||
|
type={showOldPassword ? "text" : "password"}
|
||||||
|
value={oldPassword}
|
||||||
|
onChange={(e) => setOldPassword(e.target.value)}
|
||||||
|
placeholder="Mot de passe actuel"
|
||||||
|
disabled={loading}
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
|
||||||
|
onClick={() => setShowOldPassword(!showOldPassword)}
|
||||||
|
>
|
||||||
|
{showOldPassword ? (
|
||||||
|
<EyeOff className="h-4 w-4" />
|
||||||
|
) : (
|
||||||
|
<Eye className="h-4 w-4" />
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="new-password">Nouveau mot de passe</Label>
|
||||||
|
<div className="relative">
|
||||||
|
<Input
|
||||||
|
id="new-password"
|
||||||
|
type={showNewPassword ? "text" : "password"}
|
||||||
|
value={newPassword}
|
||||||
|
onChange={(e) => setNewPassword(e.target.value)}
|
||||||
|
placeholder="Nouveau mot de passe"
|
||||||
|
disabled={loading}
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
|
||||||
|
onClick={() => setShowNewPassword(!showNewPassword)}
|
||||||
|
>
|
||||||
|
{showNewPassword ? (
|
||||||
|
<EyeOff className="h-4 w-4" />
|
||||||
|
) : (
|
||||||
|
<Eye className="h-4 w-4" />
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="confirm-password">Confirmer le mot de passe</Label>
|
||||||
|
<div className="relative">
|
||||||
|
<Input
|
||||||
|
id="confirm-password"
|
||||||
|
type={showConfirmPassword ? "text" : "password"}
|
||||||
|
value={confirmPassword}
|
||||||
|
onChange={(e) => setConfirmPassword(e.target.value)}
|
||||||
|
placeholder="Confirmer le mot de passe"
|
||||||
|
disabled={loading}
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
|
||||||
|
onClick={() => setShowConfirmPassword(!showConfirmPassword)}
|
||||||
|
>
|
||||||
|
{showConfirmPassword ? (
|
||||||
|
<EyeOff className="h-4 w-4" />
|
||||||
|
) : (
|
||||||
|
<Eye className="h-4 w-4" />
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<AlertDialogFooter>
|
||||||
|
<AlertDialogCancel disabled={loading}>Annuler</AlertDialogCancel>
|
||||||
|
<AlertDialogAction
|
||||||
|
onClick={handleChangePassword}
|
||||||
|
disabled={loading}
|
||||||
|
>
|
||||||
|
{loading ? "Modification..." : "Modifier"}
|
||||||
|
</AlertDialogAction>
|
||||||
|
</AlertDialogFooter>
|
||||||
|
</AlertDialogContent>
|
||||||
|
</AlertDialog>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
21
lib/auth-utils.ts
Normal file
21
lib/auth-utils.ts
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
import { getServerSession } from "next-auth";
|
||||||
|
import { authOptions } from "@/lib/auth";
|
||||||
|
import { NextResponse } from "next/server";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verify that the user is authenticated
|
||||||
|
* Returns null if authenticated, or a NextResponse with 401 if not
|
||||||
|
*/
|
||||||
|
export async function requireAuth(): Promise<NextResponse | null> {
|
||||||
|
const session = await getServerSession(authOptions);
|
||||||
|
|
||||||
|
if (!session) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Non authentifié" },
|
||||||
|
{ status: 401 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
72
lib/auth.ts
Normal file
72
lib/auth.ts
Normal file
@@ -0,0 +1,72 @@
|
|||||||
|
import { NextAuthOptions } from "next-auth";
|
||||||
|
import CredentialsProvider from "next-auth/providers/credentials";
|
||||||
|
import { authService } from "@/services/auth.service";
|
||||||
|
|
||||||
|
// Get secret with fallback for development
|
||||||
|
const secret = process.env.NEXTAUTH_SECRET || "dev-secret-key-change-in-production";
|
||||||
|
|
||||||
|
// Debug: log secret status (remove in production)
|
||||||
|
if (process.env.NODE_ENV === "development") {
|
||||||
|
console.log("🔐 NextAuth secret:", process.env.NEXTAUTH_SECRET ? "✅ Loaded from .env.local" : "⚠️ Using fallback");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!process.env.NEXTAUTH_SECRET && process.env.NODE_ENV === "production") {
|
||||||
|
throw new Error(
|
||||||
|
"NEXTAUTH_SECRET is required in production. Please set it in your environment variables."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const authOptions: NextAuthOptions = {
|
||||||
|
providers: [
|
||||||
|
CredentialsProvider({
|
||||||
|
name: "Credentials",
|
||||||
|
credentials: {
|
||||||
|
password: { label: "Mot de passe", type: "password" },
|
||||||
|
},
|
||||||
|
async authorize(credentials) {
|
||||||
|
try {
|
||||||
|
if (!credentials?.password) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const isValid = await authService.verifyPassword(credentials.password);
|
||||||
|
if (!isValid) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return a user object (we don't need a real user, just authentication)
|
||||||
|
return {
|
||||||
|
id: "admin",
|
||||||
|
email: "admin@local",
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error in authorize:", error);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
pages: {
|
||||||
|
signIn: "/login",
|
||||||
|
},
|
||||||
|
session: {
|
||||||
|
strategy: "jwt",
|
||||||
|
maxAge: 30 * 24 * 60 * 60, // 30 days
|
||||||
|
},
|
||||||
|
callbacks: {
|
||||||
|
async jwt({ token, user }) {
|
||||||
|
if (user) {
|
||||||
|
token.id = user.id;
|
||||||
|
}
|
||||||
|
return token;
|
||||||
|
},
|
||||||
|
async session({ session, token }) {
|
||||||
|
if (session.user && token.id) {
|
||||||
|
session.user.id = token.id;
|
||||||
|
}
|
||||||
|
return session;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
secret,
|
||||||
|
};
|
||||||
|
|
||||||
22
middleware.ts
Normal file
22
middleware.ts
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
import { withAuth } from "next-auth/middleware";
|
||||||
|
|
||||||
|
export default withAuth({
|
||||||
|
pages: {
|
||||||
|
signIn: "/login",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export const config = {
|
||||||
|
matcher: [
|
||||||
|
/*
|
||||||
|
* Match all request paths except for the ones starting with:
|
||||||
|
* - api/auth (authentication routes)
|
||||||
|
* - login (login page)
|
||||||
|
* - _next/static (static files)
|
||||||
|
* - _next/image (image optimization files)
|
||||||
|
* - favicon.ico (favicon file)
|
||||||
|
*/
|
||||||
|
"/((?!api/auth|login|_next/static|_next/image|favicon.ico).*)",
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
@@ -48,6 +48,7 @@
|
|||||||
"@radix-ui/react-tooltip": "1.1.6",
|
"@radix-ui/react-tooltip": "1.1.6",
|
||||||
"@vercel/analytics": "1.3.1",
|
"@vercel/analytics": "1.3.1",
|
||||||
"autoprefixer": "^10.4.20",
|
"autoprefixer": "^10.4.20",
|
||||||
|
"bcryptjs": "^3.0.3",
|
||||||
"class-variance-authority": "^0.7.1",
|
"class-variance-authority": "^0.7.1",
|
||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
"cmdk": "1.0.4",
|
"cmdk": "1.0.4",
|
||||||
@@ -56,6 +57,7 @@
|
|||||||
"input-otp": "1.4.1",
|
"input-otp": "1.4.1",
|
||||||
"lucide-react": "^0.454.0",
|
"lucide-react": "^0.454.0",
|
||||||
"next": "16.0.3",
|
"next": "16.0.3",
|
||||||
|
"next-auth": "^4.24.13",
|
||||||
"next-themes": "^0.4.6",
|
"next-themes": "^0.4.6",
|
||||||
"prisma": "^5.22.0",
|
"prisma": "^5.22.0",
|
||||||
"react": "19.2.0",
|
"react": "19.2.0",
|
||||||
@@ -75,6 +77,7 @@
|
|||||||
"@eslint/eslintrc": "^3.3.1",
|
"@eslint/eslintrc": "^3.3.1",
|
||||||
"@next/eslint-plugin-next": "^16.0.5",
|
"@next/eslint-plugin-next": "^16.0.5",
|
||||||
"@tailwindcss/postcss": "^4.1.9",
|
"@tailwindcss/postcss": "^4.1.9",
|
||||||
|
"@types/bcryptjs": "^3.0.0",
|
||||||
"@types/node": "^22",
|
"@types/node": "^22",
|
||||||
"@types/react": "^19",
|
"@types/react": "^19",
|
||||||
"@types/react-dom": "^19",
|
"@types/react-dom": "^19",
|
||||||
|
|||||||
6653
pnpm-lock.yaml
generated
6653
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
82
services/auth.service.ts
Normal file
82
services/auth.service.ts
Normal file
@@ -0,0 +1,82 @@
|
|||||||
|
import { promises as fs } from "fs";
|
||||||
|
import path from "path";
|
||||||
|
import { existsSync } from "fs";
|
||||||
|
import bcrypt from "bcryptjs";
|
||||||
|
|
||||||
|
const PASSWORD_FILE = path.join(process.cwd(), "prisma", "password.json");
|
||||||
|
|
||||||
|
interface PasswordData {
|
||||||
|
hash: string;
|
||||||
|
createdAt: string;
|
||||||
|
updatedAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function ensurePasswordFile(): Promise<void> {
|
||||||
|
if (!existsSync(PASSWORD_FILE)) {
|
||||||
|
// Create default password "admin" if file doesn't exist
|
||||||
|
const defaultHash = await bcrypt.hash("admin", 10);
|
||||||
|
const defaultData: PasswordData = {
|
||||||
|
hash: defaultHash,
|
||||||
|
createdAt: new Date().toISOString(),
|
||||||
|
updatedAt: new Date().toISOString(),
|
||||||
|
};
|
||||||
|
await fs.writeFile(PASSWORD_FILE, JSON.stringify(defaultData, null, 2), "utf-8");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadPasswordData(): Promise<PasswordData> {
|
||||||
|
await ensurePasswordFile();
|
||||||
|
const content = await fs.readFile(PASSWORD_FILE, "utf-8");
|
||||||
|
return JSON.parse(content);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function savePasswordData(data: PasswordData): Promise<void> {
|
||||||
|
await fs.writeFile(PASSWORD_FILE, JSON.stringify(data, null, 2), "utf-8");
|
||||||
|
}
|
||||||
|
|
||||||
|
export const authService = {
|
||||||
|
async verifyPassword(password: string): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
const data = await loadPasswordData();
|
||||||
|
return await bcrypt.compare(password, data.hash);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error verifying password:", error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
async changePassword(oldPassword: string, newPassword: string): Promise<{ success: boolean; error?: string }> {
|
||||||
|
try {
|
||||||
|
// Verify old password
|
||||||
|
const isValid = await this.verifyPassword(oldPassword);
|
||||||
|
if (!isValid) {
|
||||||
|
return { success: false, error: "Mot de passe actuel incorrect" };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hash new password
|
||||||
|
const newHash = await bcrypt.hash(newPassword, 10);
|
||||||
|
const data = await loadPasswordData();
|
||||||
|
|
||||||
|
// Update password
|
||||||
|
data.hash = newHash;
|
||||||
|
data.updatedAt = new Date().toISOString();
|
||||||
|
|
||||||
|
await savePasswordData(data);
|
||||||
|
|
||||||
|
return { success: true };
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error changing password:", error);
|
||||||
|
return { success: false, error: "Erreur lors du changement de mot de passe" };
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
async hasPassword(): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
await ensurePasswordFile();
|
||||||
|
return existsSync(PASSWORD_FILE);
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
23
types/next-auth.d.ts
vendored
Normal file
23
types/next-auth.d.ts
vendored
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
import "next-auth";
|
||||||
|
|
||||||
|
declare module "next-auth" {
|
||||||
|
interface User {
|
||||||
|
id: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Session {
|
||||||
|
user: {
|
||||||
|
id: string;
|
||||||
|
email?: string | null;
|
||||||
|
name?: string | null;
|
||||||
|
image?: string | null;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
declare module "next-auth/jwt" {
|
||||||
|
interface JWT {
|
||||||
|
id: string;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Reference in New Issue
Block a user