refacto(db): auth and user cleaner
This commit is contained in:
@@ -1,48 +1,29 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { cookies } from "next/headers";
|
||||
import connectDB from "@/lib/mongodb";
|
||||
import { UserModel } from "@/lib/models/user.model";
|
||||
import { AuthServerService } from "@/lib/services/auth-server.service";
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const { email, password, remember } = await request.json();
|
||||
await connectDB();
|
||||
const { email, password } = await request.json();
|
||||
|
||||
const user = await UserModel.findOne({ email: email.toLowerCase() });
|
||||
try {
|
||||
const userData = await AuthServerService.loginUser(email, password);
|
||||
AuthServerService.setUserCookie(userData);
|
||||
|
||||
if (!user || user.password !== password) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: "INVALID_CREDENTIALS",
|
||||
message: "Email ou mot de passe incorrect",
|
||||
return NextResponse.json({ message: "Connexion réussie", user: userData });
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message === "INVALID_CREDENTIALS") {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: "INVALID_CREDENTIALS",
|
||||
message: "Email ou mot de passe incorrect",
|
||||
},
|
||||
},
|
||||
},
|
||||
{ status: 401 }
|
||||
);
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
const userData = {
|
||||
id: user._id.toString(),
|
||||
email: user.email,
|
||||
roles: user.roles,
|
||||
authenticated: true,
|
||||
};
|
||||
|
||||
// Encoder les données utilisateur en base64
|
||||
const encodedUserData = Buffer.from(JSON.stringify(userData)).toString("base64");
|
||||
|
||||
// Définir le cookie avec les données utilisateur
|
||||
cookies().set("stripUser", encodedUserData, {
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === "production",
|
||||
sameSite: "lax",
|
||||
path: "/",
|
||||
// 30 jours si "remember me" est coché, sinon 24 heures
|
||||
maxAge: remember ? 30 * 24 * 60 * 60 : 24 * 60 * 60,
|
||||
});
|
||||
|
||||
return NextResponse.json({ message: "Connexion réussie", user: userData });
|
||||
} catch (error) {
|
||||
console.error("Erreur lors de la connexion:", error);
|
||||
return NextResponse.json(
|
||||
|
||||
@@ -1,56 +1,29 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { cookies } from "next/headers";
|
||||
import connectDB from "@/lib/mongodb";
|
||||
import { UserModel } from "@/lib/models/user.model";
|
||||
import { AuthServerService } from "@/lib/services/auth-server.service";
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const { email, password } = await request.json();
|
||||
await connectDB();
|
||||
|
||||
// Vérifier si l'utilisateur existe déjà
|
||||
const existingUser = await UserModel.findOne({ email: email.toLowerCase() });
|
||||
if (existingUser) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: "EMAIL_EXISTS",
|
||||
message: "Cet email est déjà utilisé",
|
||||
try {
|
||||
const userData = await AuthServerService.createUser(email, password);
|
||||
AuthServerService.setUserCookie(userData);
|
||||
|
||||
return NextResponse.json({ message: "Inscription réussie", user: userData });
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message === "EMAIL_EXISTS") {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: "EMAIL_EXISTS",
|
||||
message: "Cet email est déjà utilisé",
|
||||
},
|
||||
},
|
||||
},
|
||||
{ status: 400 }
|
||||
);
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
// Créer le nouvel utilisateur
|
||||
const user = await UserModel.create({
|
||||
email: email.toLowerCase(),
|
||||
password,
|
||||
roles: ["ROLE_USER"],
|
||||
authenticated: true,
|
||||
});
|
||||
|
||||
const userData = {
|
||||
id: user._id.toString(),
|
||||
email: user.email,
|
||||
roles: user.roles,
|
||||
authenticated: true,
|
||||
};
|
||||
|
||||
// Encoder les données utilisateur en base64
|
||||
const encodedUserData = Buffer.from(JSON.stringify(userData)).toString("base64");
|
||||
|
||||
// Définir le cookie avec les données utilisateur
|
||||
cookies().set("stripUser", encodedUserData, {
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === "production",
|
||||
sameSite: "lax",
|
||||
path: "/",
|
||||
// 24 heures par défaut pour les nouveaux utilisateurs
|
||||
maxAge: 24 * 60 * 60,
|
||||
});
|
||||
|
||||
return NextResponse.json({ message: "Inscription réussie", user: userData });
|
||||
} catch (error) {
|
||||
console.error("Erreur lors de l'inscription:", error);
|
||||
return NextResponse.json(
|
||||
|
||||
90
src/lib/services/auth-server.service.ts
Normal file
90
src/lib/services/auth-server.service.ts
Normal file
@@ -0,0 +1,90 @@
|
||||
import { cookies } from "next/headers";
|
||||
import connectDB from "@/lib/mongodb";
|
||||
import { UserModel } from "@/lib/models/user.model";
|
||||
|
||||
interface UserData {
|
||||
id: string;
|
||||
email: string;
|
||||
roles: string[];
|
||||
authenticated: boolean;
|
||||
}
|
||||
|
||||
export class AuthServerService {
|
||||
static async createUser(email: string, password: string): Promise<UserData> {
|
||||
await connectDB();
|
||||
|
||||
// Check if user already exists
|
||||
const existingUser = await UserModel.findOne({ email: email.toLowerCase() });
|
||||
if (existingUser) {
|
||||
throw new Error("EMAIL_EXISTS");
|
||||
}
|
||||
|
||||
// Create new user
|
||||
const user = await UserModel.create({
|
||||
email: email.toLowerCase(),
|
||||
password,
|
||||
roles: ["ROLE_USER"],
|
||||
authenticated: true,
|
||||
});
|
||||
|
||||
const userData: UserData = {
|
||||
id: user._id.toString(),
|
||||
email: user.email,
|
||||
roles: user.roles,
|
||||
authenticated: true,
|
||||
};
|
||||
|
||||
return userData;
|
||||
}
|
||||
|
||||
static setUserCookie(userData: UserData): void {
|
||||
// Encode user data in base64
|
||||
const encodedUserData = Buffer.from(JSON.stringify(userData)).toString("base64");
|
||||
|
||||
// Set cookie with user data
|
||||
cookies().set("stripUser", encodedUserData, {
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === "production",
|
||||
sameSite: "lax",
|
||||
path: "/",
|
||||
maxAge: 24 * 60 * 60, // 24 hours by default for new users
|
||||
});
|
||||
}
|
||||
|
||||
static getCurrentUser(): UserData | null {
|
||||
const userCookie = cookies().get("stripUser");
|
||||
|
||||
if (!userCookie) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return JSON.parse(atob(userCookie.value));
|
||||
} catch (error) {
|
||||
console.error("Error while getting user from cookie:", error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
static async loginUser(email: string, password: string): Promise<UserData> {
|
||||
await connectDB();
|
||||
|
||||
const user = await UserModel.findOne({ email: email.toLowerCase() });
|
||||
if (!user) {
|
||||
throw new Error("INVALID_CREDENTIALS");
|
||||
}
|
||||
|
||||
if (user.password !== password) {
|
||||
throw new Error("INVALID_CREDENTIALS");
|
||||
}
|
||||
|
||||
const userData: UserData = {
|
||||
id: user._id.toString(),
|
||||
email: user.email,
|
||||
roles: user.roles,
|
||||
authenticated: true,
|
||||
};
|
||||
|
||||
return userData;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user