-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathapp.js
78 lines (64 loc) · 2.38 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 fileUpload = require("express-fileupload");
const cookieparser = require("cookie-parser");
const bodyParser = require("body-parser");
const cors = require("cors");
const helmet = require("helmet");
const xss = require("xss-clean");
const mongoSanitize = require("express-mongo-sanitize");
const app = express();
const { globalErrorHandler, AppError } = require("./utils/errorHandler");
//config
if (process.env.NODE_ENV !== "PRODUCTION") {
require("dotenv").config({ path: "./config/.env" });
}
app.use(cookieparser());
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(fileUpload({ useTempFiles: true }));
// logger
app.use((req, res, next) => {
console.log(`[${req.method}] : ${req.originalUrl}`);
next();
});
// enable cors
const whitelist = ["http://127.0.0.1:3000", "http://localhost:3000", process.env.CLIENT_URL, process.env.ADMIN_URL];
app.use((req, res, next) => {
const origin = req.headers.origin;
if (process.env.NODE_ENV === "prod" && whitelist.indexOf(origin) !== -1) {
return next(new AppError("CORS Error: Origin not allowed", 403));
}
res.header("Access-Control-Allow-Origin", origin);
res.header("Access-Control-Allow-Credentials", true);
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
if (req.method === "OPTIONS") {
res.header("Access-Control-Allow-Methods", "PUT, POST, PATCH, GET, HEAD, OPTIONS, DELETE");
return res.status(200).json({});
}
next();
});
// set security HTTP headers
app.use(helmet());
// sanitize request data
app.use(xss());
app.use(mongoSanitize());
const members = require("./routes/membersRoute.js");
const admin = require("./routes/adminRoute.js");
app.use("/api/admin", members);
app.use("/api/admin", admin);
//routes for general users
const userRoute = require("./routes/userRoutes.js");
const abacusRoute = require("./routes/abacusRoute.js");
const enigmaRoute = require("./routes/enigmaRoute");
app.use("/api/admin/user", userRoute);
app.use("/api/admin/abacus", abacusRoute);
app.use("/api/admin/enigma", enigmaRoute);
app.all("*", (req, res, next) => {
res.status(404).json({
status: "fail",
message: `endpoint [${req.method}] : ${req.originalUrl} not found on this server`,
});
});
app.use(globalErrorHandler);
module.exports = app;