-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
96 lines (79 loc) · 2.05 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
// dotenv
require("dotenv").config();
// Plugins
const path = require("path");
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const session = require("express-session");
const MongoStore = require("connect-mongo");
const flash = require("connect-flash");
const csrf = require("csurf");
const { CronJob } = require("cron");
const errorController = require("./controllers/error");
// database things
const uri = process.env.URI;
const port = +process.env.PORT;
const base = process.env.BASE;
// Config app middlewares
const app = express();
const store = MongoStore.create({
mongoUrl: uri,
autoRemove: "native",
ttl: 7200, //2 hours
collectionName: "sessions",
});
const csrfProtection = csrf();
// view engine
app.set("view engine", "ejs");
// config body-parser
app.use(bodyParser.urlencoded({ extended: false }));
// serve file stactically
app.use(express.static(path.join(__dirname, "public")));
// session
app.use(
session({
secret: "my secrets",
saveUninitialized: false,
resave: false,
store: store,
})
);
// others middlewares
app.use(csrfProtection);
app.use(flash());
// local res
app.use((req, res, next) => {
res.locals.isAuthenticated = req.session.isLoggedIn;
res.locals.name = undefined;
res.locals.level = 0;
if (req.session.user) {
res.locals.name = req.session.user.name;
res.locals.level = req.session.user.level;
}
res.locals.csrfToken = req.csrfToken();
next();
});
// routes
const authRoutes = require("./routes/auth");
const pageRoutes = require("./routes/page");
const adminRoutes = require("./routes/admin");
app.use(pageRoutes);
app.use("/auth", authRoutes);
app.use("/admin", adminRoutes);
// error pages
app.use(errorController.get404);
app.use((error, req, res, next) => {
console.log(error);
res.status(500).render("errors/500", {
pageTitle: "500",
error: error,
});
});
mongoose
.connect(uri)
.then((result) => {
console.log("LISTENING...");
app.listen(port);
})
.catch((error) => console.log(error));