-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
527 lines (506 loc) · 18.9 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
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
// express server
const path = require("path");
const dotenv = require("dotenv");
const crypto = require("crypto");
const { promisify } = require("util");
const admin = require("firebase-admin");
const express = require("express");
const LicenceToken = require("./LicenceToken");
const { getAuth } = require("firebase-admin/auth");
const app = express();
const { getDatabase } = require("firebase-admin/database");
const cookieParser = require("cookie-parser");
const session = require("express-session");
const fetch = require("node-fetch");
const axios = require("axios").default;
dotenv.config();
const port = process.env.PORT || 8080;
const randomBytes = promisify(crypto.randomBytes);
// Firebase service account configurations.
const serviceAccount = {
type: process.env.type,
project_id: process.env.project_id,
private_key_id: process.env.private_key_id,
client_email: process.env.client_email,
client_id: process.env.client_id,
auth_uri: process.env.auth_uri,
token_uri: process.env.token_uri,
auth_provider_x509_cert_url: process.env.auth_provider_x509_cert_url,
client_x509_cert_url: process.env.client_x509_cert_url,
private_key: process.env.private_key.replace(/\\n/g, "\n"), // Parsing private key by replacing
};
// Initializing Firebase Admin SDK
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL:
"https://any-time-message-default-rtdb.asia-southeast1.firebasedatabase.app",
});
const db = getDatabase();
app.use(express.json()); // Parse the body to json format
app.use(cookieParser()); // parse cookie middle-ware
app.use(
session({
secret: process.env.serverSession_secret,
resave: false,
saveUninitialized: true,
cookie: { expires: new Date(253402300000000) },
})
);
// Listen for "/register" post request called every time after successfull creation of a new user accout.
app.post("/register", (req, res) => {
getAuth()
.verifyIdToken(req.headers.authorization) // Verify the user using JWT send in header as authorization token
.then((Decodetoken) => {
// callback function after varification
if (req.body.uid === Decodetoken.uid) {
const ref = db.ref(`${Decodetoken.uid}/PersonalInfo`); // Database reference to userID/PersonalInfo
const { uid, email } = Decodetoken; // Destructring Decodetoken to get email and uid
const Name = req.body.name; // Name of the user
// Setting value in the database Reference
ref.set({
email: email,
uid: uid,
name: Name,
photoURL: "",
});
// Generating uniqe token for the user to validate and varify uniquely
LicenceToken(Decodetoken.uid).then(async (token) => {
const nonce = (await randomBytes(32)).toString("base64"); // Random string used to make Client local database key string
const databaseKey = `${nonce}:${req.sessionID}`; //Random Database key for the Client localStorage
res.cookie("sessionId", req.sessionID, {
maxAge: new Date(23423432323232),
});
res.cookie("databaseKey", databaseKey, {
maxAge: new Date(23423432323232),
});
res.cookie("appId", process.env.seald_appId, {
maxAge: new Date(23423432323232),
});
const sendChallengeResult = await axios.post(
`${process.env.ssks_key_storage_url}tmr/back/challenge_send/`,
{
create_user: true, // boolean determined above
user_id: Decodetoken.uid, // unique identifier for the user in this app
auth_factor: {
type: "EM",
value: Decodetoken.email, // email address of the user
},
template: `<div style="font-family: Helvetica,Arial,sans-serif;min-width:1000px;overflow:auto;line-height:2">
<div style="margin:50px auto;width:70%;padding:20px 0">
<div style="border-bottom:1px solid #eee"> <a href=""
style="font-size:1.4em;color: #00466a;text-decoration:none;font-weight:600">MessageHub</a> </div>
<p style="font-size:1.1em">Hi, ${Decodetoken.name}</p>
<p> Use the following OTP to complete your Login procedures. OTP is valid
for 15 minutes</p>
<h2
style="background: #00466a;margin: 0 auto;width: max-content;padding: 0 10px;color: #fff;border-radius: 4px;">
$$CHALLENGE$$</h2>
<p style="font-size:0.9em;">Regards,<br />Team MessageHub</p>
<hr style="border:none;border-top:1px solid #eee" />
<p>If you didn’t login, then someone might know your password and trying to login please change your <a
href="https://secure-message-hub.herokuapp.com"> password
here.</a> </p>
<!-- <br> -->
<p>report malcious activity <a href="mailto:nk.technical.org@gmail.com"> here</a></p>
</div>
</div>`, // email template to use
},
{
headers: {
"Content-Type": "application/json",
"X-SEALD-APPID": process.env.seald_appId,
"X-SEALD-APIKEY": process.env.ssks_key_storage_api,
},
}
);
if (sendChallengeResult.statusText !== "OK") {
const responseText = sendChallengeResult.statusText;
throw new Error(
`Error in SSKS createUser: ${sendChallengeResult.status} ${responseText}`
);
}
// retrieval of the session id which will be used by the user
const {
session_id: twoManRuleSessionId,
must_authenticate: mustAuthenticate,
} = await sendChallengeResult.data;
// if there is no `twoManRuleKey` stored yet, we generate a new one
const twoManRuleKey = (await randomBytes(64)).toString("base64");
const storeTwoManRuleKey = db.ref(`${Decodetoken.uid}/securityKey`);
storeTwoManRuleKey.update(
{
ssks2mrkey: twoManRuleKey,
},
(err) => {
if (!err) {
res.status(201).json({
token: token,
twoManRuleSessionId,
twoManRuleKey: twoManRuleKey,
mustAuthenticate,
});
}
}
);
// response to the user
});
} else {
req.status(401);
}
})
// Catch error in athentication JWT Token
.catch((error) => {
res.status(500);
console.log(error);
});
});
// Listen for Post reqest made on "/session/login" called every time after successfull login of the User .
app.post("/session/login", async (req, res) => {
getAuth()
.verifyIdToken(req.headers.authorization) // Verfiy the user using JWT .
.then(async (Decodetoken) => {
if (req.body.uid === Decodetoken.uid) {
// Set session Cookie after verifying the user is authentcated
const nonce = (await randomBytes(32)).toString("base64");
const databaseKey = `${nonce}:${req.sessionID}`; //database key for seald-identity stored on client device
res.cookie("sessionId", req.sessionID, {
maxAge: new Date(23423432323232),
}); // set session id
res.cookie("databaseKey", databaseKey, {
maxAge: new Date(23423432323232),
}); //set databaseKey
res.cookie("appId", process.env.seald_appId, {
maxAge: new Date(23423432323232),
}); // set AppId
const sendChallengeResult = await axios.post(
`${process.env.ssks_key_storage_url}tmr/back/challenge_send/`,
{
create_user: true, // boolean determined above
user_id: Decodetoken.uid, // unique identifier for the user in this app
auth_factor: {
type: "EM",
value: Decodetoken.email, // email address of the user
},
template: `<div style="font-family: Helvetica,Arial,sans-serif;min-width:1000px;overflow:auto;line-height:2">
<div style="margin:50px auto;width:70%;padding:20px 0">
<div style="border-bottom:1px solid #eee"> <a href=""
style="font-size:1.4em;color: #00466a;text-decoration:none;font-weight:600">MessageHub</a> </div>
<p style="font-size:1.1em">Hi, ${Decodetoken.name}</p>
<p> Use the following OTP to complete your Login procedures. OTP is valid
for 15 minutes</p>
<h2
style="background: #00466a;margin: 0 auto;width: max-content;padding: 0 10px;color: #fff;border-radius: 4px;">
$$CHALLENGE$$</h2>
<p style="font-size:0.9em;">Regards,<br />Team MessageHub</p>
<hr style="border:none;border-top:1px solid #eee" />
<p>If you didn’t login, then someone might know your password and trying to login please change your <a
href="https://secure-message-hub.herokuapp.com"> password
here.</a> </p>
<!-- <br> -->
<p>report malcious activity <a href="mailto:nk.technical.org@gmail.com"> here</a></p>
</div>
</div>`,
},
{
headers: {
"Content-Type": "application/json",
"X-SEALD-APPID": process.env.seald_appId,
"X-SEALD-APIKEY": process.env.ssks_key_storage_api,
},
}
);
if (sendChallengeResult.statusText !== "OK") {
const responseText = sendChallengeResult.statusText;
res.status(sendChallengeResult.status);
res.send({
code: sendChallengeResult.status,
err: responseText,
});
throw new Error(
`Error in SSKS createUser: ${sendChallengeResult.status} ${responseText}`
);
}
// retrieval of the session id which will be used by the user
const {
session_id: twoManRuleSessionId,
must_authenticate: mustAuthenticate,
} = await sendChallengeResult.data;
// if there is no `twoManRuleKey` stored yet, we generate a new one
const storeTwoManRuleKey = db.ref(`${Decodetoken.uid}/securityKey`);
storeTwoManRuleKey.once("value", async (data) => {
if (data.hasChildren()) {
console.log(data.val().ssks2mrkey);
if (req.body.code = "mobile") {
res.status(200).json({
twoManRuleSessionId,
twoManRuleKey: data.val().ssks2mrkey,
mustAuthenticate,
passRetrival: false,
appId: process.env.seald_appId,
sessionId: req.sessionID,
databaseKey: databaseKey
});
} else {
res.status(200).json({
twoManRuleSessionId,
twoManRuleKey: data.val().ssks2mrkey,
mustAuthenticate,
passRetrival: false,
});
}
} else {
const twoManRuleKey = (await randomBytes(64)).toString("base64");
storeTwoManRuleKey.update(
{
ssks2mrkey: twoManRuleKey,
},
(e) => {
if (req.body.mode === "mobile") {
res.status(200).json({
twoManRuleSessionId,
twoManRuleKey: twoManRuleKey,
mustAuthenticate,
passRetrival: true,
appId: process.env.seald_appId,
sessionId: req.sessionID,
databaseKey: databaseKey
});
} else {
res.status(200).json({
twoManRuleSessionId,
twoManRuleKey: twoManRuleKey,
mustAuthenticate,
passRetrival: true,
})
}
}
);
}
});
}
});
});
// Listen for Post reqest made on "/session/logout" called every time after user Logout.
app.post("/session/logout", (req, res) => {
// Destroy the session and clear sessionId
req.session.destroy((err) => {
res.clearCookie("sessionId"); // Clear sessionId
res.clearCookie("databaseKey"); // clear databaseKey
res.clearCookie("appId"); // clear appId
if (!err) {
res.status(200);
res.send("done");
}
});
});
// Listen for Post reqest made on "/addcontact" called when user add a Contact.
app.post("/addcontact", (req, res) => {
getAuth()
.verifyIdToken(req.headers.authorization) // Verify user using Firebase JWT
.then((decodeToken) => {
getAuth()
.getUserByEmail(req.body.email) // tries to get user by email return user if exist otherwise give error
.then((user) => {
// User recived
const ref = db.ref(`${decodeToken.uid}/contacts`); // Referece to database.
let present = []; //variable ot hold present Contact
// Retrive all Present Contact of the user
ref.once("value", (data) => {
data.forEach((childData) => {
if (childData.val().email === req.body.email) {
present.push(childData.val().email);
}
});
// Check if the user already added in Contact' s if not add it
if (!present.includes(req.body.email)) {
ref.push().set({
uid: user.uid,
});
res.status(201);
res.send("Contact Added to the server ");
} else {
// Else Raise error .
res.status(409);
res.send("user already in contact list");
}
});
})
.catch((error) => {
// catch no user exist with the email send error no user exist
console.log(error);
res.status(500);
res.send("No User with this email");
});
})
.catch((error) => {
// Catch error in athentication JWT Token
console.log(error);
res.status(500);
res.send("internal server error");
});
});
app.post("/uploadprofile", (req, res) => {
getAuth()
.verifyIdToken(req.headers.authorization)
.then((Decodetoken) => {
if (req.body.uid === Decodetoken.uid) {
const ProfileImg = db.ref(`${Decodetoken.uid}/PersonalInfo`);
ProfileImg.update(
{
photoURL: req.body.url,
},
(error) => {
if (!error) {
res.status(200);
res.send("Update");
} else {
res.status(400);
res.send("error");
}
}
);
}
})
.catch((error) => {
console.log(error);
res.status(400);
res.send("ping");
});
});
app.post("/sendmessage", (req, res) => {
getAuth()
.verifyIdToken(req.headers.authorization)
.then((decodeToken) => {
if (req.body.uid === decodeToken.uid) {
const refSend = db.ref(
`${decodeToken.uid}/chats/${req.body.Recipetuid}/messages`
); // Referense for sender accout
const refRecive = db.ref(
`${req.body.Recipetuid}/chats/${decodeToken.uid}/messages`
); // Referense for reciver accout
const reciveSession = db.ref(
`${req.body.Recipetuid}/chats/${decodeToken.uid}`
); // Referense for sender session
const sendSession = db.ref(
`${decodeToken.uid}/chats/${req.body.Recipetuid}`
); // Referense for resiver session
if (req.body.sessionId) {
// check if sessionId is send by frontend or not
sendSession.update({
sessionId: req.body.sessionId,
}); // save sesion id for sender
reciveSession.update({
sessionId: req.body.sessionId,
}); // save sesion id for Reciver
}
if (req.body.message) {
refSend.push().set(
{
message: req.body.message,
send: true,
type: "text",
}, //Save messag for sender
(error) => {
if (!error) {
// Check for error
refRecive.push().set(
{
message: req.body.message,
send: false,
type: "text",
}, //Save messag for Reciver
(error) => {
if (!error) {
//Check for error
res.status(201);
res.send("done");
} else {
res.status(500);
res.send("Internel Server error message cannot be send");
}
}
);
} else {
res.status(500);
res.send("Internel Server error message cannot be send");
}
}
);
} else if (req.body.url) {
refSend.push().set(
{
url: req.body.url,
send: true,
type: "audio",
},
(error) => {
if (!error) {
refRecive.push().set(
{
url: req.body.url,
send: false,
type: "audio",
},
(error) => {
if (!error) {
//Check for error
res.status(201);
res.send("done");
} else {
res.status(500);
res.send("Internel Server error message cannot be send");
}
}
);
} else {
res.status(500);
res.send("Internel Server error message cannot be send");
}
}
);
}
} else {
res.status(403);
res.send("Unatorize");
}
})
.catch((error) => {
res.status(503);
console.log(error);
res.send("Internal Server Error");
});
});
// app.get("/audioMessage",(res,req)=>{
// getAuth()
// .verifyIdToken(req.headers.authorization).then((decodeToken)=>{
// if(req.body.uid===decodeToken){
// }
// })
// })
app.post("/notification", (req, res) => {
getAuth()
.verifyIdToken(req.headers.authorization)
.then((decodeToken) => {
db.ref(`${decodeToken.uid}/PersonalInfo`).update(
{
notification: req.body.token,
},
(err) => {
if (!err) {
res.status(201);
res.send("done");
} else {
res.status(406);
res.send("Not Saved");
}
}
);
});
});
app.use(express.static(path.join(__dirname, "/message-frontend/build")));
app.use((req, res, next) => {
res.sendFile(path.join(__dirname, "/message-frontend/build", "index.html"));
});
app.listen(port, () => {
console.log(`App listening on http://localhost:${port} !`);
});