Skip to content
This repository was archived by the owner on Oct 30, 2022. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from 4 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
99 changes: 99 additions & 0 deletions server/controllers/pwd.controllers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
const asyncHandler = require('express-async-handler');
const User = require('../models/user.modal');
const nodemailer = require('nodemailer');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');

module.exports.forgotPwdController = asyncHandler(async (req, res, next) => {
const { email } = req.body;
const user = await User.findOne({ email });

if (!user) {
res.status(400).send({ status: 'user not found' });
throw new Error('User not found');
}

const token = await user.createPWDresetToken();
const resetURL = `${req.protocol}://${req.get(
'host'
)}/api/_reset_password/${token}`;

var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: process.env.OUR_EMAIL,
pass: process.env.EMAIL_PASS,
},
from: 'codesync.live',
});

var mailOptions = {
from: process.env.OUR_EMAIL,
to: user.email,
cc: 'codedeeper.work@gmail.com',
subject: 'Codedeeper password reset Token',
html: `<p>Hello , ${user.name} here is your token link. <a href="${resetURL}">${resetURL}</a> to reset the password</p>`,
text: `<p>Hello , ${user.name} here is your token link. <a href="${resetURL}">${resetURL}</a> to reset the password</p>`,
};

// transporter.sendMail(mailOptions, function (error, info) {
// if (error) {
// console.log(error);
// res.status(200).send({
// status: 'failed',
// });
// } else {
// console.log('Email sent: ' + info.response);
// if (process.env.NODE_ENV == 'development') {
// res.status(200).send({
// status: 'success',
// resetURL,
// });
// } else {
// res.status(200);
// }
// }
// });

/**
* @TODO: check nodemailer authentication and
* test this in development before building for production
*/
res.status(200).send({
resetURL,
});
});

module.exports.resetPasswordController = asyncHandler(async (req, res) => {
const reset_token = req.params.JWT_TOKEN;
try {
const payload = jwt.verify(reset_token, process.env.JWT_SECRET_KEY);
const { password, confirmpassword } = req.body;
if (!password || !confirmpassword)
throw new Error('Password should be provided!');

if (password !== confirmpassword) throw new Error("Password doesn't match");

const user = await User.findById(payload.id);
if (!user) throw new Error('No user exists with this id');

if (user.passwordChangedAt && user.passwordChangedAt > payload.iat * 1000)
throw new Error(
'Please raise a new Reset Request,this token was used earlier'
);

const newPassword = await bcrypt.hash(password, 12);
user.set({ password: newPassword, passwordChangedAt: new Date() });
await user.save();

return res.send({
payload,
user,
elapsed_time: payload.exp - parseInt(Date.now() / 1000),
});
} catch (err) {
res.status(400).send({
err: err.message,
});
}
});
62 changes: 36 additions & 26 deletions server/models/user.modal.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,39 @@
const mongoose = require("mongoose");
const mongoose = require('mongoose');
const jwt = require('jsonwebtoken');

const User = mongoose.model("User", {
name: {
type: "String",
required: true,
},
email: {
type: "String",
required: true,
},
password: {
type: "String",
required: true,
},
id: {
type: "String",
},
googleLogin: {
type: "Boolean",
default: false,
},
imageUrl: {
type: "String",
}
});
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
passwordChangedAt: Date,
id: {
type: String,
},
googleLogin: {
type: Boolean,
default: false,
},
imageUrl: {
type: String,
},
});

userSchema.methods.createPWDresetToken = async function () {
return jwt.sign(
{ email: this.email, id: this._id },
process.env.JWT_SECRET_KEY,
{ expiresIn: 600 }
);
};

const User = mongoose.model('User', userSchema);
module.exports = User;
12 changes: 12 additions & 0 deletions server/routes/pwd.route.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
const express = require('express');
const {
forgotPwdController,
resetPasswordController,
} = require('../controllers/pwd.controllers');

const router = express.Router();

router.get('/_reset_password/:JWT_TOKEN', resetPasswordController);
router.post('/_forgot_password', forgotPwdController);

module.exports = router;
8 changes: 8 additions & 0 deletions server/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ app.use(express.json());
app.get("/", (req, res) => {
res.send("API IS RUNNING")
})

app.use('/api',require('./routes/pwd.route'))
app.use('/api/room/', require('./routes/room.route'));
app.use('/api/user/', require('./routes/user.route'));

Expand Down Expand Up @@ -161,6 +163,12 @@ app.post('/sendMail', (req, res) => {
// })

// }

// app.use("*",(error,req,res,next)=>{
// res.send({
// error:error.message
// })
// })
server.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})