add debut auth systeme

This commit is contained in:
Arhur
2024-12-08 03:14:52 +01:00
parent f26a23bc45
commit 3efd4c9345
16 changed files with 1835 additions and 123 deletions
+1439 -29
View File
File diff suppressed because it is too large Load Diff
+6
View File
@@ -9,12 +9,18 @@
"lint": "next lint" "lint": "next lint"
}, },
"dependencies": { "dependencies": {
"@prisma/client": "^6.0.1",
"axios": "^1.7.9",
"bcryptjs": "^2.4.3",
"next": "15.0.4", "next": "15.0.4",
"prisma": "^6.0.1",
"react": "^19.0.0", "react": "^19.0.0",
"react-dom": "^19.0.0", "react-dom": "^19.0.0",
"sqlite3": "^5.1.7",
"streaming": "file:" "streaming": "file:"
}, },
"devDependencies": { "devDependencies": {
"@types/bcryptjs": "^2.4.6",
"@types/node": "^20", "@types/node": "^20",
"@types/react": "^19", "@types/react": "^19",
"@types/react-dom": "^19", "@types/react-dom": "^19",
BIN
View File
Binary file not shown.
@@ -0,0 +1,11 @@
-- CreateTable
CREATE TABLE "User" (
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"email" TEXT NOT NULL,
"password" TEXT NOT NULL,
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" DATETIME NOT NULL
);
-- CreateIndex
CREATE UNIQUE INDEX "User_email_key" ON "User"("email");
@@ -0,0 +1,24 @@
/*
Warnings:
- Added the required column `username` to the `User` table without a default value. This is not possible if the table is not empty.
*/
-- RedefineTables
PRAGMA defer_foreign_keys=ON;
PRAGMA foreign_keys=OFF;
CREATE TABLE "new_User" (
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"username" TEXT NOT NULL,
"email" TEXT NOT NULL,
"password" TEXT NOT NULL,
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" DATETIME NOT NULL
);
INSERT INTO "new_User" ("createdAt", "email", "id", "password", "updatedAt") SELECT "createdAt", "email", "id", "password", "updatedAt" FROM "User";
DROP TABLE "User";
ALTER TABLE "new_User" RENAME TO "User";
CREATE UNIQUE INDEX "User_username_key" ON "User"("username");
CREATE UNIQUE INDEX "User_email_key" ON "User"("email");
PRAGMA foreign_keys=ON;
PRAGMA defer_foreign_keys=OFF;
+3
View File
@@ -0,0 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (i.e. Git)
provider = "sqlite"
+23
View File
@@ -0,0 +1,23 @@
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema
// Looking for ways to speed up your queries, or scale easily with your serverless or edge functions?
// Try Prisma Accelerate: https://pris.ly/cli/accelerate-init
datasource db {
provider = "sqlite"
url = "file:./dev.db"
}
generator client {
provider = "prisma-client-js"
}
model User {
id Int @id @default(autoincrement())
username String @unique
email String @unique
password String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
+30
View File
@@ -0,0 +1,30 @@
"use client";
import React from "react";
import axios from "axios";
import LoginForm from "@/components/auth/LoginForm";
const LoginPage: React.FC = () => {
const handleLogin = async (email: string, password: string) => {
console.log('Connexion de l\'utilisateur:', email, password);
try {
const response = await axios.post("/api/auth/login", {
email,
password,
});
console.log('Utilisateur connecté:', response.data);
} catch (error) {
console.error(error);
}
};
return (
<div className="min-h-screen flex items-center justify-center bg-gray-100">
<LoginForm onSubmit={handleLogin} />
</div>
);
};
export default LoginPage;
+31
View File
@@ -0,0 +1,31 @@
"use client";
import React from "react";
import axios from "axios";
import SignupForm from "@/components/auth/SignupForm";
const SignupPage: React.FC = () => {
const handleSignup = async (username: string, email: string, password: string) => {
console.log('Création de l\'utilisateur:', username, email, password);
try {
const response = await axios.post("/api/auth/signup", {
username,
email,
password,
});
console.log('Utilisateur créé:', response.data);
} catch (error) {
console.error(error);
}
};
return (
<div className="min-h-screen flex items-center justify-center bg-gray-100">
<SignupForm onSubmit={handleSignup} />
</div>
);
};
export default SignupPage;
+26
View File
@@ -0,0 +1,26 @@
import { NextResponse } from 'next/server';
import prisma from '@/lib/db';
import bcrypt from 'bcryptjs';
export async function POST(req: Request) {
const { email, password } = await req.json();
// Trouver l'utilisateur par email
const user = await prisma.user.findUnique({
where: { email }
});
if (!user) {
return NextResponse.json({ error: 'Invalid credentials' }, { status: 400 });
}
// Comparer le mot de passe
const isPasswordValid = await bcrypt.compare(password, user.password);
if (!isPasswordValid) {
return NextResponse.json({ error: 'Invalid credentials' }, { status: 400 });
}
// Réponse réussie
return NextResponse.json({ message: 'Login successful', user });
}
View File
+37
View File
@@ -0,0 +1,37 @@
import { NextResponse } from 'next/server';
import prisma from '@/lib/db';
import bcrypt from 'bcryptjs';
export async function POST(req: Request) {
const { username, email, password } = await req.json();
const existingUsername = await prisma.user.findUnique({
where: { username }
});
if (existingUsername) {
return NextResponse.json({ error: 'Username already taken' }, { status: 400 });
}
const existingUser = await prisma.user.findUnique({
where: { email }
});
if (existingUser) {
return NextResponse.json({ error: 'Email already taken' }, { status: 400 });
}
// Hacher le mot de passe
const hashedPassword = await bcrypt.hash(password, 10);
// Créer l'utilisateur
const newUser = await prisma.user.create({
data: {
username,
email,
password: hashedPassword,
}
});
return NextResponse.json({ message: 'User created successfully', user: newUser });
}
+2 -94
View File
@@ -2,100 +2,8 @@ import Image from "next/image";
export default function Home() { export default function Home() {
return ( return (
<div className="grid grid-rows-[20px_1fr_20px] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20 font-[family-name:var(--font-geist-sans)]"> <div>
<main className="flex flex-col gap-8 row-start-2 items-center sm:items-start"> <h1>Home</h1>
<Image
className="dark:invert"
src="/next.svg"
alt="Next.js logo"
width={180}
height={38}
priority
/>
<ol className="list-inside list-decimal text-sm text-center sm:text-left font-[family-name:var(--font-geist-mono)]">
<li className="mb-2">
Get started by editing{" "}
<code className="bg-black/[.05] dark:bg-white/[.06] px-1 py-0.5 rounded font-semibold">
src/app/page.tsx
</code>
.
</li>
<li>Save and see your changes instantly.</li>
</ol>
<div className="flex gap-4 items-center flex-col sm:flex-row">
<a
className="rounded-full border border-solid border-transparent transition-colors flex items-center justify-center bg-foreground text-background gap-2 hover:bg-[#383838] dark:hover:bg-[#ccc] text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5"
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
className="dark:invert"
src="/vercel.svg"
alt="Vercel logomark"
width={20}
height={20}
/>
Deploy now
</a>
<a
className="rounded-full border border-solid border-black/[.08] dark:border-white/[.145] transition-colors flex items-center justify-center hover:bg-[#f2f2f2] dark:hover:bg-[#1a1a1a] hover:border-transparent text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5 sm:min-w-44"
href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
Read our docs
</a>
</div>
</main>
<footer className="row-start-3 flex gap-6 flex-wrap items-center justify-center">
<a
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
aria-hidden
src="/file.svg"
alt="File icon"
width={16}
height={16}
/>
Learn
</a>
<a
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
aria-hidden
src="/window.svg"
alt="Window icon"
width={16}
height={16}
/>
Examples
</a>
<a
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
href="https://nextjs.org?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
aria-hidden
src="/globe.svg"
alt="Globe icon"
width={16}
height={16}
/>
Go to nextjs.org
</a>
</footer>
</div> </div>
); );
} }
+85
View File
@@ -0,0 +1,85 @@
"use client";
import React, { useState } from "react";
interface LoginFormProps {
onSubmit: (email: string, password: string) => void;
}
const LoginForm: React.FC<LoginFormProps> = ({ onSubmit }) => {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState("");
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (!email || !password) {
setError("Tous les champs sont obligatoires !");
return;
}
if (!email.includes("@")) {
setError("L'adresse e-mail est invalide.");
return;
}
setError("");
onSubmit(email, password);
};
return (
<form
onSubmit={handleSubmit}
className="max-w-md mx-auto p-6 bg-white shadow-md rounded-lg"
>
<h2 className="text-2xl font-bold text-center mb-4">Connexion</h2>
{error && (
<p className="text-red-500 text-center mb-4">{error}</p>
)}
<div className="mb-4">
<label
htmlFor="email"
className="block text-sm font-medium text-gray-700"
>
E-mail
</label>
<input
type="email"
id="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
placeholder="Entrez votre e-mail"
/>
</div>
<div className="mb-4">
<label
htmlFor="password"
className="block text-sm font-medium text-gray-700"
>
Mot de passe
</label>
<input
type="password"
id="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
placeholder="Entrez votre mot de passe"
/>
</div>
<button
type="submit"
className="w-full bg-blue-500 text-white py-2 px-4 rounded-md hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-400"
>
Se connecter
</button>
</form>
);
};
export default LoginForm;
+113
View File
@@ -0,0 +1,113 @@
"use client";
import React, { useState } from "react";
interface SignupFormProps {
onSubmit: (username: string, email: string, password: string) => void;
}
const SignupForm: React.FC<SignupFormProps> = ({ onSubmit }) => {
const [username, setUsername] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState("");
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
// Validation simple
if (!username || !email || !password) {
setError("Tous les champs sont obligatoires !");
return;
}
if (!email.includes("@")) {
setError("L'adresse e-mail est invalide.");
return;
}
if (password.length < 6) {
setError("Le mot de passe doit contenir au moins 6 caractères.");
return;
}
setError(""); // Réinitialiser les erreurs
onSubmit(username, email, password); // Appeler la fonction onSubmit
};
return (
<form
onSubmit={handleSubmit}
className="max-w-md mx-auto p-6 bg-white shadow-md rounded-lg"
>
<h2 className="text-2xl font-bold text-center mb-4">Inscription</h2>
{/* Affichage des erreurs */}
{error && (
<p className="text-red-500 text-center mb-4">{error}</p>
)}
{/* Champ nom d'utilisateur */}
<div className="mb-4">
<label
htmlFor="username"
className="block text-sm font-medium text-gray-700"
>
Nom d'utilisateur
</label>
<input
type="text"
id="username"
value={username}
onChange={(e) => setUsername(e.target.value)}
className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
placeholder="Entrez votre nom d'utilisateur"
/>
</div>
{/* Champ e-mail */}
<div className="mb-4">
<label
htmlFor="email"
className="block text-sm font-medium text-gray-700"
>
E-mail
</label>
<input
type="email"
id="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
placeholder="Entrez votre e-mail"
/>
</div>
{/* Champ mot de passe */}
<div className="mb-4">
<label
htmlFor="password"
className="block text-sm font-medium text-gray-700"
>
Mot de passe
</label>
<input
type="password"
id="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
placeholder="Entrez votre mot de passe"
/>
</div>
{/* Bouton de soumission */}
<button
type="submit"
className="w-full bg-blue-500 text-white py-2 px-4 rounded-md hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-400"
>
S'inscrire
</button>
</form>
);
};
export default SignupForm;
+5
View File
@@ -0,0 +1,5 @@
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
export default prisma;