Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 29 additions & 38 deletions backend/src/controllers/auth.controller.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,25 @@
import bcrypt from "bcryptjs";
import { getPool } from "../utils/initDB.js";
import { gennToken } from "../utils/lib.js";
const passwordRegex = /^(?=.*[A-Z])(?=.*[!@#$%^&*()_+{}\[\]:;<>,.?~\\-]).{8,16}$/;
import {
validatePassword,
hashPassword,
comparePassword,
PASSWORD_VALIDATION_MESSAGE,
} from "../utils/passwordUtils.js";
import {
handleError,
handleValidationError,
} from "../utils/errorHandler.js";
export const signUp = async (req, res) => {
const { Name, Email, Password, Address } = req.body;
try {

if (!Name || !Email || !Password || !Address) {
return res.status(400).json({ message: "All fields are required !! " });
}
if (!passwordRegex.test(Password)) {
return res.status(400).json({
message:
"Password must be 8-16 characters, include at least one uppercase letter and one special character."
});
}
if (!validatePassword(Password)) {
return handleValidationError(res, PASSWORD_VALIDATION_MESSAGE);
}
const pool = getPool();
const [existingUser] = await pool.query(
`SELECT * FROM users WHERE email = ?`,
Expand All @@ -24,9 +29,7 @@ export const signUp = async (req, res) => {
return res.status(400).json({ message: "User Already Exists" });
}


const salt = await bcrypt.genSalt(10);
const hashedPass = await bcrypt.hash(Password, salt);
const hashedPass = await hashPassword(Password);

const [result] = await pool.query(
`INSERT INTO users(name, email,password,address,role) VALUES(?,?,?,?,'user')`,
Expand All @@ -48,8 +51,7 @@ export const signUp = async (req, res) => {

return res.status(200).json(newUser);
} catch (error) {
console.log("Error in the Signup controller :", error.message);
return res.status(500).json({ message: "Internal Server Error!!" });
return handleError(res, error, "Signup controller");
}
};
export const logIn = async (req, res) => {
Expand All @@ -67,12 +69,11 @@ export const logIn = async (req, res) => {
console.log(row);
const user = row[0];
if (!user) {
return res.status(400).json({ message: "Inavlid Credentials" });
return res.status(400).json({ message: "Invalid Credentials" });
}

const isPassCorrect = await bcrypt.compare(password, user.password);
const isPassCorrect = await comparePassword(password, user.password);
if (!isPassCorrect) {
return res.status(400).json({ message: "Inavlid Credentials" });
return res.status(400).json({ message: "Invalid Credentials" });
}
gennToken(user.id, res);

Expand All @@ -86,8 +87,7 @@ export const logIn = async (req, res) => {
updated_at: user.updated_at,
});
} catch (error) {
console.log("Error in the Login controller:", error.message);
return res.status(500).json({ message: "Internal server error" });
return handleError(res, error, "Login controller");
}
};
export const logOut = (req, res) => {
Expand All @@ -104,20 +104,16 @@ export const logOut = (req, res) => {

return res.status(200).json({ message: "LoggedOut Successfully" });
} catch (error) {
console.log("Error in the log out controller : ", error.message);
return res.status(500).json({ message: " Internal Server Error" });
return handleError(res, error, "Logout controller");
}
};

export const updatePassword = async (req, res) => {
try {
const { currentPassword, newPassword } = req.body;

if (!passwordRegex.test(newPassword)) {
return res.status(400).json({
message:
"Password must be 8-16 characters, include at least one uppercase letter and one special character."
});
if (!validatePassword(newPassword)) {
return handleValidationError(res, PASSWORD_VALIDATION_MESSAGE);
}

const pool = getPool();
Expand All @@ -132,15 +128,12 @@ export const updatePassword = async (req, res) => {

const user = rows[0];


const passwordMatch = await bcrypt.compare(currentPassword, user.password);
const passwordMatch = await comparePassword(currentPassword, user.password);
if (!passwordMatch) {
return res.status(400).json({ message: "Current password is incorrect!!" });
}


const salt = await bcrypt.genSalt(10);
const newHashed = await bcrypt.hash(newPassword, salt);
const newHashed = await hashPassword(newPassword);


await pool.query(`UPDATE users SET password = ? WHERE id = ?`, [
Expand All @@ -155,17 +148,15 @@ export const updatePassword = async (req, res) => {
message: "Password updated successfully. Please log in again",
});
} catch (error) {
console.log("Error in the updatePassword Controller: ", error.message);
return res.status(500).json({ message: "Internal Server Error" });
return handleError(res, error, "updatePassword Controller");
}
};


export const checkAuth = (req,res)=>{
export const checkAuth = (req, res) => {
try {
res.status(200).json(req.user)
res.status(200).json(req.user);
} catch (error) {
console.log("Error in the CheckAuth controller :", error.message)
res.status(500).json({message : "Internal Server Error"})
return handleError(res, error, "CheckAuth controller");
}
}
};
6 changes: 3 additions & 3 deletions backend/src/controllers/dashboard.controller.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import * as dashBoardModel from "../models/dashboard.model.js"
import * as dashBoardModel from "../models/dashboard.model.js";
import { handleError } from "../utils/errorHandler.js";

export const getDashboard = async (req, res) => {
try {
const stats = await dashBoardModel.getDashboardStats();
res.status(200).json(stats);
} catch (error) {
console.error("Error fetching dashboard stats:", error);
res.status(500).json({ message: "Failed to fetch dashboard stats" });
return handleError(res, error, "getDashboard controller");
}
};
34 changes: 17 additions & 17 deletions backend/src/controllers/rating.controller.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
import * as ratingModel from "../models/rating.model.js";
import * as storeModel from "../models/store.model.js";
import {
handleError,
handleValidationError,
handleNotFoundError,
handleUnauthorizedError,
} from "../utils/errorHandler.js";


export const createRating = async (req, res) => {
Expand All @@ -8,21 +14,20 @@ export const createRating = async (req, res) => {
const user_id = req.user.id;

if (!store_id || !rating) {
return res.status(400).json({ message: "store_id and rating are required" });
return handleValidationError(res, "store_id and rating are required");
}

if (rating < 1 || rating > 5) {
return res.status(400).json({ message: "Rating must be between 1 and 5" });
return handleValidationError(res, "Rating must be between 1 and 5");
}

const ratingId = await ratingModel.addRating(user_id, store_id, rating);
res.status(201).json({ message: "Rating added successfully", ratingId });
} catch (error) {
if (error.code === "ER_DUP_ENTRY") {
return res.status(400).json({ message: "You already rated this store" });
return handleValidationError(res, "You already rated this store");
}
console.error("Error creating rating:", error);
res.status(500).json({ message: "Internal server error" });
return handleError(res, error, "createRating controller");
}
};

Expand All @@ -34,18 +39,17 @@ export const editRating = async (req, res) => {
const user_id = req.user.id;

if (!rating || rating < 1 || rating > 5) {
return res.status(400).json({ message: "Rating must be between 1 and 5" });
return handleValidationError(res, "Rating must be between 1 and 5");
}

const updated = await ratingModel.updateRating(id, user_id, rating);
if (!updated) {
return res.status(404).json({ message: "Rating not found or not yours" });
return handleNotFoundError(res, "Rating not found or not yours");
}

res.json({ message: "Rating updated successfully" });
} catch (error) {
console.error("Error updating rating:", error);
res.status(500).json({ message: "Internal server error" });
return handleError(res, error, "editRating controller");
}
};

Expand All @@ -59,21 +63,18 @@ export const storeRatings = async (req, res) => {

const store = await storeModel.getStoreById(storeId);
if (!store) {
return res.status(404).json({ message: "Store not found" });
return handleNotFoundError(res, "Store not found");
}


if (store.owner_id !== req.user.id) {
return res.status(403).json({ message: "You are not the owner of this store" });
return handleUnauthorizedError(res, "You are not the owner of this store");
}


const ratings = await ratingModel.getStoreRatings(storeId);

res.json({ storeId, ratings });
} catch (error) {
console.error("Error fetching store ratings:", error);
res.status(500).json({ message: "Internal server error" });
return handleError(res, error, "storeRatings controller");
}
};

Expand All @@ -84,8 +85,7 @@ export const getUserRatings = async (req, res) => {
const ratings = await ratingModel.getUserRatings(user_id);
res.json({ ratings });
} catch (error) {
console.error("Error fetching user ratings:", error);
res.status(500).json({ message: "Internal server error" });
return handleError(res, error, "getUserRatings controller");
}
};

18 changes: 10 additions & 8 deletions backend/src/controllers/store.controller.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@
import * as storeModel from "../models/store.model.js"
import * as storeModel from "../models/store.model.js";
import {
handleError,
handleValidationError,
} from "../utils/errorHandler.js";
export const addStore = async (req, res) => {
try {
const { name, email, address, owner_id } = req.body;
if (!name || !email || !address || !owner_id) {
return res.status(400).json({ message: "Name, email, address, and owner are required" });
return handleValidationError(res, "Name, email, address, and owner are required");
}

const newStore = await storeModel.addStore({ name, email, address, owner_id });
console.log(newStore)
res.status(201).json({ message: "New Store added Successfuly !!" });
console.log(newStore);
res.status(201).json({ message: "New Store added Successfully !!" });
} catch (error) {
console.error("Error in addStore:", error);
res.status(500).json({ message: "Failed to add store" });
return handleError(res, error, "addStore controller");
}
};

Expand All @@ -21,8 +24,7 @@ export const getAllStores = async (req, res) => {
const stores = await storeModel.getAllStores({ name, address });
res.json(stores);
} catch (error) {
console.error("Error in getAllStores Controller:", error);
res.status(500).json({ message: "Failed to fetch stores" });
return handleError(res, error, "getAllStores controller");
}
};

33 changes: 17 additions & 16 deletions backend/src/controllers/user.controller.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
import * as userModel from "../models/user.model.js";
const passwordRegex =
/^(?=.*[A-Z])(?=.*[!@#$%^&*()_+{}\[\]:;<>,.?~\\-]).{8,16}$/;
import {
validatePassword,
PASSWORD_VALIDATION_MESSAGE,
} from "../utils/passwordUtils.js";
import {
handleError,
handleValidationError,
handleNotFoundError,
} from "../utils/errorHandler.js";


export const addUser = async (req, res) => {
Expand All @@ -12,19 +19,15 @@ export const addUser = async (req, res) => {
.json({ message: "All required fields must be provided" });
}

if (!passwordRegex.test(password)) {
return res.status(400).json({
message:
"Password must be 8-16 characters, include at least one uppercase letter and one special character.",
});
if (!validatePassword(password)) {
return handleValidationError(res, PASSWORD_VALIDATION_MESSAGE);
}

const newUser = await userModel.addUser(name, email, password, address, role);
console.log(newUser)
return res.status(201).json({message : "New User Created Successfully !!"})
console.log(newUser);
return res.status(201).json({ message: "New User Created Successfully !!" });
} catch (error) {
console.error("Error in addUser controller:", error);
res.status(500).json({ message: "Failed to add user" });
return handleError(res, error, "addUser controller");
}
};

Expand All @@ -37,8 +40,7 @@ export const getAllUsers = async (req, res) => {
const users = await userModel.getAllUsers({ name, email, address, role });
res.json(users);
} catch (error) {
console.error("Error in getAllusers Conroller:", error);
res.status(500).json({ message: "Failed to fetch users" });
return handleError(res, error, "getAllUsers controller");
}
};

Expand All @@ -47,11 +49,10 @@ export const getUserDetails = async (req, res) => {
const { id } = req.params;
const user = await userModel.getUserDetails(id);

if (!user) return res.status(404).json({ message: "User not found" });
if (!user) return handleNotFoundError(res, "User not found");

res.json(user);
} catch (error) {
console.error("Error fetching user controller:", error);
res.status(500).json({ message: "Failed to fetch user details" });
return handleError(res, error, "getUserDetails controller");
}
};
5 changes: 2 additions & 3 deletions backend/src/models/user.model.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { getPool } from "../utils/initDB.js";
import bcrypt from "bcryptjs";
import { hashPassword } from "../utils/passwordUtils.js";

export const addUser = async (name, email, password, address, role) => {
const pool = getPool();
const salt = await bcrypt.genSalt(10);
const hashPass = await bcrypt.hash(password, salt);
const hashPass = await hashPassword(password);

const [result] = await pool.query(
`INSERT INTO users (name,email,password,address,role) VALUES(?,?,?,?,?)`,
Expand Down
16 changes: 16 additions & 0 deletions backend/src/utils/errorHandler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
export const handleError = (res, error, context, statusCode = 500) => {
console.log(`Error in ${context}:`, error.message);
return res.status(statusCode).json({ message: "Internal Server Error" });
};

export const handleValidationError = (res, message) => {
return res.status(400).json({ message });
};

export const handleNotFoundError = (res, message) => {
return res.status(404).json({ message });
};

export const handleUnauthorizedError = (res, message) => {
return res.status(403).json({ message });
};
Loading