-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
431 lines (271 loc) · 11.7 KB
/
index.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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
require("dotenv").config();
const express = require("express");
const cors = require("cors");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const cookieParser = require("cookie-parser");
const utils = require("./utils/utils");
const app = express();
const router = require("./router");
const pool = require("./db/index");
const sendVerificationEmail = require("./mailer/index.js");
const json_dummy_user = require("./db/user");
app.use(router);
const CORS_OPTIONS = {
origin: process.env.FRONTEND_HOST,
credentials: true,
preflightContinue: true
};
console.log(CORS_OPTIONS);
const USER_EMAIL_COOKIE_OPTIONS = { expires: utils.cookieExpiresIn(14), httpOnly: false, sameSite: "none", secure: true};
let REFRESH_TOKEN_COOKIE_OPTIONS;
if (!process.env.NODE_ENV || process.env.NODE_ENV === "development") {
REFRESH_TOKEN_COOKIE_OPTIONS = { expires: utils.cookieExpiresIn(14), httpOnly: true, sameSite: "lax"};
} else {
REFRESH_TOKEN_COOKIE_OPTIONS = { expires: utils.cookieExpiresIn(14), httpOnly: true, sameSite: "none", secure: true};
}
// middleware
app.use(cors(CORS_OPTIONS));
app.use(express.json());
app.use(cookieParser());
let errors = [];
function generateAccessToken(user) {
const TOKEN_EXPIRATION_TIME = "15m";
return jwt.sign(user, process.env.ACCESS_TOKEN_SECRET, { expiresIn: TOKEN_EXPIRATION_TIME });
}
function generateEmailVerificationToken(email) {
const TOKEN_EXPIRATION_TIME = "15m";
return jwt.sign(email, process.env.EMAIL_VERIFICATION_SECRET, { expiresIn: TOKEN_EXPIRATION_TIME });
}
function authenticateToken(req, res, next) {
const authHeader = req.headers["authorization"];
const token = authHeader && authHeader.split(" ")[1];
if (!token) return res.sendStatus(401);
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, user) => {
if (err) return res.sendStatus(403);
req.user = user;
next();
})
}
function authenticateEmailToken(req, res, next) {
const token = req.query.token;
if (!token) return res.sendStatus(401);
jwt.verify(token, process.env.EMAIL_VERIFICATION_SECRET, (err, email) => {
if (err) return res.sendStatus(403);
req.email = email;
next();
})
}
async function userInDb (email) {
const userProfileDbResponse = await pool.query(`SELECT * FROM users WHERE user_email=$1`, [email]);
const isThereOnlyOne = userProfileDbResponse.rowCount === 1;
const data = userProfileDbResponse.rows[0];
console.log(isThereOnlyOne);
return {isThereOnlyOne: isThereOnlyOne, data: data}
}
async function checkPassword (email, password) {
try {
const user = await userInDb(email);
if (user.isThereOnlyOne) {
const hashedPassword = user.data.user_password;
const isPasswordCorrect = await bcrypt.compare(password, hashedPassword);
if (isPasswordCorrect) {
return "password is correct"
} else {
return new Error("password is incorrect")
}
} else {
return new Error("user not found")
}
} catch (err) {
errors.push({place: "checkPassword function", error: err.message});
}
}
app.post ("/signup", async (req, res) => {
try {
const { name, email, password } = req.body;
let usersWithThisNameOrEmail = await pool.query("SELECT * FROM users WHERE user_email = $1", [email]);
usersWithThisNameOrEmail = usersWithThisNameOrEmail.rowCount;
if (usersWithThisNameOrEmail === 0) {
const date = new Date(Date.now());
const dummyBalance = Math.floor(Math.random() * 1000000);
const saltRounds = 10;
await bcrypt.hash(password, saltRounds, function (err, hashedPassword) {
pool.query ("INSERT INTO users (user_name, user_email, user_password, registration_date, account_balance) VALUES ($1, $2, $3, $4, $5)",
[name, email, hashedPassword, date, dummyBalance]);
});
const token = await generateEmailVerificationToken({email});
await sendVerificationEmail(email, token);
res.send('User successfully added');
} else {
errors.push({place: "post /signup", error: `User with email ${email} already exists`});
res.status(403).send("user with this email already exists");
}
} catch (err) {
errors.push({place: "post /signup", error: err.message});
}
});
app.get ("/email/verify", authenticateEmailToken, async (req, res) => {
try {
const email = req.email.email;
const user = await userInDb(email);
if (user.isThereOnlyOne) {
await pool.query("UPDATE users SET user_active=true WHERE user_email=$1", [email]);
}
res.sendStatus(200);
} catch (err) {
res.send("Проверка email не удалась");
errors.push({place: "post /email/verify", error: err.message});
}
});
app.post ("/login", async (req, res) => {
const { email, password } = req.body;
try {
const user = await userInDb(email);
if (user.isThereOnlyOne) {
const hashedPassword = user.data.user_password;
const isPasswordCorrect = await bcrypt.compare(password, hashedPassword);
if (isPasswordCorrect) {
const accessToken = await generateAccessToken({email});
const refreshToken = await jwt.sign(email, process.env.REFRESH_TOKEN_SECRET);
const dbValidTokens = await pool.query("SELECT * FROM valid_refresh_tokens WHERE user_email = $1", [email]);
const hasUserGotValidToken = dbValidTokens.rowCount > 0;
if (!hasUserGotValidToken) {
let date = new Date(Date.now());
await pool.query("INSERT INTO valid_refresh_tokens (token, token_added, user_email) VALUES ($1, $2, $3)",
[refreshToken, date, email]);
}
res.cookie('telecom-dashboard-user-name', email, USER_EMAIL_COOKIE_OPTIONS);
res.cookie('refreshToken', refreshToken, REFRESH_TOKEN_COOKIE_OPTIONS);
await res.json({ accessToken: accessToken, refreshToken: refreshToken });
} else {
errors.push({place: "post /login", error: "Password is incorrect"});
res.status(403).send("password is incorrect");
}
} else {
errors.push({place: "post /login", error: "User database has been corrupted"});
res.sendStatus(500);
}
} catch (err) {
errors.push({place: "post /login", error: err.message});
}
});
// refresh access token
app.get("/token", (req, res) => {
const refreshToken = req.cookies.refreshToken;
if (!refreshToken) return res.sendStatus(401);
jwt.verify(refreshToken, process.env.REFRESH_TOKEN_SECRET, async (err, email) => {
if (err) return res.send(err.message);
const validRefreshTokensInDb = await pool.query("SELECT * FROM valid_refresh_tokens WHERE user_email = $1", [email]);
if (validRefreshTokensInDb.rowCount > 0) {
const validRefreshTokenInDb = validRefreshTokensInDb.rows[0].token;
if (validRefreshTokenInDb !== refreshToken) return res.sendStatus(401);
}
res.cookie('telecom-dashboard-user-email', email, USER_EMAIL_COOKIE_OPTIONS);
const accessToken = generateAccessToken({email: email});
return res.json({accessToken: accessToken, email: email});
});
});
app.delete("/logout", async (req, res) => {
const refreshToken = req.cookies.refreshToken;
const validRefreshTokensInDb = await pool.query("SELECT * FROM valid_refresh_tokens WHERE token = $1",
[refreshToken]);
if (validRefreshTokensInDb.rowCount > 0) {
await pool.query("DELETE FROM valid_refresh_tokens WHERE token = $1", [refreshToken]);
}
res.sendStatus(204);
});
app.post("/dashboard", authenticateToken, async (req, res) => {
const {section, page} = req.body;
const email = req.user.email;
const user = await userInDb(email);
if (user.data.user_active) {
// the awkward "tabs" is used instead of "pages" because the "pages" is a keyword
if ( section !== "profile") {
const responseWithContent = {
"content": json_dummy_user[section].tabs[page - 1],
"section": section,
"tabsCount": json_dummy_user[section].tabs_count,
"tab": page
};
await res.json(responseWithContent);
} else {
const data = user.data;
const content = {
"user_name": data.user_name,
"user_email": data.user_email,
"company_name": data.company_name,
"account_balance": data.account_balance,
"city_name": data.city_name,
"registration_date": data.registration_date
};
const responseWithContent = {
"content": content,
"section": "profile"
};
await res.json(responseWithContent);
}
} else {
const content = {
user_status: "неактивен",
message: "Воспользуйтесь ссылкой в сообщении, " +
"которое было отправлено на указанный при регистрации email," +
"чтобы активировать учетную запись"
};
const responseWithContent = {
"content": content,
"section": "profile"
};
await res.json(responseWithContent);
}
});
app.post("/dashboard/edit-user-profile", authenticateToken, async (req, res) => {
const {fieldsToEdit, email} = req.body;
if (email && fieldsToEdit.length > 0) {
try {
let query = ["UPDATE users SET "];
const queryValues = [];
for (let i = 0; i < fieldsToEdit.length; i++) {
query.push(`${fieldsToEdit[i].field}=$${i+1} `);
queryValues.push(fieldsToEdit[i].value);
}
query.push(`WHERE user_email=$${fieldsToEdit.length + 1}`);
query = query.join("");
queryValues.push(email);
await pool.query(query, queryValues);
await res.send("profile edit success");
} catch (err) {
console.error(err.message);
}
}
});
// TODO get rid of callbacks and add feedback
app.post("/auth/change_password", async (req, res) => {
const { email, oldPassword, newPassword } = req.body;
try {
const checkPasswordResponse = await checkPassword(email, oldPassword);
if (checkPasswordResponse === 'password is correct') {
const saltRounds = 10;
let changePasswordResponse;
await bcrypt.hash(newPassword, saltRounds, (err, hashedPassword) => {
changePasswordResponse = pool.query ("UPDATE users SET user_password=$1 WHERE user_email=$2",
[hashedPassword, email]);
console.log(changePasswordResponse);
});
} else {
res.status(403).send("password is incorrect");
}
res.sendStatus(200);
} catch (err) {
if (err.message === 'password is incorrect') return res.send('password is incorrect');
if (err.message === 'user not found') return res.send('user not found');
console.error(err.message);
}
});
app.get('/errors', (req, res) => {
res.send(errors && errors);
});
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`The server is running on port ${PORT}`);
});