This repository has been archived by the owner on Aug 11, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
78 lines (67 loc) · 2.12 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
const express = require("express");
const logger = require("morgan");
const session = require("express-session");
const passport = require("passport");
const helmet = require("helmet");
const compression = require("compression");
const redis = require("redis");
const RedisStore = require("connect-redis")(session);
const crypto = require("crypto");
const path = require("path");
const cors = require("cors");
const csurf = require("csurf");
const cookieParser = require("cookie-parser");
const routes = require("./routes");
const client = redis.createClient(process.env.REDIS_URL);
const app = express();
// Views and static files
app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "views"));
app.use(express.static("public"));
// Middleware
app.use(logger("dev"));
app.use(helmet());
app.use(cors());
app.use(compression());
app.use(express.json());
app.use(express.urlencoded());
app.use(express.static(path.join(__dirname, "react_build")));
app.use(cookieParser());
app.use(csurf({ cookie: true }));
app.use(
session({
store: new RedisStore({ client }),
secret: process.env.SECRET || crypto.randomBytes(20).toString("hex"),
cookie: {
secure: false,
httpOnly: true,
},
})
);
// Passport
require("./config/passport");
app.use(passport.initialize());
app.use(passport.session());
// Add auth info and csrfToken to template locals
app.use((req, res, next) => {
res.locals.authenticated = req.isAuthenticated() || false;
res.locals.user = req.user || {};
res.locals.csrfToken = req.csrfToken();
next();
});
app.use("/", routes);
app.get("*", (_, res) => res.render("404"));
app.use((err, req, res, _) => {
if (process.env.NODE_ENV !== "production") {
console.log(err);
}
// Set statusCode to 500 if it isn't already there
err.statusCode = err.statusCode || 500;
err.message = err.message || err.name || "Internal Server Error";
err.code = err.code || err.name || "500_INTERNAL_SERVER_ERR";
res.locals.authenticated = req.isAuthenticated() || false;
res.locals.user = req.user;
res.render("error", { code: err.statusCode, message: err.message });
return;
});
module.exports = app;