-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.js
188 lines (136 loc) · 4.74 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
if (process.env.NODE_ENV != "production") {
require('dotenv').config()
// console.log(process.env) // remove this after you've confirmed it is working
}
const express = require("express");
const app = express();
const path = require("path");
const mongoose = require("mongoose");
const methodOverride = require("method-override");
// const ejsMate = require("ejs-mate");
const wrapAsync = require("./utils/wrapAsync.js");
const ExpressError = require("./utils/ExpressError.js");
const session = require("express-session");
const MongoStore = require('connect-mongo');
const flash = require("connect-flash");
const passport = require("passport");
const LocalStrategy = require("passport-local");
const User = require("./Models/user.js");
const reviewRouter = require("./routes/review.js");
const listingRouter = require("./routes/listing.js");
const userRouter = require("./routes/user.js");
// const dbUrl = 'mongodb://127.0.0.1:27017/wanderlust';
// const dbUrl = process.env.ATLASDB_URL;
async function main() {
await mongoose.connect(process.env.ATLASDB_URL);
}
main().then(() => {
console.log("Connected With WanderLust DB");
})
.catch((err) => {
console.log(err);
});
const store = MongoStore.create({
mongoUrl: process.env.ATLASDB_URL,
crypto: {
secret: process.env.SECRET,
},
touchAfter: 24 * 3600, // 24 Hours = 1 Day
});
store.on("error", () => {
console.log("Error in MongoSession Store", error);
});
const sessionOptions = {
// store : store,
store,
secret: process.env.SECRET,
resave: false,
saveUninitialized: true,
cookie: {
expires: Date.now() + 7 * 24 * 60 * 60 * 1000, //today date ms + 7 day millisecond
maxAge: 7 * 24 * 60 * 60 * 1000,
httpOnly: true, //used for security from XSS attack
}
};
app.use(session(sessionOptions));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.use((req, res, next) => {
res.locals.successMsg = req.flash("success");
res.locals.errorMsg = req.flash("error");
res.locals.currUser = req.user;
next();
});
//Middlewares
app.use(express.static(path.join(__dirname, "public")));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(methodOverride("_method"));
//setting for view engine
app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "views"));
// app.engine("ejs", ejsMate);
//Endpoints (Routes)
app.get("/", (req, res) => {
res.render("./list/index.ejs", { layouts: false });
});
app.use("/listings/:id/reviews", reviewRouter);
app.use("/listings", listingRouter);
app.use("/", userRouter);
// (req,res,next)=>{
// if(req.isAuthenticated()) {
// console.log('User logged in successfully');
// return next();
// }else{
// req.flash("error","You Must Be Logged In Before Using This !");
// res.redirect("/login");
// }
// }
// Google Auth
require("./auth/google.js");
app.get("/auth/google",
passport.authenticate('google', { scope: ['profile', 'email'] })
);
app.get("/auth/google/callback",
passport.authenticate('google', {
failureRedirect: "/signup", failureFlash: true,
}),(req,res)=>{
res.redirect(`/user/profile/${req.user._id}`);
}
);
app.all("*", (req, res, next) => {
next(new ExpressError(404, "Page Not Found."));
});
// Error Handling Middleware
app.use((err, req, res, next) => {
let { status = 500, message = "Something Went Wrong." } = err;
// res.status(status).send(`<h1>${message}</h1>`);
if (message.substring(0, 23) === "Cast to ObjectId failed") {
req.flash("error", "Listing You requested for does not exist !");
res.redirect("/listings");
}
res.status(status).render("./list/error.ejs", { message });
});
// const portAddress = process.env.HOST || 3000;
// app.listen(portAddress, () => {
// console.log(`Server is Listing On Port ${portAddress}.`);
// });
// Use PORT provided in environment or default to 3000
const port = process.env.PORT || 3000;
// Listen on `port` and 0.0.0.0
app.listen(port, "0.0.0.0", function () {
console.log(`Server is Listing On Port ${port}`);
});
// Extra Code (But Helpful)
// app.get("/demouser", wrapAsync(async (req, res) => {
// // let fakeUser = new User({
// // email:"[email protected]",
// // username:"demouser007",
// // });
// // let registeredUser = await User.register(fakeUser,"mypassword123"); // Convenience method to register a new user instance with a given password. Checks if username is unique.
// res.send(registeredUser);
// }));