This repository has been archived by the owner on Aug 19, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
196 lines (168 loc) · 4.48 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
// Setting up Env Vars
import dotenv from "dotenv";
if (process.env.NODE_ENV !== "production") {
dotenv.config();
}
const PORT = process.env.PORT || 5000;
const CLIENT = `http://localhost:${PORT}`;
const MONGOD_PORT = process.env.DB_PORT || 27017;
const secret = process.env.SECRET || "whatawonderfullsecret!"
// const secure = process.env.SECURE_COOKIES === "true" || false;
import express from "express";
import mongoose from "mongoose";
// Path
import path from "path";
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Session
import session from "express-session";
import MongoStore from "connect-mongo";
// Passport.js
import passport from "passport";
import LocalStrategy from "passport-local"
import mongoSanitize from "express-mongo-sanitize"
import helmet from "helmet";
import User from "./models/user.js";
// API
import cors from "cors";
import APIRoutes from "./API/api.js"
// DB CONNECTION
const dbUrl = process.env.DB_URL || "mongodb://localhost:" + MONGOD_PORT + "/managerDB"
mongoose.connect(dbUrl, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => {
console.log("Connection to the Database was established successfully!");
})
.catch(error => {
console.log("An ERROR occurred while attempting to connect to the Database");
console.log(error);
})
mongoose.connection.once("open", async () => {
if (await User.countDocuments().exec() < 1) {
let email = process.env.ADMIN_EMAIL || "";
let name = process.env.ADMIN_USERNAME || "admin"
let password = process.env.ADMIN_PASSWORD || "admin";
let phoneNumber = process.env.ADMIN_PHONE_NUMBER || "";
let accessLevel = "Administrator";
try {
const user = new User({ name: name, email: email, phoneNumber: phoneNumber, accessLevel: accessLevel, username: name });
await User.register(user, password);
console.log("username: " + name)
console.log("password: " + password)
}
catch (e) {
console.log(e)
}
}
})
// Session Configuration
const store = MongoStore.create({
mongoUrl: dbUrl,
touchAfter: 24 * 60 * 60,
crypto: {
secret
}
});
const sessionConfig = {
store,
name: "managerSession",
secret,
resave: false,
saveUninitialized: true,
cookie: {
httpOnly: false,
expires: Date.now() + (1000 * 60 * 60 * 24),
maxAge: (1000 * 60 * 60 * 24),
}
}
//
const app = express();
// Parsing JSON
app.use(express.urlencoded({ extended: true }));
// Configuring Session
app.use(session(sessionConfig));
// Helmet
app.use(helmet());
// Mongo Sanitize
app.use(mongoSanitize({
replaceWith: '_'
}));
app.use(express.json());
app.use(cors({
origin: CLIENT,
methods: "GET,POST,PUT,PATCH,DELETE",
credentials: true,
}));
// Passport Session Manager
app.use(passport.initialize());
app.use(passport.session());
// Passport Configuration
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
// Configuring Helemt's Content Security Policy
const scriptSrcUrls = [
"https://kit.fontawesome.com/8204973c77.js",
];
const styleSrcUrls = [
"https://fonts.googleapis.com",
];
const connectSrcUrls = [
"https://ka-f.fontawesome.com/"
];
const fontSrcUrls = [
"https://fonts.googleapis.com",
"https://fonts.gstatic.com",
];
const mediaSrcUrls = [
];
app.use(
helmet.contentSecurityPolicy({
directives: {
defaultSrc: [],
connectSrc: ["'self'", ...connectSrcUrls],
scriptSrc: ["'unsafe-inline'", "'self'", ...scriptSrcUrls],
styleSrc: ["'self'", "'unsafe-inline'", ...styleSrcUrls],
workerSrc: ["'self'", "blob:"],
childSrc: ["blob:"],
objectSrc: [],
mediaSrc: [
"'self'", ...mediaSrcUrls],
imgSrc: [
"'self'",
"blob:",
"data:",
],
fontSrc: ["'self'", ...fontSrcUrls],
},
})
);
// Main Middleware
app.use((req, res, next) => {
// Storing current user data
res.locals.currentUser = req.user;
next();
});
// API
app.use("/api", APIRoutes)
// Serving the Front-End
app.use(express.static("client/build"));
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
});
// E R R O R
app.use((err, req, res, next) => {
console.log("! ! ! E R R O R ! ! !");
const { statusCode = 500 } = err;
if (!err.message) err.message = "Oh No, Something Went Wrong!"
console.log(err);
console.log(err.message);
return res.status(statusCode).json({ error: err.message });
});
// Start Listening
app.listen(PORT, () => {
console.log(`Server has started on PORT: ${PORT}`);
})