-
Notifications
You must be signed in to change notification settings - Fork 49
/
app.js
244 lines (197 loc) · 6.67 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
if(process.env.NODE_ENV!="production") { //not to deploy .env file while uploading to git
require('dotenv').config();
}
const port = 8000;
const express =require("express");
const app=express();
const mongoose=require("mongoose");
const listing=require("./models/listing.js");
const path=require("path");
const methodOverride=require("method-override");
const ejsMate=require("ejs-mate");
const reviews=require("./models/reviews.js");
const asyncwrap=require("./utils/error.js");
const expressError=require("./utils/expressError.js");
const multer = require('multer')
const {storage}=require("./cloudConfig.js")
const upload = multer({storage}); //destination =cloud storage
const cookieparser=require("cookie-parser");
const session=require("express-session");
const MongoStore = require('connect-mongo'); //to connect mongo to cloud database
const flash = require("connect-flash");
const passport=require("passport");
const localStrategy=require("passport-local");
const User=require("./models/user.js");
const { isLoggedIn } = require("./middlewares/middleware.js");
const {saveRedirectUrl}=require("./middlewares/middleware.js");
const {isOwner,isAuthor}=require("./middlewares/middleware.js");
const {index, newpost, createpost, editpost, saveEditpost,search, deletepost, showPost, signup}=require("./controllers/listing.js");
const { deleteReview, reviewPost } = require("./controllers/reviews.js");
const cors = require('cors'); // CORS added
// Use CORS for all routes
app.use(cors({
origin: 'http://your-frontend-domain.com', // Replace with your frontend domain
methods: ['GET', 'POST', 'PUT', 'DELETE'],
credentials: true
}));
app.use(cookieparser());
const dbUrl=process.env.ATLAS_DB_TOKEN;
async function main() {
await mongoose.connect(dbUrl);
console.log("database connected");
}
main().catch(err => console.log(err));
app.set("views", path.join(__dirname, "views")); //to run file from everywhere
app.set("view engine","ejs");
app.use(express.static(path.join(__dirname, "/public"))); //to use files in public folder
app.use(methodOverride('_method'));
app.use(express.urlencoded({extended:true})); //for parsing the data
app.engine('ejs', ejsMate); //to create ejs template for every page ex. footer,navbar
const store =MongoStore.create({
mongoUrl:dbUrl,
crypto:{
secret:process.env.SECRET
},
touchAfter:24*3600,
});//to store info of session even after refresh
store.on("error", ()=>{
console.log("error in mongo session store", err);
})
const sessionOptions={
store,
secret:process.env.SECRET,
resave:false,
saveUninitialized: true,
cookie:{
expires:Date.now() +7*24*60*60*1000,
maxAge:7*24*60*60*1000,
httpOnly : true,
},
};
app.use(session(sessionOptions)); //used to save users login in ame browser always, has session id
app.use(flash());
app.use(passport.initialize());
app.use(passport.session()); //to identify users from page to page
passport.use(new localStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser()); //used in login
passport.deserializeUser(User.deserializeUser()); //used for logout
//flash middleware
app.use((req, res, next) => {
res.locals.success = req.flash('success');
res.locals.error = req.flash('error');
res.locals.currUser=req.user; //storecurrent session user info in currUser
// console.log(res.locals);
next();
});
//About us page
app.get('/about',asyncwrap ( async (req, res) => {
try {
res.render('about');
} catch (err) {
console.error(err);
res.status(500).send('Internal Server Error');
}
}));
//terms and conditions page
app.get('/terms',asyncwrap ( async (req, res) => {
try {
res.render('terms');
} catch (err) {
console.error(err);
res.status(500).send('Internal Server Error');
}
}));
//Privacy policy page
app.get('/privacy',asyncwrap ( async (req, res) => {
try {
res.render('privacy');
} catch (err) {
console.error(err);
res.status(500).send('Internal Server Error');
}
}));
//API
//signup
app.get("/signup",asyncwrap (async(req,res) => {
res.render("signup.ejs");
}));
app.post('/signup', asyncwrap(async (req, res, next) => {
const { username, email, password } = req.body;
// Check for missing fields
if (!username || !password) {
req.flash('error', 'Username and password are required');
return res.redirect('/signup');
}
try {
const newUser = new User({ username, email });
await User.register(newUser, password);
req.login(newUser, (err) => {
req.flash('success', 'Welcome! Account created successfully.');
res.redirect('/listing');
});
} catch (err) {
req.flash('error', err.message);
res.redirect('/signup');
}
}));
//login
app.route("/login")
.get( asyncwrap ((req,res) =>{
res.render("login.ejs");
}))
.post(
saveRedirectUrl,
passport.authenticate("local", {
failureRedirect: "/login",
failureFlash: true
}), (req, res) => {
req.flash("success", "Welcome back to wanderlust!");
let redirect=res.locals.redirectUrl||"/listing";
res.redirect(redirect); // Redirect to a route that will display the message
});
//logout
app.get("/logout",(req,res,next) =>{
req.logout((err) =>{
if(err) {
return next(err);
}
req.flash("success","You logged out successfuly!");
res.redirect("/listing");
})
});
//define listing conroller
//BUG FIX
const listingController = require('./controllers/listing.js');
// Create new listing form route
// app.get("/new",isLoggedIn, asyncwrap(newpost));
app.get("/listing/new", isLoggedIn, asyncwrap(listingController.newpost));
//index route
app.get("/listing",asyncwrap(index));
//create post
app.post("/listing", upload.array('listing[image]', 10), isLoggedIn, asyncwrap(createpost));
//search the listings
app.post("/listing/search",asyncwrap(search));
//edit the listings
app.get("/listing/:id/edit",isLoggedIn,isOwner,asyncwrap(editpost));
//save the updated listing
app.put('/listing/:id', isLoggedIn,isOwner,upload.array('listing[image]'), asyncwrap(saveEditpost));
//delete listing
app.delete("/listing/:id",isLoggedIn,isOwner,asyncwrap(deletepost));
app.get('/listing/:id', asyncwrap(showPost));
//review submit route
app.post("/listing/:id/review", isLoggedIn, asyncwrap(reviewPost));
//delete reviews
app.delete("/listing/:id/review/:rid",isLoggedIn,isAuthor,asyncwrap(deleteReview));
//for all invalid route error
app.use("*",(req,res,next) =>{
res.render("not_found.ejs");
// next(new expressError(404,"page not found"));
})
//error handling
app.use((err,req,res,next) =>{
let{status=500,msg="Something went wrong"}=err;
res.render("error.ejs",{msg,status});
})
app.listen(port, () =>{
console.log("server is listening on port", port);
});