Skip to content

Commit

Permalink
Merge pull request #2 from PsionicGeek/master
Browse files Browse the repository at this point in the history
new code
  • Loading branch information
Divyanshu-Sethi authored Jan 10, 2024
2 parents 148e71b + e15dd3a commit 76b7417
Show file tree
Hide file tree
Showing 13 changed files with 182 additions and 95 deletions.
6 changes: 3 additions & 3 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@ const app = express()
const dotenv = require('dotenv');
const userRouter = require("./routes/user")
dotenv.config({path : '.env'})

const cookieParser = require('cookie-parser')
//=================================================================================
app.use(express.json());
app.use(cookieParser())
const adminRouter = require('./routes/admin')


Expand All @@ -18,8 +19,7 @@ app.use('/user', userRouter);

//=================================================================================
//CONNECT TO DATABASE

mongoose.connect( "mongodb://localhost:27017/TastyDB")
mongoose.connect(process.env.DB_URL)
.then(() => { console.log('CONNECTED TO DATABASE :)') })
.catch((err) => { console.log('CONNECTION TO DATABASE FAILED :(', err) })

Expand Down
37 changes: 37 additions & 0 deletions controllers/adminController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
const Category = require('../models/categorySchema')
const Dish = require('../models/dishSchema')

//=============================================================================================================================
const addDish = async(req, res)=>{
const dishObject = req.body; //the passed category name must exist

//extract the category name
const category_name = dishObject.category_name;
delete dishObject.category_name

//find the category in document
const foundCategory = await Category.findOne({name : category_name})
if (foundCategory == null)
res.status(401).json({msg : 'Category not found'})
dishObject.category = foundCategory;

//create a new dish
const newDish = await Dish.create(dishObject);

if (newDish)
res.status(200).json(newDish)
else
res.status(401).json({ message: 'Cannot add dish (Invalid or missing details)' })
}
//===============================================================================================================================
const addCategory = async(req, res)=>{
const categoryObject = req.body;
//create a new category
const newCategory = await Category.create(categoryObject);
if (newCategory)
res.status(200).json(newCategory)
else
res.status(401).json({ message: 'Cannot add category (Invalid or missing details)' })
}
//====================================================================================================================================
module.exports = { addDish, addCategory }
69 changes: 62 additions & 7 deletions controllers/userController.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ const User = require("../models/userSchema");
const jwt = require("jsonwebtoken");
const bcrypt = require('bcrypt');

//===================================================================================================================
// controllers/authController.js
const signup = async (req, res) => {
try {
Expand All @@ -15,6 +16,7 @@ const signup = async (req, res) => {
return res.status(400).json({ message: 'User with this email or mobile number already exists' });
}

console.log(username)
// Hash the password
const hashedPassword = await bcrypt.hash(password, 10);

Expand All @@ -36,13 +38,66 @@ const signup = async (req, res) => {
res.status(500).json({ message: 'Internal Server Error' });
}
};
//==============================================================================================================
//sign in
const getToken = (user) => {
const token = jwt.sign(
{
id: user.id,
email: user.email,
isAdmin: user.isAdmin,
},
process.env.JWT_SECRET,
{
expiresIn: '40d',
}
);
return token;
};

const signin= async(req, res) =>{
const userObject = req.body;
const { email, password } = userObject
const foundUser = await User.findOne({ email });

if (foundUser && (await bcrypt.compare(password, foundUser.password)))
{
const token = getToken(foundUser);
const responseObj = {
id: foundUser.id,
email: foundUser.email,
name: foundUser.name,
address: foundUser.address,
isAdmin: foundUser.isAdmin,
token,
}

const signin= (req, res) =>{
console.log("hello");
res.send("Hello")
const options = {
expires: new Date(Date.now() + (7 * 24 * 60 * 60 * 1000)), //Date.now() gives date in "ms"...we need to keep cookie in browser for 1 week
//we need to add 1 week [in ms] to the current date
httpOnly : true

}
const userObj = {
token : token,
user_id : foundUser.id
}
res.status(200).cookie("user", userObj, options).json(responseObj)
return;
}
else
res.status(400).json({msg : 'User not registered'})
};
module.exports = authController = {
signup,
signin
};
//=============================================================================================================================
//signout
const signout = (req, res) => {
try {
res.clearCookie("user");
res.status(200).json({msg : 'Signout successful'});
}
catch (err){
res.status(400).json({msg : 'Signout not possible'})
}
}
//================================================================================================================================
module.exports = { signup, signin, signout };
17 changes: 17 additions & 0 deletions middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
const jwt = require("jsonwebtoken");

const isLoggedIn = (req, res, next)=>{

const token = req.cookies.token
try{
const user = jwt.verify(token, process.env.JWT_SECRET);
req.user = user;
}
catch (err)
{
return res.status(401).json({error: "Authorization required"});
}
next();
};

module.exports = { isLoggedIn };
38 changes: 0 additions & 38 deletions middleware/tokenMiddleware.js

This file was deleted.

2 changes: 1 addition & 1 deletion models/dishSchema.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ const Schema= mongoose.Schema({
type:Date,
default:null
},
category_id:{
category:{
type:mongoose.Schema.Types.ObjectId,
ref:'Category',
required:true
Expand Down
4 changes: 2 additions & 2 deletions models/orderSchema.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ const Schema= mongoose.Schema({
type:Date,
default:null
},
user_id:{
user:{
type:mongoose.Schema.Types.ObjectId,
ref:'User',
required:true
Expand All @@ -29,7 +29,7 @@ const Schema= mongoose.Schema({
},
dishes:[
{
dish_id:{
dish:{
type:mongoose.Schema.Types.ObjectId,
ref:'Dish',
required:true
Expand Down
4 changes: 2 additions & 2 deletions models/paymentSchema.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,12 @@ const Schema= mongoose.Schema({
type:Number,
required:true
},
user_id:{
user:{
type:mongoose.Schema.Types.ObjectId,
ref:'User',
required:true
},
order_id:{
order:{
type:mongoose.Schema.Types.ObjectId,
ref:'Order',
required:true
Expand Down
20 changes: 20 additions & 0 deletions node_modules/.package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

21 changes: 21 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"license": "ISC",
"dependencies": {
"bcrypt": "^5.1.1",
"cookie-parser": "^1.4.6",
"dotenv": "^16.3.1",
"express": "^4.18.2",
"express-async-handler": "^1.2.0",
Expand Down
40 changes: 6 additions & 34 deletions routes/admin.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,40 +6,12 @@ const Dish = require('../models/dishSchema')
const User = require('../models/userSchema')
const Payment = require('../models/paymentSchema')
const Order = require('../models/orderSchema')

const { addDish, addCategory } = require('../controllers/adminController')
//===================================================================================================================================
router.post('/addDish', async(req, res)=>{
const dishObject = req.body; //the passed category name must exist

//extract the category name
const category_name = dishObject.category_name;
delete dishObject.category_name

//find the category in document
const foundCategory = await Category.findOne({name : category_name})
if (foundCategory == null)
res.status(401).json({msg : 'Category not found'})
dishObject.category_id = foundCategory.id;

//create a new dish
const newDish = await Dish.create(dishObject);

if (newDish)
res.status(200).json(newDish)
else
res.status(401).json({ message: 'Cannot add dish (Invalid or missing details)' })
})
//==================================================================================================================================
router.post('/addCategory', async(req, res)=>{
const categoryObject = req.body;
//create a new category
const newCategory = await Category.create(categoryObject);
if (newCategory)
res.status(200).json(newCategory)
else
res.status(401).json({ message: 'Cannot add category (Invalid or missing details)' })
})
router.get('/', function(req, res, next) {
res.send('Hello Admin');
});

router.post('/addDish', addDish)
router.post('/addCategory', addCategory)

//========================================================================================================================================
module.exports = router
Loading

0 comments on commit 76b7417

Please sign in to comment.