-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
193 lines (168 loc) · 4.57 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
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
const express = require("express");
const app = express();
const path = require("path");
// Import routes
const humans = require("./routes/humans");
const locations = require("./routes/locations");
const users = require("./routes/users");
// For environment variables
require("dotenv").config();
// Bcrypt for password encryption
const bcrypt = require("bcrypt");
// Database initialization
const MongoClient = require("mongodb").MongoClient;
MongoClient.connect(
`mongodb+srv://${process.env.MONGO_USER}:${process.env.MONGO_PASS}@sandbox.1ybr6.mongodb.net/myFirstDatabase?retryWrites=true&w=majority`,
{ useUnifiedTopology: true },
function (err, client, res) {
if (err != null) {
res.send(err);
}
app.locals.db = client.db("bootcamp_project2");
console.log(`Connected to database...`);
}
);
// Express middleware
// app.use(express.static("public"));
app.use(express.static(path.join(__dirname, "build")));
// With this, it doesn't run
// app.get('/*', (req, res) => {
// res.sendFile(path.join(__dirname, 'build', 'index.html'));
// });
app.use(express.json());
// External routes
app.use("/api/humans/", humans);
app.use("/api/locations/", locations);
app.use("/api/users/", users);
// Express session
const expressSession = require("express-session")({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
});
app.use(expressSession);
// Passport
const passport = require("passport");
app.use(passport.initialize());
app.use(passport.session());
const LocalStrategy = require("passport-local").Strategy;
passport.use(
new LocalStrategy({ usernameField: "email" }, function (
email,
password,
done
) {
app.locals.db
.collection("users")
.find({ email: email })
.toArray(function (err, users) {
if (users.length === 0) {
return done(null, false);
}
const user = users[0];
if (bcrypt.compareSync(password, user.password)) {
return done(null, user);
} else {
return done(null, false);
}
});
})
);
passport.serializeUser(function (user, done) {
done(null, user.email);
});
passport.deserializeUser(function (email, done) {
app.locals.db
.collection("users")
.find({ email: email })
.toArray(function (err, users) {
if (users.length === 0) {
console.log("0 users");
done(null, null);
}
console.log("1 user");
done(null, users[0]);
});
});
// Route to check if user is logged
app.get("/api/login/check", (req, res) => {
if (req.session.passport) {
res.send({ isLogged: true, user: req.session.passport.user });
return;
}
res.send({ isLogged: false });
});
app.post("/api/signin", function (req, res) {
const email = req.body.email.trim();
const password = bcrypt.hashSync(req.body.password, 10);
const name = req.body.name.trim();
const surname = req.body.surname.trim();
const dateCreation = new Date();
app.locals.db.collection("users").findOne({ email: email }, (err, user) => {
if (!user) {
app.locals.db.collection("users").insertOne(
{
name,
surname,
email,
password,
date_creation: dateCreation,
},
(err, respuesta) => {
if (err !== null) {
res.send({
new_user: false,
success: false,
msg: "An error occurred: " + err,
});
} else {
res.send({
new_user: true,
success: true,
msg: "User was registered",
});
}
}
);
} else {
res.send({ new_user: false, msg: "User is already registered" });
}
});
});
app.post(
"/api/login",
passport.authenticate("local", {
successRedirect: "/success",
failureRedirect: "/fail",
})
);
app.get("/success", (req, res) => {
res.send({
loginDataCorrect: true,
msg: "Login successful",
user: req.user,
session: true,
});
});
app.get("/fail", (req, res) => {
res.send({
loginDataCorrect: false,
msg: "Wrong user or password",
session: false,
});
});
app.put("/api/logout", (req, res) => {
req.session.destroy(function (err) {
res.send({ loggedOut: true, msg: "Logout successful" });
});
});
// Redirect all requests to index.html
app.get("/*", function (req, res) {
res.sendFile(path.join(__dirname, "./build/index.html"), function (err) {
if (err) {
res.status(500).send(err);
}
});
});
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening on port ${port}...`));