Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
95 lines (77 loc) · 2.41 KB
/
Copy pathserver.js
File metadata and controls
95 lines (77 loc) · 2.41 KB
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
require("dotenv").config();
const express = require("express");
const path = require("path");
const cookieParser = require("cookie-parser");
const logger = require("morgan");
const cors = require("cors");
const jwtDecode = require("jwt-decode");
const mongoose = require("mongoose");
const jwt = require("express-jwt");
const csrf = require("csurf");
const bodyParser = require("body-parser");
const { hashPassword } = require("./server/utilities");
const User = require("./server/models/user.model");
const publicRoutes = require("./server/routes/public.routes");
const privateRoutes = require("./server/routes/private.routes");
const csrfProtection = csrf({ cookie: true });
const app = express();
app.use(cors());
app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, "client", "build")));
const defaultUser = async (req, res, next) => {
try {
const defaultpass = "password";
const hashedPassword = await hashPassword(defaultpass);
const userData = {
email: "admin@admin.com",
firstname: "admin",
lastname: "admin",
username: "admin",
password: hashedPassword,
role: "admin",
changepassword: true,
};
const existingUsername = await User.findOne({
username: userData.username,
}).lean();
if (!existingUsername) {
const newUser = new User(userData);
await newUser.save();
}
} catch (err) {
console.log(err);
return res
.status(400)
.json({ message: "There was a problem creating your account" });
}
};
defaultUser();
app.use("/api", publicRoutes);
const checkJwt = jwt({
secret: process.env.JWT_SECRET,
algorithms: ["HS256"],
issuer: "api.jpeterson",
audience: "api.jpeterson",
getToken: (req) => req.cookies.token,
});
app.use(csrfProtection);
app.get("/api/csrf-token", (req, res) => {
res.json({ csrfToken: req.csrfToken() });
});
app.use("/api/private/", checkJwt, privateRoutes);
mongoose
.connect(process.env.MONGODB_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
})
.then(() => console.log("mongoDB connected..."));
app.get("/*", function (req, res, next) {
res.sendFile(path.join(__dirname, "client", "build", "index.html"));
});
module.exports = app;