Advertisement
Guest User

Untitled

a guest
Nov 8th, 2017
193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.17 KB | None | 0 0
  1. ------------------ Main.js ------------------
  2.  
  3.  
  4. var app = require('express');
  5. var server = require('http').createServer(app);
  6. var io = require('socket.io')(server);
  7. var mysql = require('mysql');
  8. var cluster = require('cluster');
  9. let bodyParser = require('body-parser');
  10. let handle = require('./controllers/apicontroller.js');
  11.  
  12.  
  13. ///////////////////////////////////////////////////////////////////////////
  14. //Create MySql Connections///
  15. ///////////////////////////////////////////////////////////////////////////
  16. var connection = mysql.createPool({
  17. host: "",
  18. user: "",
  19. password: "",
  20. database: ""
  21. });
  22.  
  23. if (cluster.isMaster) {
  24.  
  25. cluster.fork();
  26. cluster.fork();
  27. cluster.on('online', function(worker) {
  28. console.log('Worker ' + worker.process.pid + ' is online');
  29. });
  30. cluster.on('exit', function(worker, code, signal) {
  31. console.log('Worker ' + worker.process.pid + ' died with code: ' + code + ', and signal: ' + signal);
  32. console.log('Starting a new worker');
  33. cluster.fork();
  34. });
  35.  
  36. } else {
  37.  
  38. ///////////////////////////////////////////////////////////////////////////
  39. //Handle API Requests///
  40. ///////////////////////////////////////////////////////////////////////////
  41. app.use(bodyParser.json());
  42. app.use(function(req, res, next) {
  43. res.setHeader('Access-Control-Allow-Origin', '*');
  44. res.header("Access-Control-Allow-Credentials: true");
  45. res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  46. next();
  47. });
  48.  
  49. app.post('/api/v1/relay', function(request, response) {
  50. console.log('Worker ' + cluster.worker.id + ': Processing..')
  51.  
  52. //check customers subscription
  53. let key = request.body['public_key']
  54. let queryingString = 'SELECT * FROM users_app WHERE public_key = ?';
  55.  
  56. connection.query(queryingString, [key], function(err, result, fields) {
  57. if (err) throw err;
  58.  
  59. if (request.body['public_key'] !== result[0]['public_key'] ||
  60. request.body['private_key'] !== result[0]['private_key'] ||
  61. !request.body['channel'] || !request.body['event']) {
  62. //log this to a file later get origin for tracking
  63. console.log('bad request from: ');
  64. return response.sendStatus(400);
  65. }
  66. //get the user id of this customers
  67. var identifier = result[0]['users_app_id'];
  68. var customer_id = result[0]['user_id'];
  69. handle.thisRequest(request, response, io, connection,
  70. identifier, customer_id, app);
  71. });
  72. });
  73.  
  74. server.listen(8081, function() {
  75. console.log('Process ' + process.pid + ' is listening to all incoming requests');
  76. });
  77.  
  78. server.on('close', function() {
  79. connection.end();
  80. })
  81. }
  82.  
  83.  
  84.  
  85.  
  86.  
  87.  
  88. ------------ API Controller -----------
  89.  
  90. let limit = require('./ratelimitcontroller.js');
  91.  
  92. module.exports = {
  93. thisRequest: function(request, response, io, connection,
  94. identifier, customer_id){
  95.  
  96. var key = customer_id;
  97. var queryingString = 'SELECT * FROM users WHERE id = ?';
  98.  
  99. connection.query(queryingString, [key], function(err, result, fields) {
  100. if (err) throw err;
  101. switch(result[0]['subscription']) {
  102. case 'Sandbox':
  103. limit.sandboxPlan(request, response, io, connection,
  104. identifier, customer_id);
  105. break;
  106. case 'Small':
  107. limit.smallPlan(request, response, io, connection,
  108. identifier, customer_id);
  109. break;
  110. case 'Medium':
  111. limit.mediumPlan(request, response, io, connection,
  112. identifier, customer_id);
  113. break;
  114. case 'Large':
  115. limit.largePlan(request, response, io, connection,
  116. identifier, customer_id);
  117. break;
  118. }
  119. });
  120. }
  121. };
  122.  
  123.  
  124. ---------- Sandbox ----------
  125. module.exports = {
  126. sandboxPlan: function(request, response, io, connection, identifier, customer_id){
  127. var RateLimiter = require('limiter').RateLimiter;
  128. var limiter = new RateLimiter(3, 'second', true); // fire CB immediately
  129.  
  130. // Immediately send 429 header to client when rate limiting is in effect
  131. limiter.removeTokens(1, function(err, remainingRequests) {
  132. if (remainingRequests < 1) {
  133. console.log('Customer: ' + customer_id + ' has reached their limit.')
  134. response.writeHead(429, {'Content-Type': 'text/plain;charset=UTF-8'});
  135. return response.end('429 Too Many Requests - your IP is being rate limited');
  136. } else {
  137. //pass the data to the customers front end
  138. let event = request.body['event'];
  139. let data = request.body.data;
  140. io.emit(event, data);
  141.  
  142. //let customer know request was successfull
  143. response.sendStatus(200);
  144.  
  145. //track customers usage
  146. return track.customersMessage(identifier, connection);
  147. }
  148. });
  149. }
  150. }
  151.  
  152.  
  153. ------------------- useage controller ----------
  154. module.exports = {
  155. customersMessage: function(identifier, connection){
  156. var key = identifier;
  157. var getAppInformation = 'SELECT * FROM users_app_details WHERE users_app_id = ?';
  158.  
  159. connection.query(getAppInformation, [key], function(err, result, fields) {
  160. if (err) throw err;
  161. let appID = result[0]['users_app_id'];
  162. let messageTotal = result[0]['messages_total'] + 1;
  163. let messageCycle = result[0]['messages_cycle'] + 1;
  164.  
  165. var sql = "UPDATE users_app_details set messages_total = ? , messages_cycle = ? WHERE users_app_id = ?";
  166. connection.query(sql, [messageTotal, messageCycle, appID], function(err, result) {
  167. if (err) throw err;
  168. console.log('processed');
  169. });
  170. });
  171. }
  172. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement