-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
102 lines (84 loc) · 2.51 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
94
95
96
97
98
99
100
101
102
const express = require("express");
const path = require("path");
const mongoose = require("mongoose");
const passport = require("passport");
const session = require("express-session");
const flash = require("connect-flash");
const {
ensureAuthenticated,
isGuardian,
isAdmin,
} = require("./middlewares/auth");
require("dotenv/config");
const app = express();
const db = process.env.mongoURI;
app.set("view engine", "ejs");
// Express BodyParser
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Setting static assets directories
app.use(express.static(path.join(__dirname, "public")));
// Passport config
require("./middlewares/passport")(passport);
// Express session middleware
app.use(
session({
secret: "secret",
resave: true,
saveUninitialized: true,
})
);
// Connect flash middleware
app.use(flash());
// Passport middleware
app.use(passport.initialize());
app.use(passport.session());
// Setting Global vars for flash messages and user auth status
app.use((req, res, next) => {
res.locals.isAuthenticated = req.isAuthenticated();
res.locals.success_msg = req.flash("success_msg");
res.locals.error_msg = req.flash("error_msg");
res.locals.error = req.flash("error");
next();
});
mongoose
.connect(db, {
useUnifiedTopology: true,
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
})
.then(() => console.log(`MongoDB connected successfully`))
.catch((err) => console.log(`Error connecting mongodb ` + err));
const Notice = require("./models/Notice");
app.get("/", async (req, res) => {
const notice = await Notice.findOne({}).sort({ date: -1 });
console.log(notice);
res.render("index", { notice });
});
app.use("/auth", require("./routes/auth"));
if (process.env.NODE_ENV === "production") {
app.use(
"/guardian",
[ensureAuthenticated, isGuardian],
require("./routes/guardian")
);
app.use(
"/guardian/students",
[ensureAuthenticated, isGuardian],
require("./routes/student")
);
app.use(
"/payment",
[ensureAuthenticated, isGuardian],
require("./routes/payment")
);
app.use("/admin", [ensureAuthenticated, isAdmin], require("./routes/admin"));
} else {
app.use("/guardian", require("./routes/guardian"));
app.use("/guardian/students", require("./routes/student"));
app.use("/payment", require("./routes/payment"));
app.use("/admin", require("./routes/admin"));
}
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server is running on port ${PORT}`));