Advertisement
Guest User

app.js

a guest
Sep 29th, 2017
514
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * Copyright 2015 IBM Corp. All Rights Reserved.
  3.  *
  4.  * Licensed under the Apache License, Version 2.0 (the "License");
  5.  * you may not use this file except in compliance with the License.
  6.  * You may obtain a copy of the License at
  7.  *
  8.  *      http://www.apache.org/licenses/LICENSE-2.0
  9.  *
  10.  * Unless required by applicable law or agreed to in writing, software
  11.  * distributed under the License is distributed on an "AS IS" BASIS,
  12.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13.  * See the License for the specific language governing permissions and
  14.  * limitations under the License.
  15.  */
  16.  
  17. 'use strict';
  18.  
  19. var express = require('express'); // app server
  20. var bodyParser = require('body-parser'); // parser for post requests
  21. var Conversation = require('watson-developer-cloud/conversation/v1'); // watson sdk
  22. var fs = require('fs');
  23. var http = require('http');
  24. var https = require('https');
  25. var privateKey  = fs.readFileSync('./newkey.pem', 'utf8');
  26. var certificate = fs.readFileSync('./newcert.pem', 'utf8');
  27. var credentials = {key: privateKey, cert: certificate};
  28. var cors = require('cors')
  29. var request = require('request');
  30. var cookieParser = require('cookie-parser');
  31. var helmet = require('helmet')
  32. var randomstring = require('randomstring');
  33. var crypto = require('crypto');
  34.  
  35. var app = express();
  36.  
  37.  
  38. // Bootstrap application settings
  39. app.use(helmet({
  40.   frameguard: false
  41. }));
  42. app.use(express.static('./public')); // load UI from public folder
  43. app.use(bodyParser.json());
  44. app.use(bodyParser.urlencoded({ extended: true }));
  45. app.use(cors());
  46. app.use(cookieParser());
  47. app.use(function (req, res, next) {
  48.     res.setHeader('Access-Control-Allow-Origin', '*');
  49.     res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
  50.     res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
  51.     next();
  52. });
  53.  
  54. var httpServer = http.createServer(app);
  55. var httpsServer = https.createServer(credentials, app);
  56.  
  57. httpServer.listen(8080);
  58. httpsServer.listen(443);
  59. // Create the service wrapper
  60. var conversation = new Conversation({
  61.     // If unspecified here, the CONVERSATION_USERNAME and CONVERSATION_PASSWORD env properties will be checked
  62.     // After that, the SDK will fall back to the bluemix-provided VCAP_SERVICES environment property
  63.     // username: '<username>',
  64.     // password: '<password>',
  65.     // url: 'https://gateway.watsonplatform.net/conversation/api',
  66.     version_date: Conversation.VERSION_DATE_2017_04_21
  67. });
  68.  
  69. function checkToken(req, res, next){
  70.    
  71.     if(req.path === '/AuthBdesk' || req.path === '/verificar-token'){
  72.         next();
  73.     } else {
  74.         var extraData = req.cookies.extraData;
  75.         var token = req.cookies.tokenbdesk;
  76.        
  77.         var sha_password = crypto.createHash('sha256').update('q7KuDO&8DAuLU09').digest("hex");
  78.         var key = 'chatbot-watson' + sha_password + extraData + 'https://hmggabi.aguiabranca.com.br/AuthBdesk'
  79.         var generated_token = crypto.createHash('sha256').update(key).digest("hex");
  80.        
  81.        
  82.         if(token == generated_token){
  83.             next();
  84.         } else {
  85.             res.status(403).end('Forbidden');
  86.         }
  87.     }
  88. }
  89.  
  90. app.use(checkToken);
  91.  
  92. app.get('/AuthBdesk', function(req, res){
  93.     var token = req.query.token;
  94.     res.cookie("tokenbdesk", token);
  95.     res.redirect("http://hmggabi.aguiabranca.com.br/iframe-gab.html");
  96. });
  97.  
  98. app.post('/verificar-token', function(req, res){
  99.     var sha_password = crypto.createHash('sha256').update('q7KuDO&8DAuLU09').digest("hex");
  100.     var key = 'chatbot-watson' + sha_password + req.body.extraData + 'https://hmggabi.aguiabranca.com.br/AuthBdesk'
  101.     var generated_token = crypto.createHash('sha256').update(key).digest("hex");
  102.  
  103.    
  104.     if(req.body.token == generated_token){
  105.         res.send("success");
  106.     } else {
  107.         res.clearCookie("token-bdesk");
  108.         res.send("error");
  109.     }
  110. });
  111.  
  112. // Endpoint to be call from the client side
  113. app.post('/api/message', function(req, res) {
  114.     var workspace = process.env.WORKSPACE_ID || '<workspace-id>';
  115.     if (!workspace || workspace === '<workspace-id>') {
  116.         return res.json({
  117.             'output': {
  118.                 'text': 'The app has not been configured with a <b>WORKSPACE_ID</b> environment variable. Please refer to the ' + '<a href="https://github.com/watson-developer-cloud/conversation-simple">README</a> documentation on how to set this variable. <br>' + 'Once a workspace has been defined the intents may be imported from ' + '<a href="https://github.com/watson-developer-cloud/conversation-simple/blob/master/training/car_workspace.json">here</a> in order to get a working application.'
  119.             }
  120.         });
  121.     }
  122.     var payload = {
  123.         workspace_id: workspace,
  124.         context: req.body.context || {},
  125.         input: req.body.input || {}
  126.     };
  127.  
  128.     // Send the input to the conversation service
  129.     conversation.message(payload, function(err, data) {
  130.         if (err) {
  131.             return res.status(err.code || 500).json(err);
  132.         }
  133.         return res.header("Access-Control-Allow-Origin", "*")
  134.             .header("Access-Control-Allow-Headers", "X-Requested-With")
  135.             .json(updateMessage(payload, data));
  136.     });
  137. });
  138.  
  139. app.post('/abrir-chamado', function(req, res){
  140.    
  141.     var headers = {
  142.         'Authorization': 'Bearer gAAAACiGdw5NEUH4ir-qZFwJNs9Kc4B2H5d8JEsEVhPEtn4-xSUMDg735c313I8A1ZRAhqkLCigg73ZJL2ofgHhPU7L8bqtOHEYsGuV6IgCL4SQCGHLZEdbnG-tEBAg7NRzrqsZQhUjmugztEO0vKeHci7aOMA8lxAA51Q60gMnKRl3VFAEAAIAAAABOm_ptCKu1pBdhIPWKOEZW750p2leNSM4eCFv-I8l7J7p0uTOnVk0Ifhezl8V1btLYUHnpHwD0m0K1OmSGXIk41Sx1dfaJL0tQDYu4mDFiJU-_Nrw-tbAj6P28Da09eUS2LUrfwnETX5KWOyJECWhXHCFk0liR9wcPVVNwtXyxfm7pfSfTwGo2qb9B1dt1CEM6zdy93c66-XLXFN89Uoub88Va9uErhkwYTeWwkZMgp5WJm6Kw5x6ara053usmmTtXQyLsOC3OYOUR2Jzs1EEnG3539IkTJhdYp4EFv69VZZeChJ79hBn4rMl1t-kBA3CT_cev52Fz3ZmtpkhRENfvy19lUC50n6O9Ow6jMTcYKQ',
  143.         'Content-Type': 'application/json'
  144.     }
  145.        
  146.     if (req.body.cpf){
  147.         var participanteOptions = {
  148.             //TODO: Change user name
  149.             url: 'http://hmgsos.aguiabranca.com.br/ASKRest/v1/participantes/793/pesquisar/' + req.body.cpf,
  150.             method: 'GET',
  151.             headers: headers,
  152.         }
  153.         request(participanteOptions, function (error, response, body) {
  154.             if(JSON.parse(body).length > 0){
  155.                 var papeis = {
  156.                     'ANTE': '{ IdParticipante : ' + req.body.usuario + ', IdTipoPapel : 1 }',
  157.                     "COP": [JSON.parse(body)[0].Id]
  158.                 };
  159.             } else {
  160.                 var papeis = {
  161.                     'ANTE': '{ IdParticipante : ' + req.body.usuario + ', IdTipoPapel : 1 }'
  162.                 };
  163.             }
  164.             var options = {
  165.                 url: 'https://hmgsos.aguiabranca.com.br/ASKRest/v1/requisicoes/abrir',
  166.                 method: 'POST',
  167.                 headers: headers,
  168.                 body: JSON.stringify({
  169.                     'Formulario': 73,
  170.                     'Conjuntos': {
  171.                         'DadosBasicos': {
  172.                             'Assunto': 'Atendimento Gabi',
  173.                             'Descricao': 'O cliente deseja obter ajuda para ' + req.body.tipoChamado,
  174.                             'DescricaoOrigem': 'Chatbot',
  175.                             'Atividade': req.body.atividade
  176.                         },
  177.                         'Papeis': papeis
  178.                     }
  179.                 })
  180.             }  
  181.             request(options, function (error, response, body) {
  182.                 res.send(body);
  183.             });
  184.         });
  185.     } else {
  186.         var options = {
  187.             url: 'https://hmgsos.aguiabranca.com.br/ASKRest/v1/requisicoes/abrir',
  188.             method: 'POST',
  189.             headers: headers,
  190.             body: JSON.stringify({
  191.                 'Formulario': 73,
  192.                 'Conjuntos': {
  193.                     'DadosBasicos': {
  194.                         'Assunto': 'Atendimento Gabi',
  195.                         'Descricao': 'O cliente deseja obter ajuda para ' + req.body.tipoChamado,
  196.                         'DescricaoOrigem': 'Chatbot',
  197.                         'Atividade': req.body.atividade
  198.                     },
  199.                     'Papeis': {
  200.                         'ANTE': '{ IdParticipante : ' + req.body.usuario + ', IdTipoPapel : 1 }'
  201.                     }
  202.                 }
  203.             })
  204.         }  
  205.         request(options, function (error, response, body) {
  206.             res.send(body);
  207.         });
  208.     }
  209. });
  210.  
  211. app.post('/atualizar-chamado', function(req, res){
  212.    
  213.     var headers = {
  214.         'Authorization': 'Bearer gAAAACiGdw5NEUH4ir-qZFwJNs9Kc4B2H5d8JEsEVhPEtn4-xSUMDg735c313I8A1ZRAhqkLCigg73ZJL2ofgHhPU7L8bqtOHEYsGuV6IgCL4SQCGHLZEdbnG-tEBAg7NRzrqsZQhUjmugztEO0vKeHci7aOMA8lxAA51Q60gMnKRl3VFAEAAIAAAABOm_ptCKu1pBdhIPWKOEZW750p2leNSM4eCFv-I8l7J7p0uTOnVk0Ifhezl8V1btLYUHnpHwD0m0K1OmSGXIk41Sx1dfaJL0tQDYu4mDFiJU-_Nrw-tbAj6P28Da09eUS2LUrfwnETX5KWOyJECWhXHCFk0liR9wcPVVNwtXyxfm7pfSfTwGo2qb9B1dt1CEM6zdy93c66-XLXFN89Uoub88Va9uErhkwYTeWwkZMgp5WJm6Kw5x6ara053usmmTtXQyLsOC3OYOUR2Jzs1EEnG3539IkTJhdYp4EFv69VZZeChJ79hBn4rMl1t-kBA3CT_cev52Fz3ZmtpkhRENfvy19lUC50n6O9Ow6jMTcYKQ',
  215.         'Content-Type': 'application/json'
  216.     }
  217.     var options = {
  218.         url: 'https://hmgsos.aguiabranca.com.br/ASKRest/v1/requisicoes/' + req.body.chamadoID  + '/acoes',
  219.         method: 'POST',
  220.         headers: headers,
  221.         body: JSON.stringify({
  222.                             'Id': 'Restringir Acompanhamento [ACO]',
  223.                             'Descricao': req.body.log
  224.                         })
  225.     }
  226.     request(options, function (error, response, body) {
  227.         res.send(body);
  228.     });
  229. });
  230.  
  231. app.post('/fechar-chamado', function(req, res){
  232.    
  233.     var headers = {
  234.         'Authorization': 'Bearer gAAAACiGdw5NEUH4ir-qZFwJNs9Kc4B2H5d8JEsEVhPEtn4-xSUMDg735c313I8A1ZRAhqkLCigg73ZJL2ofgHhPU7L8bqtOHEYsGuV6IgCL4SQCGHLZEdbnG-tEBAg7NRzrqsZQhUjmugztEO0vKeHci7aOMA8lxAA51Q60gMnKRl3VFAEAAIAAAABOm_ptCKu1pBdhIPWKOEZW750p2leNSM4eCFv-I8l7J7p0uTOnVk0Ifhezl8V1btLYUHnpHwD0m0K1OmSGXIk41Sx1dfaJL0tQDYu4mDFiJU-_Nrw-tbAj6P28Da09eUS2LUrfwnETX5KWOyJECWhXHCFk0liR9wcPVVNwtXyxfm7pfSfTwGo2qb9B1dt1CEM6zdy93c66-XLXFN89Uoub88Va9uErhkwYTeWwkZMgp5WJm6Kw5x6ara053usmmTtXQyLsOC3OYOUR2Jzs1EEnG3539IkTJhdYp4EFv69VZZeChJ79hBn4rMl1t-kBA3CT_cev52Fz3ZmtpkhRENfvy19lUC50n6O9Ow6jMTcYKQ',
  235.         'Content-Type': 'application/json'
  236.     }
  237.     var options = {
  238.         url: 'https://hmgsos.aguiabranca.com.br/ASKRest/v1/requisicoes/' + req.body.chamadoID + '/acoes',
  239.         method: 'POST',
  240.         headers: headers,
  241.         body: JSON.stringify({
  242.                             'Id': 'Concluir Requisição [CONC]',
  243.                             'Descricao': req.body.log
  244.                         })
  245.     }
  246.     request(options, function (error, response, body) {
  247.         res.send(body);
  248.     });
  249. });
  250.  
  251. app.post('/ps', function(req, res) {
  252.     const shell = require('node-powershell');
  253.  
  254.     if(req.body.name && req.body.cpf){
  255.         let ps = new shell({
  256.             executionPolicy: 'Bypass',
  257.             noProfile: true
  258.         });
  259.  
  260.         ps.addCommand('exec/ExecResetAD.ps1 ' + req.body.name + ' ' + req.body.cpf)
  261.         ps.invoke()
  262.             .then(output => {
  263.                 res.json({content: "True"});
  264.             })
  265.             .catch(err => {
  266.                 res.json({error: 'Something wrong happened'});
  267.                 ps.dispose();
  268.             });
  269.     } else {
  270.         res.json({error: "Parameter 'name' and/or 'cpf' not found."});
  271.     }
  272. });
  273.  
  274. app.post('/sh', function(req, res) {
  275.     var child_process = require('child_process');
  276.    
  277.     if(req.body.name){
  278.         var bat = require.resolve('./exec/execSisdia.bat');
  279.         var ls = child_process.spawn(bat, [ req.body.name ]);
  280.  
  281.         ls.on('exit', function (code) {
  282.             console.log('child process exited with code ' + code);
  283.             if(code == 1){
  284.                 res.json({error: "User not found"});
  285.             } else {
  286.                 res.json({content: 'True'});
  287.             }
  288.         });
  289.     } else {
  290.         res.json({error: "Parameter 'name' not found."});
  291.     }
  292. });
  293.  
  294. /**
  295.  * Updates the response text using the intent confidence
  296.  * @param  {Object} input The request to the Conversation service
  297.  * @param  {Object} response The response from the Conversation service
  298.  * @return {Object}          The response with the updated message
  299.  */
  300. function updateMessage(input, response) {
  301.     var responseText = null;
  302.     if (!response.output) {
  303.         response.output = {};
  304.     } else {
  305.         return response;
  306.     }
  307.     if (response.intents && response.intents[0]) {
  308.         var intent = response.intents[0];
  309.         // Depending on the confidence of the response the app can return different messages.
  310.         // The confidence will vary depending on how well the system is trained. The service will always try to assign
  311.         // a class/intent to the input. If the confidence is low, then it suggests the service is unsure of the
  312.         // user's intent . In these cases it is usually best to return a disambiguation message
  313.         // ('I did not understand your intent, please rephrase your question', etc..)
  314.         if (intent.confidence >= 0.75) {
  315.             responseText = 'I understood your intent was ' + intent.intent;
  316.         } else if (intent.confidence >= 0.5) {
  317.             responseText = 'I think your intent was ' + intent.intent;
  318.         } else {
  319.             responseText = 'I did not understand your intent';
  320.         }
  321.     }
  322.     response.output.text = responseText;
  323.     return response;
  324. }
  325.  
  326. module.exports = app;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement