From 98e85671672cfef6226fa22df1f98ee83b0a2a09 Mon Sep 17 00:00:00 2001 From: saras-69 <115482884+saras-69@users.noreply.github.com> Date: Mon, 4 Nov 2024 03:08:51 +0530 Subject: [PATCH 1/2] add password recovery feature --- app.js | 53 +++++++++------------- controllers/users.js | 19 ++++++-- routes/user.js | 7 ++- views/users/forgot.ejs | 51 ++++++++++++++++++++++ views/users/login.ejs | 99 ++++++++++++++++++++++-------------------- 5 files changed, 145 insertions(+), 84 deletions(-) create mode 100644 views/users/forgot.ejs diff --git a/app.js b/app.js index 600621e..7a0c994 100644 --- a/app.js +++ b/app.js @@ -1,4 +1,4 @@ -if(process.env.NODE_ENV != "production"){ +if (process.env.NODE_ENV != "production") { require('dotenv').config(); } const express = require("express"); @@ -16,43 +16,42 @@ const passport = require("passport"); const LocalStrategy = require("passport-local"); const User = require("./models/user.js"); const userRouter = require("./routes/user.js"); -/* if you want to run the project and do not have .env files configured , please uncomment the next -two commented codes and comment down this code await mongoose.connect(dbUrl); You project will run succesfully*/ const MONGO_URL = "mongodb://mongo:27017/wanderlust"; // used with docker // const MONGO_URL = "mongodb://127.0.0.1:27017/wanderlust"; // use for local db -const dbUrl =process.env.ATLASDB_URL; +const dbUrl = process.env.ATLASDB_URL; + main() .then(() => { console.log("connected to DB"); }).catch((err) => { console.log(err); }); -async function main(){ + +async function main() { await mongoose.connect(MONGO_URL); // await mongoose.connect(dbUrl); } -app.set("view engine","ejs"); +app.set("view engine", "ejs"); app.set("views", path.join(__dirname, "views")); -app.use(express.urlencoded({extended:true})); +app.use(express.urlencoded({ extended: true })); app.use(methodOverride("_method")); app.engine('ejs', ejsMate); -app.use(express.static(path.join(__dirname,"/public"))); +app.use(express.static(path.join(__dirname, "/public"))); + const sessionOptions = { secret: "mysupersecretcode", resave: false, saveUninitialized: true, cookie: { - expires: Date.now()+7*24*60*60*1000, - maxAge: 7*24*60*60*1000, + expires: Date.now() + 7 * 24 * 60 * 60 * 1000, + maxAge: 7 * 24 * 60 * 60 * 1000, httpOnly: true, }, }; -/*app.get("/", (req,res) => { - res.send("Hi,I am root"); -});*/ + app.use(session(sessionOptions)); app.use(flash()); app.use(passport.initialize()); @@ -61,19 +60,19 @@ passport.use(new LocalStrategy(User.authenticate())); passport.serializeUser(User.serializeUser()); passport.deserializeUser(User.deserializeUser()); -app.use((req,res,next) =>{ +app.use((req, res, next) => { res.locals.success = req.flash("success"); res.locals.error = req.flash("error"); res.locals.currUser = req.user; - //console.log(success); next(); }); -app.use("/listings",listingRouter); -app.use("/listings/:id/reviews",reviewRouter); -app.use("/",userRouter); +app.use("/listings", listingRouter); +app.use("/listings/:id/reviews", reviewRouter); +app.use("/", userRouter); + app.get('/privacy', (req, res) => { - res.render('privacy'); // This should be placed before the app.all("*") block + res.render('privacy'); }); // Catch-all route for undefined paths @@ -81,24 +80,12 @@ app.all("*", (req, res, next) => { next(new ExpressError(404, "Page Not Found!")); }); - -//if any of the incomming request does not match then throw this error -app.all("*",(req,res,next) =>{ - next(new ExpressError(404,"Page Not Found!")); -}); -//error handling is done by middleware -app.use((err,req,res,next) =>{ - let {statusCode=500,message="Something went wrong!"}=err; - res.status(statusCode).render("error.ejs",{message}); - //res.status(statusCode).send(message); -}); - +// Error handling middleware app.use((err, req, res, next) => { - console.log(err); // Log the full error to see what’s causing the issue let { statusCode = 500, message = "Something went wrong!" } = err; res.status(statusCode).render("error.ejs", { message }); }); -app.listen(8080,()=>{ +app.listen(8080, () => { console.log("Server is listening to port 8080"); }); \ No newline at end of file diff --git a/controllers/users.js b/controllers/users.js index 51e4059..feedf0b 100644 --- a/controllers/users.js +++ b/controllers/users.js @@ -5,7 +5,7 @@ const renderSignupForm = (req, res) => { res.render("users/signup.ejs"); }; -const signup = async (req, res) => { +const signup = async (req, res, next) => { try { // Check for validation errors const errors = validationResult(req); @@ -53,10 +53,23 @@ const logout = (req, res, next) => { }); }; +// Render the password recovery form +const renderForgotPasswordForm = (req, res) => { + res.render('users/forgot.ejs'); +}; + +// Handle the password recovery form submission +const forgotPassword = (req, res) => { + req.flash('info', 'If an account with that email exists, you will receive an email with instructions to reset your password.'); + res.redirect('/forgot'); +}; + module.exports = { renderSignupForm, signup, renderLoginForm, login, - logout -}; + logout, + renderForgotPasswordForm, + forgotPassword +}; \ No newline at end of file diff --git a/routes/user.js b/routes/user.js index 04a369f..4f338fd 100644 --- a/routes/user.js +++ b/routes/user.js @@ -1,6 +1,5 @@ const express = require("express"); const router = express.Router(); -const User = require("../models/user.js"); const wrapAsync = require("../utils/wrapAsync.js"); const passport = require("passport"); const { saveRedirectUrl } = require("../middleware.js"); @@ -30,4 +29,10 @@ router router.get("/logout", saveRedirectUrl, userController.logout); +// Add routes for forgot password +router + .route("/forgot") + .get(userController.renderForgotPasswordForm) + .post(wrapAsync(userController.forgotPassword)); + module.exports = router; \ No newline at end of file diff --git a/views/users/forgot.ejs b/views/users/forgot.ejs new file mode 100644 index 0000000..4ee0fe3 --- /dev/null +++ b/views/users/forgot.ejs @@ -0,0 +1,51 @@ +<% layout("/layouts/boilerplate") -%> +