-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
93 lines (79 loc) · 2.26 KB
/
server.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
import express from "express";
import mongoose from "mongoose";
import session from "express-session";
import flash from "connect-flash";
import passport from "./config/passport.js";
import methodOverride from "method-override";
import path from "path";
import { fileURLToPath } from "url";
import dotenv from "dotenv";
import User from "./models/User.js";
dotenv.config();
// Import Routes
import userRoutes from "./routes/users.js";
import postRoutes from "./routes/posts.js";
import connectDb from "./config/db.js";
// Initialize app
const app = express();
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Connect to MongoDB
connectDb();
// Middleware
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(methodOverride("_method"));
app.use(express.static("public"));
// Set static folder
app.use(express.static(path.join(__dirname, "public")));
// Set EJS as view engine
app.set("view engine", "ejs");
// Express session
app.use(
session({
secret: "secret",
resave: true,
saveUninitialized: true,
})
);
// Passport middleware
app.use(passport.initialize());
app.use(passport.session());
// Connect flash
app.use(flash());
// Global variables for flash messages
app.use((req, res, next) => {
res.locals.success_msg = req.flash("success_msg");
res.locals.error_msg = req.flash("error_msg");
res.locals.error = req.flash("error");
res.locals.loggedIn = req.isAuthenticated();
next();
});
// Middleware to ensure user is authenticated
const ensureAuthenticated = (req, res, next) => {
if (req.isAuthenticated()) {
return next();
}
req.flash("error_msg", "You need to log in to view this page");
res.redirect("/users/login");
};
// Routes
app.use("/users", userRoutes);
app.use("/posts", ensureAuthenticated, postRoutes);
// Home route - Protected
app.get("/", (req, res) => {
res.render("landing");
});
app.get("/home", ensureAuthenticated, async (req, res) => {
let admin = false;
let user = await User.findById(req.user.id);
if (user.isAdmin) {
admin = true;
}
res.render("home", { posts: [], admin });
});
// Server configuration
const PORT = process.env.PORT || 5000;
app.listen(PORT, () =>
console.log(`Server started on port http://localhost:${PORT}`)
);