Advertisement
masquitos

Backend

Sep 14th, 2020 (edited)
188
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Старт сервера
  2. app.use(function(req, res, next) {
  3.   req.reqId = LogContext.getContext();
  4.   MyLogger.log(req.reqId, fileName, req.url);
  5.   next();
  6. });
  7.  
  8. // body parser
  9. app.use(
  10.   bodyParser.json({
  11.     limit: "5mb"
  12.   })
  13. );
  14.  
  15.  
  16. app.use((req, res, next) => {
  17.   asyncLocalStorage.run(new Map(), () => {
  18.     asyncLocalStorage.getStore().set("requestId", uuid());
  19.     next();
  20.   });
  21. });
  22.  
  23.  
  24. app.use("/api", apiRouter);
  25. app.use("/public", publicRouter);
  26.  
  27. app.use("/api/helpdesk", helpDeskApiRouter);
  28. app.use("/public/helpdesk", helpDeskPublicRouter);
  29.  
  30.  
  31. server.listen(environment.port, environment.host, function() {
  32.   console.log(
  33.     "Node server started on %s://%s:%d",
  34.     environment.http_type,
  35.     environment.host,
  36.     environment.port
  37.   );
  38. });
  39.  
  40.  
  41.  
  42. // Роуетер экспресса
  43. router.use(publicRoutes.CONFORM, require("../../users/conform/conform"));
  44. router.use(publicRoutes.AUTH, require("../../users/auth/auth-router"));
  45. router.use(publicRoutes.REGISTER, require("../../users/register/registration"));
  46. router.use(publicRoutes.REFRESH, require("../../users/refresh/refresh-router"));
  47. router.use(publicRoutes.RESTORE, require("../../users/restore/restore"));
  48. router.use(publicRoutes.CHANGE_PASSWORD, require("../../users/change-password/changepassword"));
  49.  
  50. module.exports = router;
  51.  
  52. // Логика роутера экспресса
  53.  
  54. router.route("/").patch(refreshToken);
  55.  
  56. async function refreshToken(req, res) {
  57.   let body;
  58.   const myLogger = new MyLogger(req.reqId, fileName);
  59.   try {
  60.     const refreshLogic = new RefreshLogic(req.body.token, req.reqId);
  61.     const token = await refreshLogic.refreshToken();
  62.     body = requester.createBody({ token });
  63.   } catch (error) {
  64.     body = requester.createError(error);
  65.     myLogger.myErrorLogger(error);
  66.     myLogger.log("Send to user " + JSON.stringify(body));
  67.   }
  68.  
  69.   res.json(body);
  70. }
  71.  
  72.  
  73. // Бизнес логика
  74. class RefreshLogic extends CommonRefreshLogic {
  75.   constructor(token, logId) {
  76.     super(token, logId);
  77.   }
  78.  
  79.   checkRole() {
  80.     if (
  81.       this.decodedToken.role !== myRoles.USER &&
  82.       this.decodedToken.role !== myRoles.GUEST
  83.     ) {
  84.       const e = new MyError(errorCodes.INVALID_USER_ROLE, "");
  85.       this.myLogger.myErrorLogger(e);
  86.       throw e;
  87.     }
  88.   }
  89.  
  90.   async refreshToken() {
  91.     try {
  92.       this.myLogger.debug("refreshToken");
  93.       this.validateToken();
  94.       this.verifyToken();
  95.       this.checkRole();
  96.       await this.checkIsUserExist();
  97.       await this.compareChange();
  98.       await this.updateUserIdentity();
  99.       const token = tokenGenerator.getToken(this.user);
  100.       return token;
  101.     } catch (e) {
  102.       throw e;
  103.     }
  104.   }
  105. }
  106.  
  107. // Test example
  108.  
  109. describe("Тестирование авторизации", function() {
  110.   it("При успехе возращается токен", async () => {
  111.     await request(server)
  112.       .post("/public/auth")
  113.       .send({
  114.         email: "masquitos@mail.ru",
  115.         password: "12345"
  116.       })
  117.       .expect(res => {
  118.         assert.strictEqual(validator.isJWT(res.body.data.token), true);
  119.       });
  120.   });
  121.  
  122.   it(
  123.     "При не верном логине/пароле возращается ошибка с текстом " +
  124.       errorCodes.INVALID_USER_OR_PASSWORD.text,
  125.     async () => {
  126.       await request(server)
  127.         .post("/public/auth")
  128.         .send({
  129.           email: "masquitos@mail.ru",
  130.           password: "123456"
  131.         })
  132.         .expect(res => {
  133.           assert.strictEqual(
  134.             res.body.error.text,
  135.             errorCodes.INVALID_USER_OR_PASSWORD.text
  136.           );
  137.         });
  138.     }
  139.   );
  140. });
  141.  
  142. // socket.io get event
  143.  
  144.         socket.on(events.MESSAGES, async function(
  145.           conversationsMessages,
  146.           callback
  147.         ) {
  148.           try {
  149.             const userId = socket.decoded_token.id;
  150.             for (const convId of Object.keys(conversationsMessages)) {
  151.               const conversationId = parseInt(convId, 10);
  152.               const companion = await db_helper.getCompanion(
  153.                 userId,
  154.                 conversationId
  155.               );
  156.               const messages = conversationsMessages[conversationId];
  157.               await db_helper.saveMessages(conversationId, userId, messages);
  158.               const totalCount = await db_helper.getMessageTotalCount(
  159.                 conversationId
  160.               );
  161.               // Отправляем сообщение назад, что мы его получили.
  162.               // Отправляем сообщения участнику чата
  163.               messages.forEach(msg => {
  164.                 msg.totalCount = totalCount;
  165.               });
  166.               self.sendData(
  167.                 userId,
  168.                 companion.user_id,
  169.                 events.MESSAGES,
  170.                 messages
  171.               );
  172.             }
  173.  
  174.             callback(requester.createBody());
  175.           } catch (error) {
  176.             callback(requester.createError(error));
  177.             console.error("Не могу сохранить сообщения пользователя", error);
  178.           }
  179.         });
  180.  
  181. // socket.io send data
  182.  
  183.   sendData(fromId, toId, event, data, logId) {
  184.     const socket = this.getUserSocket(toId);
  185.     if (socket) {
  186.       socket.emit(event, data);
  187.       MyLogger.log(logId, fileName, "event " + event);
  188.     } else {
  189.       if (event === events.MESSAGES) {
  190.         mailWorker.sendNotifyMessage(fromId, toId, data);
  191.       }
  192.       if (event === events.TASK) {
  193.         data.subscriptions.forEach(id =>
  194.           mailWorker.sendNotifySubscriptions(toId, id, data.data)
  195.         );
  196.       }
  197.     }
  198.   }
  199.  
  200. // send email
  201.   async sendNotifyMessage(fromUserId, toUserId, messages) {
  202.     try {
  203.       const dbFromUser = await dbHelper.getUserById(fromUserId);
  204.       const dbToUser = await dbHelper.getUserById(toUserId);
  205.       if (dbToUser.role === myRoles.USER) {
  206.         const dbNotify = await dbHelper.getUserNotify(toUserId);
  207.         const notify = parser.parseNotify(dbNotify);
  208.         myLog.log(
  209.           "try sendNotifyMessage",
  210.           "from",
  211.           fromUserId,
  212.           "to",
  213.           toUserId,
  214.           notify
  215.         );
  216.         if (notify.isMessages) {
  217.           myLog.log("sendNotifyMessage", notify);
  218.           messages.forEach(el => {
  219.             mailSender.sendNotifyMessage(
  220.               dbFromUser.name,
  221.               dbToUser.email,
  222.               el.text
  223.             );
  224.           });
  225.         }
  226.       }
  227.     } catch (e) {
  228.       console.error("Error sendNotifyMessage : ", e.message);
  229.     }
  230.   }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement