-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
580 lines (405 loc) · 15.2 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
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
require("dotenv").config();
const express = require("express");
const http = require("http");
const socket = require("socket.io");
const bodyParser = require('body-parser');
const path = require("path");
const jwt = require('jsonwebtoken');
const jwt_decode = require('jwt-decode');
const crypto = require("crypto");
const cookieParser = require('cookie-parser');
const withAuth = require('./middleware');
const createPayment = require('./Stripe/createPayment');
const createStripeCustomer = require('./Stripe/createStripeCustomer');
const secret = process.env.SECRET;
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
const server = http.createServer(app);
const io = socket(server);
const port = process.env.PORT || 8000;
var firebase = require("firebase/app");
require("firebase/auth");
require("firebase/firestore");
var firebaseConfig = {
apiKey: process.env.API_KEY,
authDomain: "professionall.firebaseapp.com",
projectId: "professionall",
storageBucket: "professionall.appspot.com",
messagingSenderId: "628673579093",
appId: "1:628673579093:web:cbb614b2bf2ed592fc2cdc",
measurementId: "G-LT02G7RWYZ"
};
firebase.initializeApp(firebaseConfig);
const firestore = firebase.firestore();
var nodemailer = require('nodemailer');
app.get('/checkToken', withAuth, function(req, res) {
res.sendStatus(200);
});
var transporter = nodemailer.createTransport({
service: 'hotmail',
auth: {
user: process.env.EMAIL,
pass: process.env.PASSWORD
}
});
app.post('/api/login/', async(req, res) => {
console.log(req.body);
var theUser = {};
//const newDoc = await firestore.collection('users').add(req.body);
await firebase.auth().signInWithEmailAndPassword(req.body.email, req.body.password)
.then((userCredential) => {
// Signed in
theUser = userCredential;
})
.catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
// ..
res.status(400).send(`${errorMessage} and ${errorCode}`);
});
console.log(theUser);
var email = theUser.user.email;
var user = theUser.user.uid;
const callDoc = firestore.collection('users').doc(user);
var doc = await callDoc.get();
var user_data = doc.data();
const payload = {
email: email,
user: user,
role: user_data.role,
stripe_id: user_data.stripe_id,
name: user_data.name
};
const token = jwt.sign(payload, secret, {
expiresIn: '24h'
});
res.cookie('token', token, { httpOnly: true })
.sendStatus(200);
});
app.get('/logout', function(req, res) {
res.cookie('token', null, { maxAge: 0 })
.sendStatus(200);
});
app.get('/api/decode/', async(req, res) => {
const token = req.cookies.token;
if (!token) res.status(400).send("Authentication issue")
console.log(token);
var decoded = jwt_decode(token, process.env.SECRET);
console.log(jwt_decode(token, process.env.SECRET));
res.status(201).send(decoded);
});
app.post('/api/register/', async(req, res) => {
//const newDoc = await firestore.collection('users').add(req.body);
let uid = "";
await firebase.auth().createUserWithEmailAndPassword(req.body.email, req.body.password)
.then((userCredential) => {
// Signed in
var user = userCredential.user.uid;
var email = userCredential.user.email;
firestore.collection('users').doc(user).set({
name: req.body.name,
appointments: [],
role: 'user',
email: email
})
uid = user;
})
.catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
// ..
res.status(400).send(`${errorMessage} and ${errorCode}`);
});
const customer_stripe_id = await createStripeCustomer(req.body.name, req.body.email);
firestore.collection('users').doc(uid).update({ stripe_id: customer_stripe_id })
const payload = {
email: req.body.email,
user: uid,
role: "user",
stripe_id: customer_stripe_id,
name: req.body.name
};
const token = jwt.sign(payload, secret, {
expiresIn: '24h'
});
res.cookie('token', token, { httpOnly: true })
.sendStatus(200);
});
app.post('/api/reset/', async(req, res) => {
console.log(req.body);
firebase.auth().sendPasswordResetEmail(
req.body.email)
.then(function() {
console.log("sent");
})
.catch(function(error) {
console.log(error);
});
});
app.post('/api/appointment/create', async(req, res) => {
//create email to inform expert that he has a new appointment pending
const appointment = {
customer: req.body.customer,
expert: req.body.expert,
day: req.body.day,
hour: req.body.hour,
price: req.body.price,
service: req.body.service,
uuid: crypto.randomBytes(16).toString("hex"),
status: 0,
professional_time:0,
user_time:0
};
const newDoc = await firestore.collection('appointments').add(appointment);
const app_id = newDoc.id;
await firestore.collection('users').doc(appointment.customer).update({
appointments: firebase.firestore.FieldValue.arrayUnion(app_id)
})
const exp = firestore.collection('users').doc(appointment.expert);
var exp_data = await exp.get();
var dataa = exp_data.data();
let hoursOff = dataa.hoursOff
if(!hoursOff[req.body.day])hoursOff[req.body.day]=[]
hoursOff[req.body.day].push(req.body.hour)
await firestore.collection('users').doc(appointment.expert).update({
appointments: firebase.firestore.FieldValue.arrayUnion(app_id),
hoursOff: hoursOff
})
res.status(200).send("ok");
});
app.post('/api/appointment/review', async(req, res) => {
const appointment_id = req.body.appointment;
const review = req.body.review;
const customer = req.body.customer;
const rating = req.body.rating;
const professional_id = req.body.expert;
console.log(req.body)
const appointment = await firestore.collection('appointments').doc(appointment_id).get();
const appointment_data = appointment.data();
console.log(appointment_data);
await firestore.collection('users').doc(professional_id).collection('reviews').add({
customer: customer,
review: review,
rating: rating
})
res.status(200).send("ok");
});
app.get('/api/search', async(req, res) => {
const search = req.query.search.toLowerCase();
console.log(search)
let results = [];
const users = await firestore.collection('users').get();
users.forEach(doc => {
const user_data = doc.data();
if (user_data.role == "professional") {
if (user_data.profession.toLowerCase() == search) {
results.push({
name: user_data.name,
job: user_data.profession,
info: user_data.about,
id: doc.id,
url: user_data.photo,
rating: user_data.stars
});
}
}
})
res.status(200).send(results);
})
app.get('/api/user/get', async(req, res) => {
let user = req.query.user || req.body.user;
const callDoc = firestore.collection('users').doc(user);
var doc = await callDoc.get();
var data = doc.data();
let reviews = [];
let average = 0;
let number=0;
const reviewsDic = await firestore.collection('users/'+user+'/reviews').get();
reviewsDic.docs.forEach((document) => {
const data = document.data();
reviews.push(data)
average+=parseFloat(data.rating)
number++;
});
data.reviews = reviews;
data.stars = parseFloat(average/number).toFixed(1);
if (req.query.appointments) {
let appointments = data.appointments;
const fullAppointments = [];
for (var i = 0; i < appointments.length; i++) {
const appointment = firestore.collection('appointments').doc(appointments[i]);
var appointment_data = await appointment.get();
var theData = appointment_data.data();
theData.appointment_id = appointments[i]
const expert = firestore.collection('users').doc(theData.expert);
var expert_data = await expert.get();
expert_data = expert_data.data();
theData.expert_name = expert_data.name
const customer = firestore.collection('users').doc(theData.customer);
var customer_data = await customer.get();
customer_data = customer_data.data();
theData.customer_name = customer_data.name;
//get experts name
fullAppointments.push(theData);
}
data.appointments = fullAppointments;
}
res.status(201).send(data);
});
app.post('/api/appointment/approve/', async(req, res) => {
await firestore.collection('appointments').doc(req.body.id).update({
status: req.body.status
})
const message = req.body.status == 1?"confirmed":"denied";
const appointment = firestore.collection('appointments').doc(req.body.id);
var appointment_data = await appointment.get();
var theData = appointment_data.data();
const customer_id = theData.customer;
const expert_id = theData.expert;
const cust = firestore.collection('users').doc(customer_id);
var cust_data = await cust.get();
const customer = cust_data.data();
const exp = firestore.collection('users').doc(expert_id);
var exp_data = await exp.get();
const expert = exp_data.data();
var mailOptions = {
from: {
name: 'Find Expert Online',
address: process.env.EMAIL
},
to: customer.email,
subject: 'Your Appointment',
text: `Your appointment with ${expert.name} at ${theData.day + ","+theData.hour} for "${theData.service}" has been ${message}.`
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
res.status(200).send("ok");
});
app.post('/api/appointments/time', async(req, res) => {
const appointment_id = req.body.id;
const role = req.body.role;
const appointment = firestore.collection('appointments').doc(appointment_id);
var appointment_data = await appointment.get();
var theData = appointment_data.data();
console.log(theData);
let professional_time = theData.professional_time?theData.professional_time+10:10;
let user_time = theData.user_time?theData.user_time+10:10;
if(role == 'professional'){
await firestore.collection('appointments').doc(appointment_id).update({
professional_time:professional_time
})
}else{
await firestore.collection('appointments').doc(appointment_id).update({
user_time: user_time
})
}
res.status(201).send("ok");
});
app.get('/api/expert/getAppointment', async(req, res) => {
const callDoc = firestore.collection('users').doc('uDOmxlKpwHvQaJ0N1Dds');
var doc = await callDoc.get();
console.log(doc.data());
res.status(201).send(doc.data());
});
app.post('/api/user/edit', async(req, res) => {
const user = db.collection('users').doc(req.body.id);
res = await user.update({ name: req.body.name });
});
app.post('/api/expert/edit', async(req, res) => {
const expert = req.body.expert;
console.log(req.body)
firestore.collection('users').doc(expert).update(req.body)
res.status(200).send("ok");
});
app.post('/api/stripe/createCustomer', async(req, res) => {
const name = req.body.name;
const email = req.body.email;
const customer_fb_id = req.body.id;
const customer_stripe_id = await createStripeCustomer(name, email);
firestore.collection('users').doc(customer_fb_id).update({ stripe_id: customer_stripe_id })
res.status(200).send("ok");
});
app.get('/api/appointment/:id', async(req, res) => {
const id = req.params.id.toString();
const appointment = firestore.collection('appointments').doc(id);
var appointment_data = await appointment.get();
var theData = appointment_data.data();
res.status(200).send(theData);
});
app.post('/api/stripe/createPayment', async(req, res) => {
const customer = req.body.id;
const price = req.body.price;
const appointment_id = req.body.appointment;
const stripe_pi_id = await createPayment(customer, price);
if (stripe_pi_id) firestore.collection('appointments').doc(appointment_id).update({ status: 2 })
res.status(200).send("ok");
});
//instead of const rooms we will access firebase and see if in the assigned uuid room someone is currently inside and waiting
//every time a user enters or leaves the room we have to keep a log about his time of arrival and departure from the room
const rooms = {};
const chats = {};
io.on("connection", socket => {
socket.on("profile", profile_id => {
const callDoc = firestore.collection('users').doc(profile_id);
var doc;
(async() => {
doc = await callDoc.get();
})();
});
socket.on("join room", roomID => {
console.log("the socket is:" + socket.id)
console.log(rooms[roomID])
if (rooms[roomID]) {
const me = rooms[roomID].find(id => id === socket.id);
if (!me) rooms[roomID].push(socket.id);
} else {
rooms[roomID] = [socket.id];
}
const otherUser = rooms[roomID].find(id => id !== socket.id);
if (otherUser) {
socket.emit("other user", otherUser);
socket.to(otherUser).emit("user joined", socket.id);
} else {
socket.emit("no user", "23");
}
});
socket.on("join chat", roomID => {
if (chats[roomID]) {
chats[roomID].push(socket.id);
} else {
chats[roomID] = [socket.id];
}
const otherUser = chats[roomID].find(id => id !== socket.id);
if (otherUser) {
socket.emit("other user chat", otherUser);
socket.to(otherUser).emit("user joined chat", socket.id);
}
socket.emit("your id", socket.id);
});
socket.on("send message", body => {
io.emit("message", body)
})
socket.on("offer", payload => {
io.to(payload.target).emit("offer", payload);
});
socket.on("answer", payload => {
io.to(payload.target).emit("answer", payload);
});
socket.on("ice-candidate", incoming => {
io.to(incoming.target).emit("ice-candidate", incoming.candidate);
});
});
if (process.env.PROD) {
app.use(express.static(path.join(__dirname, './client/build')));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, './client/build/index.html'));
})
}
server.listen(port, () => console.log(`🚀🚀🚀🚀🚀server is running on port ${port}🚀🚀🚀 `));