Advertisement
Guest User

Untitled

a guest
Dec 6th, 2019
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 21.97 KB | None | 0 0
  1. //put interpreter into strict mode
  2. "use strict";
  3.  
  4. //require the express and morgan packages
  5. const express = require("express");
  6. const morgan = require("morgan");
  7. const mongo = require("mongodb");
  8. const ObjectId = require("mongodb").ObjectId;
  9. var MongoClient = require("mongodb").MongoClient;
  10. var url = "mongodb://mongodb:27017/";
  11. const contentType = "Content-Type";
  12. const appJson = "application/json";
  13. const amqp = require('amqplib/callback_api')
  14.  
  15.  
  16. MongoClient.connect(url, function (err, db) {
  17. if (err) throw err;
  18. let dbo = db.db("mydb");
  19. console.log("Database created!");
  20. dbo.createCollection("channels", function (err, res) {
  21. console.log("Channel Collection created!");
  22. });
  23. dbo.createCollection("messages", function (err, res) {
  24. console.log("Messages Collection created!");
  25. });
  26. const general = {
  27. name: "general",
  28. createdAt: new Date()
  29. };
  30. dbo.collection("channels").update({ name: "general" }, general, { upsert: true });
  31. });
  32.  
  33. //create a new express application
  34. const app = express();
  35.  
  36. //get ADDR environment variable,
  37. //defaulting to ":80"
  38. const addr = process.env.NODE_ADDR || ":80";
  39. //split host and port using destructuring
  40. const [host, port] = addr.split(":");
  41.  
  42. //add JSON request body parsing middleware
  43. app.use(express.json());
  44. //add the request logging middleware
  45. app.use(morgan("dev"));
  46.  
  47.  
  48.  
  49.  
  50. async function connectToRabbit() {
  51. await amqp.connect("amqp://" + process.env.RABBITMQADDR + ":5672/", async (err, conn) => {
  52. await conn.createChannel(function (err, ch) {
  53. var q = process.env.RABBITMQADDR;
  54. ch.assertQueue(q, { durable: false });
  55. channel = ch;
  56. });
  57. });
  58. }
  59.  
  60. let channel;
  61. connectToRabbit();
  62.  
  63. function getChannel() {
  64. return channel;
  65. }
  66.  
  67. app
  68. .route("/v1/channels")
  69. .get((req, res) => {
  70. if (!req.get("X-User") || req.get("X-User").length == 0) {
  71. res.setHeader('Content-Type', 'text/plain');
  72. res.status(401).send("Unauthorized");
  73. return;
  74. }
  75.  
  76. let reqUserID = JSON.parse(JSON.stringify(req.header("X-User"))).id;
  77. MongoClient.connect(url, function (err, db) {
  78. if (err) throw err;
  79. let dbo = db.db("mydb");
  80. dbo
  81. .collection("channels")
  82. .find(req.query.startsWith && { name: new RegExp("^" + req.query.startsWith) }, { creator: reqUserID })
  83. .toArray(function (err, result) {
  84. if (err) throw err;
  85. res.status(200);
  86. res.set(contentType, appJson);
  87. res.json(result);
  88. db.close();
  89. return;
  90. });
  91. });
  92. })
  93. .post((req, res) => {
  94. if (!req.get("X-User") || req.get("X-User").length == 0) {
  95. res.setHeader('Content-Type', 'text/plain')
  96. res.status(401).send("Unauthorized");
  97. return;
  98. }
  99. let reqUserID = JSON.parse(req.header("X-User")).id;
  100. res.set("Content-Type", "application/json");
  101. var myobj = req.body;
  102. if (!myobj.name) {
  103. res.setHeader('Content-Type', 'text/plain');
  104. res.status(403).send("Channel name is required");
  105. return;
  106. } else {
  107. MongoClient.connect(url, async function (err, db) {
  108. if (err) throw err;
  109. let dbo = db.db("mydb");
  110. if (myobj.name == null) myobj.name = "";
  111. if (myobj.description == null) myobj.description = "";
  112. if (myobj.private == null) myobj.private = false;
  113. myobj.members == null
  114. ? (myobj.members = [{ id: reqUserID }])
  115. : (myobj.members = [{ id: reqUserID }].concat(myobj.members));
  116. myobj.createdAt = new Date();
  117. myobj.creator = JSON.parse(req.header("X-User"));
  118. myobj.editedAt = null;
  119. const duplicatechannel = await dbo.collection("channels").findOne({ name: myobj.name });
  120. if (duplicatechannel) {
  121. res.setHeader('Content-Type', 'text/plain');
  122. res.status(400).send("Duplicate channel");
  123. return;
  124. }
  125. dbo.collection("channels").insertOne(myobj, function (err, result) {
  126. if (err) throw err;
  127. let channelMembers = [];
  128. myobj.members && myobj.private && myobj.members.forEach(member => {
  129. channelMembers.push(member.id);
  130. });
  131. console.log("MYOBJ---------------", myobj);
  132. myobj.id = myobj._id;
  133. console.log("MYOBJ---------------", myobj);
  134. const event = {
  135. type: "channel-new",
  136. channel: myobj,
  137. userIDs: channelMembers
  138. };
  139. getChannel().sendToQueue(process.env.RABBITMQADDR, new Buffer(JSON.stringify(event)), { persistent: true });
  140. res.status(201);
  141. res.set(contentType, appJson);
  142.  
  143.  
  144. // myobj.id = myobj._id;
  145. res.json(myobj);
  146. db.close();
  147. return;
  148. });
  149. });
  150. }
  151. })
  152. .all((req, res) => {
  153. res.setHeader('Content-Type', 'text/plain');
  154. res.status(405).send('method not allowed');
  155. return
  156. });
  157.  
  158.  
  159. app
  160. .route("/v1/channels/:channelID")
  161. .get((req, res) => {
  162. res.set(contentType, appJson);
  163. if (!req.get("X-User") || req.get("X-User").length == 0) {
  164. res.setHeader('Content-Type', 'text/plain');
  165. res.status(401).send("Unauthorized");
  166. return;
  167. }
  168. if (req.params.channelID.length != 24) {
  169. res.setHeader('Content-Type', 'text/plain');
  170. res.status(403).send("Invalid channel ID");
  171. return;
  172. }
  173. let newChannelID = new mongo.ObjectId(req.params.channelID);
  174. let reqUserID = JSON.parse(req.header("X-User")).id;
  175. MongoClient.connect(url, function (err, db) {
  176. if (err) throw err;
  177. let dbo = db.db("mydb");
  178. dbo.collection("channels").findOne(
  179. {
  180. _id: newChannelID
  181. },
  182. function (err, result) {
  183. if (err) throw err;
  184. let memberArr = function () {
  185. for (let x of result.members) {
  186. if (x.id == reqUserID) {
  187. return true;
  188. }
  189. }
  190. return false;
  191. };
  192. console.log("result", result);
  193. if (result && result.private == true && !memberArr()) {
  194. res.setHeader('Content-Type', 'text/plain');
  195. res.status(403).send("Current user is not member of channel " + newChannelID);
  196. return;
  197. } else {
  198. // console.log("result", result);
  199. dbo
  200. .collection("messages")
  201. .find({
  202. channelID: newChannelID
  203. })
  204. .limit(100)
  205. .toArray(function (err, result2) {
  206. if (err) throw err;
  207. const result3 = [];
  208. result2.forEach((r) => {
  209. r.id = r._id; result3.push(r)
  210. });
  211. res.status(200);
  212. res.json(result3)
  213. db.close();
  214. return
  215. });
  216. db.close();
  217. }
  218. }
  219. );
  220. });
  221. })
  222. .post((req, res) => {
  223. if (!req.get("X-User") || req.get("X-User").length == 0) {
  224. res.setHeader('Content-Type', 'text/plain');
  225. res.status(401).send("Unauthorized");
  226. return;
  227. }
  228. let reqUserID = JSON.parse(req.header("X-User")).id;
  229. if (req.params.channelID.length != 24) {
  230. res.setHeader('Content-Type', 'text/plain');
  231. res.status(403).send("Invalid channel ID");
  232. return;
  233. }
  234. let channelID = new mongo.ObjectId(req.params.channelID);
  235. MongoClient.connect(url, function (err, db) {
  236. if (err) throw err;
  237. let dbo = db.db("mydb");
  238. dbo.collection("channels").findOne(
  239. {
  240. _id: channelID
  241. },
  242. function (err, result) {
  243. if (err) throw err;
  244. let memberArr = function () {
  245. for (let x of result.members) {
  246. if (x.id == reqUserID) {
  247. return true;
  248. }
  249. }
  250. return false;
  251. };
  252. if (result == null || (result.private == true && !memberArr())) {
  253. res.setHeader('Content-Type', 'text/plain');
  254. res.status(403).send("Current user is not member of channel " + channelID);
  255. return;
  256. } else {
  257. let msgObj = req.body;
  258. msgObj.body = req.body.body;
  259. msgObj.channelID = channelID;
  260. msgObj.createdAt = new Date();
  261. msgObj.creator = JSON.parse(req.get("X-User"));
  262. msgObj.editedAt = null;
  263. dbo.collection("messages").insertOne(msgObj, async function (err, result) {
  264. if (err) throw err;
  265. let channelMembers = [];
  266. const foundChannel = await dbo.collection("channel").findOne({ _id: msgObj.channelID })
  267. if (foundChannel) {
  268. foundChannel.members && foundChannel.private && foundChannel.members.forEach(member => {
  269. channelMembers.push(member.id);
  270. });
  271. }
  272. const event = {
  273. type: "message-new",
  274. message: msgObj,
  275. userIDs: channelMembers
  276. };
  277. getChannel().sendToQueue(process.env.RABBITMQADDR, new Buffer(JSON.stringify(event)), { persistent: true });
  278. res.status(201);
  279. res.set("Content-Type", "application/json");
  280. msgObj.id = msgObj._id;
  281. console.log("MSGOBJ---------------", msgObj);
  282. res.json(msgObj);
  283. db.close();
  284. return;
  285. });
  286. }
  287. }
  288. );
  289. });
  290. })
  291. .patch((req, res) => {
  292. if (!req.get("X-User") || req.get("X-User").length == 0) {
  293. res.setHeader('Content-Type', 'text/plain');
  294. res.status(401).send("Unauthorized");
  295. return;
  296. }
  297. if (req.params.channelID.length != 24) {
  298. res.setHeader('Content-Type', 'text/plain');
  299. res.status(403).send("Invalid channel ID");
  300. return;
  301. }
  302. let channelID = new mongo.ObjectId(req.params.channelID);
  303. let reqUserID = JSON.parse(req.header("X-User")).id;
  304. let reqBody = req.body;
  305. MongoClient.connect(url, async (err, db) => {
  306. if (err) throw err;
  307. let dbo = db.db("mydb");
  308. const result = await dbo.collection("channels").findOne({ _id: channelID });
  309. if (reqUserID != result.creator.id) {
  310. res.setHeader('Content-Type', 'text/plain');
  311. res.status(403).send("Unauthorized user or channel does not exist");
  312. return;
  313. } else {
  314. dbo
  315. .collection("channels")
  316. .findOneAndUpdate(
  317. { _id: channelID },
  318. { $set: { name: reqBody.name, description: reqBody.description, editedAt: new Date() } },
  319. { returnOriginal: false },
  320. (err, document) => {
  321. if (err) throw err;
  322. let result = document.value;
  323. let channelMembers = [];
  324. result.members && result.private && result.members.forEach(member => {
  325. channelMembers.push(member.id);
  326. });
  327. const event = {
  328. type: "channel-update",
  329. channel: result,
  330. userIDs: channelMembers
  331. };
  332. console.log("json stringify result", JSON.stringify(result));
  333. console.log("event stringify", JSON.stringify(event))
  334. getChannel().sendToQueue(process.env.RABBITMQADDR, new Buffer(JSON.stringify(event)), { persistent: true });
  335. res.setHeader('Content-Type', 'application/json');
  336. res.status(200);
  337. result.id = result._id;
  338. console.log("result", result)
  339. console.log("@@@@@@@@@2@@@", typeof result)
  340. res.json(result);
  341. db.close();
  342. }
  343. );
  344. }
  345. });
  346. })
  347. .delete((req, res) => {
  348. if (!req.get("X-User") || req.get("X-User").length == 0) {
  349. res.setHeader('Content-Type', 'text/plain');
  350. res.status(401).send("Unauthorized");
  351. return;
  352. }
  353. if (req.params.channelID.length != 24) {
  354. res.setHeader('Content-Type', 'text/plain');
  355. res.status(403).send("Invalid channel ID");
  356. return;
  357. }
  358. let channelID = new mongo.ObjectId(req.params.channelID);
  359. let reqUserID = JSON.parse(req.header("X-User")).id;
  360. MongoClient.connect(url, async (err, db) => {
  361. if (err) throw err;
  362. let dbo = db.db("mydb");
  363. const result = await dbo.collection("channels").findOne({ _id: channelID });
  364. console.log("REQUSERID-----------------", req.header("X-User"))
  365. console.log("REQUSERID-----------------", reqUserID);
  366. console.log("RESULTCREATOR-----------------", result.creator.id);
  367.  
  368. if (reqUserID != result.creator.id) {
  369. res.setHeader('Content-Type', 'text/plain');
  370. res.status(403).send("Unauthorized user or channel does not exist");
  371. return;
  372. } else {
  373. const foundChannel = await dbo.collection("channels").findOne({ _id: channelID });
  374. await dbo.collection("channels").remove({ _id: channelID });
  375. dbo.collection("messages").deleteMany({ channelID: channelID }, async (err, document) => {
  376. if (err) throw err;
  377. let channelMembers = [];
  378. if (foundChannel) {
  379. foundChannel.members.forEach(member => {
  380. channelMembers.push(member.id);
  381. });
  382. }
  383. const event = {
  384. type: "channel-delete",
  385. channelID: foundChannel.id,
  386. userIDs: channelMembers
  387. };
  388. getChannel().sendToQueue(process.env.RABBITMQADDR, new Buffer(JSON.stringify(event)), { persistent: true });
  389. res.setHeader('Content-Type', 'text/plain');
  390. res.status(200).send(`Channel with id "${channelID}" was successfuly deleted!"`);
  391. db.close();
  392. return
  393. });
  394. }
  395. });
  396. })
  397. .all((req, res) => {
  398. res.setHeader('Content-Type', 'text/plain')
  399. res.status(405).send('method not allowed')
  400. return
  401. });
  402.  
  403. app
  404. .route("/v1/channels/:channelID/members")
  405. .post((req, res) => {
  406. if (!req.get("X-User") || req.get("X-User").length === 0) {
  407. res.setHeader('Content-Type', 'text/plain');
  408. res.status(401).send("Unauthorized");
  409. return;
  410. }
  411. if (req.params.channelID.length != 24) {
  412. res.setHeader('Content-Type', 'text/plain');
  413. res.status(403).send("Invalid channel ID");
  414. return;
  415. }
  416. let channelID = new mongo.ObjectId(req.params.channelID);
  417. const currentUser = JSON.parse(req.header("X-User"));
  418. const userBody = req.body;
  419. MongoClient.connect(url, async (err, db) => {
  420. if (err) throw err;
  421. let dbo = db.db("mydb");
  422. const result = await dbo.collection("channels").findOne({ _id: channelID });
  423. if (!result || JSON.stringify(result.creator) !== JSON.stringify(currentUser)) {
  424. res.setHeader('Content-Type', 'text/plain');
  425. res.status(403).send("Unauthorized user or channelID does not exist");
  426. return;
  427. } else {
  428. dbo
  429. .collection("channels")
  430. .findOneAndUpdate(
  431. { _id: channelID },
  432. { $push: { members: userBody } },
  433. { returnOriginal: false },
  434. (err, document) => {
  435. if (err) throw err;
  436. const result = document.value;
  437. res.setHeader('Content-Type', 'text/plain');
  438. res.status(201).send(`User with id "${userBody.id}" was added as a member to channel "${channelID}"`);
  439. db.close();
  440. return
  441. }
  442. );
  443. }
  444. });
  445. })
  446. .delete((req, res) => {
  447. if (!req.get("X-User") || req.get("X-User").length === 0) {
  448. res.setHeader('Content-Type', 'text/plain');
  449. res.status(401).send("Unauthorized");
  450. return;
  451. }
  452. if (req.params.channelID.length != 24) {
  453. res.setHeader('Content-Type', 'text/plain');
  454. res.status(403).send("Invalid channel ID");
  455. return;
  456. }
  457. let channelID = new mongo.ObjectId(req.params.channelID);
  458. const currentUser = JSON.parse(req.header("X-User"));
  459. const userBody = req.body;
  460. MongoClient.connect(url, async (err, db) => {
  461. if (err) throw err;
  462. let dbo = db.db("mydb");
  463. const result = await dbo.collection("channels").findOne({ _id: channelID });
  464. if (!result || JSON.stringify(result.creator) !== JSON.stringify(currentUser)) {
  465. res.setHeader('Content-Type', 'text/plain');
  466. res.status(403).send("Unauthorized user or channelID does not exist");
  467. return;
  468. } else {
  469. dbo
  470. .collection("channels")
  471. .findOneAndUpdate(
  472. { _id: channelID },
  473. { $pull: { members: userBody } },
  474. { returnOriginal: false },
  475. (err, document) => {
  476. if (err) throw err;
  477. res.setHeader('Content-Type', 'text/plain');
  478. res.status(201).send(`User with id "${userBody.id}" was removed as a member to channel "${channelID}"`);
  479. db.close();
  480. return
  481. }
  482. );
  483. }
  484. });
  485. })
  486. .all((req, res) => {
  487. res.setHeader('Content-Type', 'text/plain')
  488. res.status(405).send('method not allowed')
  489. return
  490. });
  491.  
  492. app
  493. .route("/v1/messages/:messageID")
  494. .patch((req, res) => {
  495. if (!req.get("X-User") || req.get("X-User").length == 0) {
  496. res.setHeader('Content-Type', 'text/plain');
  497. res.status(401).send("Unauthorized");
  498. return;
  499. }
  500. if (req.params.messageID.length != 24) {
  501. res.setHeader('Content-Type', 'text/plain');
  502. res.status(403).send("Invalid message ID");
  503. return;
  504. }
  505. let messageID = new mongo.ObjectId(req.params.messageID);
  506. const user = JSON.parse(req.header("X-User"));
  507. console.log("user", user)
  508. MongoClient.connect(url, async function (err, db) {
  509. if (err) throw err;
  510. let dbo = db.db("mydb");
  511. const result = await dbo.collection("messages").findOne({ _id: messageID });
  512. console.log("msg result", result);
  513. if (user.id != result.creator.id) {
  514. res.setHeader('Content-Type', 'text/plain');
  515. res.status(403).send("Unauthorized user or messageID does not exist");
  516. return;
  517. } else {
  518. console.log("user in else", user)
  519. console.log("user in else", user._id)
  520.  
  521. dbo
  522. .collection("messages")
  523. .findOneAndUpdate(
  524. { _id: messageID },
  525. { $set: { body: req.body.body, editedAt: new Date() } },
  526. { returnOriginal: false },
  527. async (err, document) => {
  528. if (err) throw err;
  529. let result = document.value;
  530. let channelMembers = [];
  531. const foundChannel = await dbo.collection("channels").findOne({ _id: result.channelID })
  532. foundChannel.members && foundChannel.private && foundChannel.members.forEach(member => {
  533. channelMembers.push(member.id);
  534. });
  535. const event = {
  536. type: "message-update",
  537. message: result,
  538. userIDs: channelMembers
  539. };
  540. getChannel().sendToQueue(process.env.RABBITMQADDR, new Buffer(JSON.stringify(event)), { persistent: true });
  541. res.setHeader('Content-Type', 'application/json');
  542. res.status(200);
  543. result.id = result._id;
  544. res.json(result);
  545. db.close();
  546. return
  547. }
  548. );
  549. }
  550. });
  551. })
  552. .delete((req, res) => {
  553. if (!req.get("X-User") || req.get("X-User").length == 0) {
  554. res.setHeader('Content-Type', 'text/plain');
  555. res.status(401).send("Unauthorized");
  556. return;
  557. }
  558.  
  559. console.log("--------------------", req.params)
  560. console.log("--------------------", req.params.messageID)
  561. if (req.params.messageID.length != 24) {
  562. res.setHeader('Content-Type', 'text/plain');
  563. res.status(403).send("Invalid message ID");
  564. return;
  565. }
  566. let messageID = new mongo.ObjectId(req.params.messageID);
  567. const currentUser = JSON.parse(req.header("X-User"));
  568.  
  569. MongoClient.connect(url, async (err, db) => {
  570. if (err) throw err;
  571. let dbo = db.db("mydb");
  572. const result = await dbo.collection("messages").findOne({ _id: messageID });
  573. console.log("ID----------------------", result.creator.id);
  574. console.log("ID----------------------", currentUser.id);
  575. console.log("ID----------------------", currentUser);
  576. console.log("ID----------------------", result.creator);
  577.  
  578. console.log("ID----------------------", typeof currentUser);
  579. console.log("ID----------------------", typeof result.creator);
  580.  
  581. if (JSON.stringify(result.creator.id) != JSON.stringify(currentUser.id)) {
  582. res.setHeader('Content-Type', 'text/plain');
  583. res.status(403).send("Unauthorized user or messageID does not exist");
  584. return;
  585. } else {
  586. dbo.collection("messages").remove({ _id: messageID }, async (err, deleted) => {
  587. if (err) throw err;
  588. let channelMembers = [];
  589. const foundChannel = await dbo.collection("channels").findOne({ _id: result.channelID })
  590. foundChannel.members && foundChannel.private && foundChannel.members.forEach(member => {
  591. channelMembers.push(member.id);
  592. });
  593. const event = {
  594. type: "message-delete",
  595. messageID: result.id,
  596. userIDs: channelMembers
  597. };
  598. getChannel().sendToQueue(process.env.RABBITMQADDR, new Buffer(JSON.stringify(event)), { persistent: true });
  599. res.setHeader('Content-Type', 'text/plain');
  600. res.status(200).send(`Message with ID ${messageID} was successful deleted!`);
  601. return;
  602. });
  603. }
  604. });
  605. })
  606. .all((req, res) => {
  607. res.setHeader('Content-Type', 'text/plain')
  608. res.status(405).send('method not allowed')
  609. });
  610.  
  611.  
  612. //start the server listening on host:port
  613. app.listen(parseInt(port), () => {
  614. console.log(`server is listening at http://${addr}...`);
  615. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement