Skip to content

Commit

Permalink
Solve issue #8 : Added test for Auth routes
Browse files Browse the repository at this point in the history
  • Loading branch information
mathanraj0601 committed Jan 20, 2024
1 parent cd15768 commit 8226234
Show file tree
Hide file tree
Showing 5 changed files with 276 additions and 132 deletions.
11 changes: 7 additions & 4 deletions server/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,11 @@ app.use(Routes);

/**
* connect to db then start server
*/
dbConnect(() => app.listen(process.env.PORT, () =>
console.log(`Server is running on port ${process.env.PORT}`)
))
// */
dbConnect(() => {
app.listen(process.env.PORT, () => {
console.log(`Server is running on port ${process.env.PORT}`);
});
});

module.exports = app;
22 changes: 11 additions & 11 deletions server/config/connect.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
const mongoose = require("mongoose");

const dbConnect = async (callback) => {
try {
mongoose.set('strictQuery', false)
const connect = await mongoose.connect(process.env.MONGO_URL);
if (connect) {
console.log("DB is successfully connected");
callback(); //start the server
}
} catch (error) {
console.error("Error connecting to the database:", error);
try {
mongoose.set("strictQuery", false);
const connect = await mongoose.connect(process.env.MONGO_URL);
if (connect) {
console.log("DB is successfully connected");
callback(); //start the server
}
}
} catch (error) {
console.error("Error connecting to the database:", error);
}
};

module.exports = dbConnect;
module.exports = dbConnect;
244 changes: 128 additions & 116 deletions server/controllers/auth.js
Original file line number Diff line number Diff line change
@@ -1,101 +1,110 @@
const User = require('../model/user.js')
const bcrypt = require("bcrypt")
const jwt = require('jsonwebtoken') // authentication, login , authorization - is he an admin or not?
const passwordReset = require('../model/passwordReset.js');
const mailer = require('../helper/mailer');
require('dotenv').config()
const User = require("../model/user.js");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken"); // authentication, login , authorization - is he an admin or not?
const passwordReset = require("../model/passwordReset.js");
const mailer = require("../helper/mailer");
require("dotenv").config();

// register/signup
exports.register = async (req, res) => {
try {
const isExisting = await User.findOne({ email: req.body.email })
if (isExisting) {
throw new Error("Already an account with this email. Try a new one!")
}
const hashedPassword = await bcrypt.hash(req.body.password, 10);
const newUser = await User.create({ ...req.body, password: hashedPassword })
const { password, ...others } = newUser._doc
const token = jwt.sign({ id: newUser._id, isAdmin: newUser.isAdmin }, process.env.JWT_SECRET, { expiresIn: "5h" })

return res.status(201).json({ others, token })
} catch (error) {
return res.status(500).json(error.message)
try {
const isExisting = await User.findOne({ email: req.body.email });
if (isExisting) {
throw new Error("Already an account with this email. Try a new one!");
}
}
const hashedPassword = await bcrypt.hash(req.body.password, 10);
const newUser = await User.create({
...req.body,
password: hashedPassword,
});
const { password, ...others } = newUser._doc;
const token = jwt.sign(
{ id: newUser._id, isAdmin: newUser.isAdmin },
process.env.JWT_SECRET,
{ expiresIn: "5h" }
);

return res.status(201).json({ others, token });
} catch (error) {
return res.status(500).json(error.message);
}
};

// login
exports.login = async (req, res) => {
try {
const user = await User.findOne({ email: req.body.email })
if (!user) {
throw new Error("User credentials are wrong!")
}
try {
const user = await User.findOne({ email: req.body.email });
if (!user) {
throw new Error("User credentials are wrong!");
}

const comparePass = await bcrypt.compare(req.body.password, user.password)
if (!comparePass) {
throw new Error("User credentials are wrong!")
}
const comparePass = await bcrypt.compare(req.body.password, user.password);
if (!comparePass) {
throw new Error("User credentials are wrong!");
}

const { password, ...others } = user._doc
const token = jwt.sign({ id: user._id, isAdmin: user.isAdmin }, process.env.JWT_SECRET, { expiresIn: "5h" })
const { password, ...others } = user._doc;
const token = jwt.sign(
{ id: user._id, isAdmin: user.isAdmin },
process.env.JWT_SECRET,
{ expiresIn: "5h" }
);

return res.status(200).json({ others, token })
} catch (error) {
return res.status(500).json(error.message)
}
}
return res.status(200).json({ others, token });
} catch (error) {
return res.status(500).json(error.message);
}
};

//forgot-password
exports.forgotPassword = async(req,res)=>{
try {
console.log("Forgot password request body: ",req.body);
const { email } = req.body;
const userData = await User.findOne({email});
console.log("Email: ", email);
console.log("User data: ", userData);
if(!userData)
{
return res.status(400).json({
success: false,
msg: "Email doesn't exists!",
});
}
const randomString = Math.random().toString(36).slice(-8);
const msg= `<p>Hi ${userData.username}, please click <a href="http://localhost:5173/reset-password?token=${randomString}">here</a> to reset your password.</p>`
const PasswordReset = await passwordReset({
user_id: userData._id,
token: randomString
})
await PasswordReset.save();
mailer.sendMail(userData.email, "Reset Password", msg);
return res.status(201).json({
success: true,
msg: 'Reset Password Link sent to your mail, please check!'
})
} catch (error) {
return res.status(400).json({
success: false,
msg: error.message
});
exports.forgotPassword = async (req, res) => {
try {
console.log("Forgot password request body: ", req.body);
const { email } = req.body;
const userData = await User.findOne({ email });
console.log("Email: ", email);
console.log("User data: ", userData);
if (!userData) {
return res.status(400).json({
success: false,
msg: "Email doesn't exists!",
});
}
}
const randomString = Math.random().toString(36).slice(-8);
const msg = `<p>Hi ${userData.username}, please click <a href="http://localhost:5173/reset-password?token=${randomString}">here</a> to reset your password.</p>`;
const PasswordReset = await passwordReset({
user_id: userData._id,
token: randomString,
});
await PasswordReset.save();
mailer.sendMail(userData.email, "Reset Password", msg);
return res.status(201).json({
success: true,
msg: "Reset Password Link sent to your mail, please check!",
});
} catch (error) {
return res.status(400).json({
success: false,
msg: error.message,
});
}
};

// reset-password
exports.resetPassword = async(req,res)=>{
try {
const {token} = req.query.token;
console.log("Token: ",token);
const resetData = await passwordReset.findOne({token: req.query.token});
console.log("Reset data: ",resetData);
if(!resetData)
{
return res.status(404)
}
return res.status(200).json({resetData})
} catch (error) {
return res.status(404).json(error.message)
exports.resetPassword = async (req, res) => {
try {
const { token } = req.query;
console.log("Token: ", token);
const resetData = await passwordReset.findOne({ token: req.query.token });
console.log("Reset data: ", resetData);
if (!resetData) {
return res.status(404).send("invalid token");
}
}
return res.status(200).json({ resetData });
} catch (error) {
return res.status(404).json(error.message);
}
};

// exports.updatePassword = async(req,res)=> {
// try {
Expand All @@ -104,7 +113,7 @@ exports.resetPassword = async(req,res)=>{

// const {c_password}=req.body.c_password;
// console.log("Confirm Password: ",c_password);

// if(password!=c_password)
// {
// return res.status(401).json({msg: "Passwords aren't matching"})
Expand All @@ -125,38 +134,41 @@ exports.resetPassword = async(req,res)=>{
// } catch (error) {
// console.log('Error in updating the password : ', error);
// return res.status(404).json({msg: "Error"});
// }
// }
// }

exports.updatePassword = async(req,res)=> {
try {
const {password,c_password} = req.body;
let {token}= req.query
token = decodeURIComponent(token)
console.log(token);
console.log(password)
console.log(c_password);
// const resetData = await passwordReset.findOne({user_id});
const resetData = await passwordReset.findOne({token: token});
console.log("Reset Data: ",resetData);
// if(password!=c_password)
// {
// return res.status(401).json({msg: "Passwords aren't matching"})
// }
const hashedPassword=await bcrypt.hash(c_password,10);
await User.findByIdAndUpdate({_id: resetData.user_id},{
$set:{
password: hashedPassword
}
})
const userData = await User.findById({_id: resetData.user_id});
console.log("User Data: ",userData);
const msg= `<p>Dear ${userData.username}, This is to confirm that the password for your account has been successfully changed.</p>`
mailer.sendMail(userData.email,"Password updated successful",msg);
await passwordReset.deleteMany({_id: resetData.user_id})
return res.status(200).json({ msg: "Password updated successfully" });
} catch (error) {
console.log('Error in updating the password : ', error);
return res.status(404).json({msg: "Error"});
}
}
exports.updatePassword = async (req, res) => {
try {
const { password, c_password } = req.body;
let { token } = req.query;
token = decodeURIComponent(token);
console.log(token);
console.log(password);
console.log(c_password);
// const resetData = await passwordReset.findOne({user_id});
const resetData = await passwordReset.findOne({ token: token });
console.log("Reset Data: ", resetData);
// if(password!=c_password)
// {
// return res.status(401).json({msg: "Passwords aren't matching"})
// }
const hashedPassword = await bcrypt.hash(c_password, 10);
await User.findByIdAndUpdate(
{ _id: resetData.user_id },
{
$set: {
password: hashedPassword,
},
}
);
const userData = await User.findById({ _id: resetData.user_id });
console.log("User Data: ", userData);
const msg = `<p>Dear ${userData.username}, This is to confirm that the password for your account has been successfully changed.</p>`;
mailer.sendMail(userData.email, "Password updated successful", msg);
await passwordReset.deleteMany({ _id: resetData.user_id });
return res.status(200).json({ msg: "Password updated successfully" });
} catch (error) {
console.log("Error in updating the password : ", error);
return res.status(404).json({ msg: "Error" });
}
};
6 changes: 5 additions & 1 deletion server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"main": "app.js",
"scripts": {
"start": "nodemon app.js",
"test": "echo \"Error: no test specified\" && exit 1"
"test": "jest --watchAll --verbose"
},
"author": "Anup Khismatrao",
"license": "MIT",
Expand All @@ -14,11 +14,15 @@
"cors": "^2.8.5",
"dotenv": "^16.3.1",
"express": "^4.18.2",
"jest": "^29.7.0",
"jsonwebtoken": "^9.0.2",
"mongoose": "^7.4.1",
"morgan": "^1.10.0",
"multer": "^1.4.5-lts.1",
"nodemailer": "^6.9.8",
"nodemon": "^3.0.1"
},
"devDependencies": {
"supertest": "^6.3.4"
}
}
Loading

0 comments on commit 8226234

Please sign in to comment.