Skip to content
Open
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
Binary file added .DS_Store
Binary file not shown.
152 changes: 152 additions & 0 deletions Controllers/RestaurantControllers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
const Restaurant = require('../Modals/Schema/RestaurantSch');
const { sendEmail } = require('../Helpers/mailer');
const { hashPassword, comparePassword } = require('../Helpers/Hashing');
const { generateToken } = require('../Helpers/JWT');

// Controller to render the registration page
exports.renderRegister = (req, res) => res.send('/register');

// Controller to render the login page
exports.renderLogin = (req, res) => res.send('/login');

// Controller to register a new restaurant
exports.registerRestaurant = async (req, res) => {
try {
const { name, email, password, country, city, address, phoneNumber, openingHours, menu } = req.body;

// Check if the restaurant already exists
const existingRestaurant = await Restaurant.findOne({ email });
if (existingRestaurant) {
return res.status(400).json({ message: 'Restaurant already exists' });
}

// Hash the password before saving
const hashedPassword = await hashPassword(password);

// Create a new restaurant instance
const newRestaurant = new Restaurant({ name, email, password: hashedPassword, country, city, address, phoneNumber, openingHours, menu });

// Save the new restaurant
const result = await newRestaurant.save();

// Send registration email
sendEmail(newRestaurant.email, newRestaurant.name);

// Send success response
res.status(200).send('Restaurant registration successful');
} catch (error) {
console.error('Error registering restaurant:', error);
res.status(500).send('Server Error');
}
};

// Controller to handle restaurant login
exports.restaurantLogin = async (req, res) => {
try {
const { email, password } = req.body;

// Find the restaurant by email
const restaurant = await Restaurant.findOne({ email });
if (!restaurant) {
return res.status(400).json({ message: 'Invalid Credentials' });
}

// Compare passwords
const isPasswordValid = await comparePassword(password, restaurant.password);
if (!isPasswordValid) {
return res.status(400).json({ message: 'Incorrect Password' });
}

// Generate JWT token
const token = await generateToken({ restaurant });

// Send success response with token
res.status(200).cookie('tokenAuth', token).json({ message: 'Restaurant logged successfully', token });
} catch (error) {
console.error('Error logging in restaurant:', error);
res.status(500).json({ message: 'Server Error' });
}
};

// Controller to get restaurant profile by ID
exports.getRestaurantProfile = async (req, res) => {
try {
const ownerId = req.params.id;

// Find the restaurant by ID
const restaurantProfile = await Restaurant.findById(ownerId);
if (!restaurantProfile) {
return res.status(404).json({ error: 'Restaurant owner profile not found' });
}

// Send restaurant profile
res.status(200).json(restaurantProfile);
} catch (error) {
console.error('Error getting restaurant owner profile:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
};

// Controller to update restaurant profile by ID
exports.updateRestaurantProfile = async (req, res) => {
try {
const ownerId = req.params.id;

// Find the existing restaurant
const existingOwner = await Restaurant.findById(ownerId);
if (!existingOwner) {
return res.status(404).json({ error: 'Restaurant owner not found' });
}

// Prepare updated data
const updatedData = {
name: req.body.name || existingOwner.name,
email: req.body.email || existingOwner.email,
country: req.body.country || existingOwner.country,
city: req.body.city || existingOwner.city,
address: req.body.address || existingOwner.address,
phoneNumber: req.body.phoneNumber || existingOwner.phoneNumber,
openingHours: req.body.openingHours || existingOwner.openingHours,
};

// Check if a new password is provided
if (req.body.password) {
const passwordMatch = await bcrypt.compare(req.body.password, existingOwner.password);
if (!passwordMatch) {
updatedData.password = await bcrypt.hash(req.body.password, 10);
}
}

// Update menu items if provided in the request
if (req.body.menu) {
updatedData.menu = req.body.menu;
}

// Update the restaurant
const updatedOwner = await Restaurant.findByIdAndUpdate(ownerId, updatedData, { new: true });

// Send success response
res.status(200).json({ message: 'Restaurant owner profile updated successfully', owner: updatedOwner });
} catch (error) {
console.error('Error updating restaurant owner profile:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
};

// Controller to delete restaurant profile by ID
exports.deleteRestaurantProfile = async (req, res) => {
try {
const ownerId = req.params.id;

// Delete the restaurant by ID
const deletedOwner = await Restaurant.findByIdAndDelete(ownerId);
if (deletedOwner) {
return res.status(200).json({ message: 'Restaurant owner profile deleted successfully' });
} else {
return res.status(404).json({ error: 'Restaurant owner not found' });
}
} catch (error) {
console.error('Error during profile deletion:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
};
58 changes: 58 additions & 0 deletions Controllers/UserControllers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
const User = require('../Modals/Schema/UserSch')
const {sendEmail} = require('../Helpers/mailer')
const {hashPassword,comparePassword} = require('../Helpers/Hashing')
const {generateToken} = require('../Helpers/JWT')

exports.renderRegister = (req,res) => {
res.send('/register')
}

exports.renderLogin = (req,res) => {
res.send('/login')
}

exports.registerUser = async (req,res) => {
try{
const {email} = req.body;
const user = await User.findOne({email});
if(user){
return res.status(400).json({message: 'User already exists'})
}
const {username,password,age,country,sex,phoneNumber,bio} = new User(req.body)
const hashedPassword = await hashPassword(password)
const newUser = new User({
username,
email : email,
password : hashedPassword,
age ,
country ,
sex ,
phoneNumber ,
bio
})
const result = await newUser.save()
sendEmail(newUser.email,newUser.username)
res.status(200).send('User registration successful')
}catch(error){
console.log('error' , error)
res.status(500).send('Server Error');
}
}

exports.userLogin = async (req,res) => {
try{
const {email,password} = req.body
const user = await User.findOne({email})
if(!user){
return res.status(400).json({message : 'Invalid Credentials'})
}

const checked =await comparePassword(password,user.password)
if(!checked) return res.status(400).json({message:"Incorrect Password"})

const token = await generateToken({user : user})
res.status(200).cookie('tokenAuth',token).send('User logged successfuly')
}catch(error){
console.log('error' , error)
}
}
File renamed without changes.
83 changes: 0 additions & 83 deletions Controllers/restaurantController.js

This file was deleted.

12 changes: 12 additions & 0 deletions Helpers/Hashing.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
const bcrypt = require('bcrypt')

class Hashing{
async hashPassword(password,salt=10){
return await bcrypt.hash(password,salt);
}
async comparePassword(password,hashedPassword){
return await bcrypt.compare(password,hashedPassword);
}
}

module.exports = new Hashing
9 changes: 9 additions & 0 deletions Helpers/JWT.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const jwt = require('jsonwebtoken');

exports.generateToken = async (data)=>{
return jwt.sign(data, process.env.SECRETKEY, {expiresIn: '1h'})
}

exports.verifyToken = (token)=>{
return jwt.verify(token, process.env.SECRETKEY)
}
30 changes: 30 additions & 0 deletions Helpers/mailer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
const nodemailer = require('nodemailer')
require('dotenv').config()

exports.sendEmail = async (mail,username) => {
const transporter = nodemailer.createTransport({
service: "gmail",
auth: {
user: process.env.EMAIL,
pass: process.env.PASSWORD
}
});

const mailOptions = {
from: process.env.EMAIL,
to: mail,
subject: "Welcome To our platform",
html : `<h3>Welcome ${username}</h3><br><p>Thank you for registering</p>`
};

transporter.sendMail(mailOptions, function(error, info) {
if (error) {
console.log(error);
res.send('Error');
} else {
console.log("Email sent: " + info.response);
res.send("Success");
}
});
}

12 changes: 0 additions & 12 deletions Middlwares/multer.js
Original file line number Diff line number Diff line change
@@ -1,12 +0,0 @@
const multer = require('multer')
const storage = multer.diskStorage ({
destination : (req, file, cb) => {
cb(null, './public/Images')
},
filename : (req, file , cb) => {
cb(null, Date.now() + '-' + file.originalname)
}
})

const upload = multer({storage})
module.exports = upload.single('image')
10 changes: 10 additions & 0 deletions Middlwares/sanitize.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
const xss = require("xss")
exports.Sanitize = (req, res, next) => {
const fields = ['username','email','age','country','sex','phoneNumber','bio']
for(i in fields) {
if(req.body[fields[i]]) {
req.body[fields[i]] = xss(req.body[fields[i]])
}
}
next()
}
Loading