Advertisement
Guest User

Untitled

a guest
Oct 27th, 2016
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.04 KB | None | 0 0
  1. {
  2. "ID": 0 // a number indicating which function to call
  3. "msg": "{
  4. // embedded JSON contains the data
  5. .....
  6. }"
  7. }
  8.  
  9. /* Library to add date and time to any console.log */
  10. require('log-timestamp');
  11. /* Asynchronous JSON parse library */
  12. var parseJSON = require('json-parse-async');
  13. /* Asynchronous JSON stringify library */
  14. var asyncJSON = require('async-json');
  15. /* Keymetrics advance metrics */
  16. var pmx = require('pmx').init({
  17. http: false, // HTTP routes logging (default: true)
  18. ignore_routes: [], // Ignore http routes (Default: [])
  19. errors: true, // Exceptions loggin (default: true)
  20. custom_probes: false, // Auto expose JS Loop Latency and HTTP req/s
  21. network: true, // Network monitoring at the application level
  22. ports: false // Shows which ports your app is listening on (default: false)
  23. });
  24. var probe = pmx.probe();
  25. // The counter will start at 0
  26. var counter = probe.counter({
  27. name: 'Current connected players'
  28. });
  29. /* Encryption situp */
  30. var crypto = require('crypto');
  31. var key = new Buffer([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]);
  32. var iv = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]);
  33. var cipherAlgorithmUsed = 'aes-256-cbc';
  34. /* Encrypt buffer */
  35. function encrypt(textBuffer) {
  36. try {
  37. var cipher = crypto.createCipheriv(cipherAlgorithmUsed, key, iv);
  38. var crypted = Buffer.concat([cipher.update(textBuffer), cipher.final()]);
  39. return crypted;
  40. } catch (err) {
  41. // Handle the error here.
  42. console.error('Error trying to encrypt, ' + err);
  43. return '';
  44. }
  45. return '';
  46. }
  47. /* Decrypt buffer */
  48. function decrypt(encryptedBuffer) {
  49. try {
  50. var decipher = crypto.createDecipheriv(cipherAlgorithmUsed, key, iv);
  51. var dec = Buffer.concat([decipher.update(encryptedBuffer), decipher.final()]);
  52. return dec;
  53. } catch (err) {
  54. // Handle the error here.
  55. console.error('Error trying to decrypt, ' + err);
  56. return '';
  57. }
  58. return '';
  59. }
  60. /* Database Connection */
  61. var ConnectionPool = require('tedious-connection-pool');
  62. var DBTDSConnection = require('tedious').Connection;
  63. var Request = require('tedious').Request;
  64. var poolConfig = {
  65. min: 10, // The minimun of connections there can be in the pool. Default = 10
  66. max: 1000, //The maximum number of connections there can be in the pool. Default = 50
  67. log: false
  68. };
  69. var dBConnectionconfig = {
  70. userName: 'kskskhr@939jdn',
  71. password: 'kwpfnekososken',
  72. server: 'jjsmcmnxjfhsn.database.windows.net',
  73. options: {
  74. requestTimeout: 0,
  75. debug: {
  76. packet: false,
  77. data: false,
  78. payload: false,
  79. token: false,
  80. log: false
  81. },
  82. encrypt: true,// If you are on Microsoft Azure, you need this:
  83. database: 'ylldkgnje_db'
  84. }
  85. };
  86. //create the pool
  87. var pool = new ConnectionPool(poolConfig, dBConnectionconfig);
  88. pool.on('error', function(err) {
  89. console.error('Error when trying to create DB connection pool' + err);
  90. });
  91. /* Login Server */
  92. var net = require('net');
  93. var HOST = '127.0.0.1';
  94. var PORT = 4000; // nginx is used infront as a reverse proxy
  95. var server = net.createServer(); // Create a server instance
  96. server.listen(PORT, HOST);
  97. onClientConnected_ServerEvent = function(sock) {
  98. counter.inc(); // Increment the counter, metrics
  99. sock.on('data', function(data) { // data from client
  100. parseJSON(decrypt(data), function(err, content) {
  101. if (err) {
  102. console.error('Error when trying to parse json received from client, json received is ' + data + ', and the error is ' + err);
  103. sock.end();
  104. } else {
  105. switch (content.reqID) {
  106. case 0:
  107. setPlayerData(sock, content.msg);
  108. break;
  109. case 1:
  110. getPlayerData(sock, content.msg);
  111. break;
  112. case 2:
  113. createUser(sock, content.msg);
  114. break;
  115. default:
  116. console.log('request id sent doesnt match any of the cases, id sent is ' + content.reqID);
  117. return;
  118. }
  119. }
  120. });
  121. });
  122. sock.on('close', function(data) {
  123. counter.dec(); // Decrement the counter, metrics
  124. });
  125. sock.on('timeout', function(data) {
  126. });
  127. }
  128. /*
  129. Emitted when an error occurs. The 'close' event will be called directly following this event. See example in discussion of server.listen.
  130. */
  131. onError_ServerEvent = function(err) {
  132. // handle errors here
  133. console.error('onError_ServerEvent occured, ' + err);
  134. throw err;
  135. }
  136. server.on('connection', onClientConnected_ServerEvent);
  137. server.on('error', onError_ServerEvent);
  138. var PlayerData = function() {
  139. this.appVersionAndroid = "2.7",
  140. this.appVersioniOS = "2.7",
  141. this.kickStatus = "true",
  142. this.maxNumOfPlayerInRoom = "10",
  143. this.userName = "potato",
  144. this.coin = 2311,
  145. this.ruby = 22,
  146. this.rep = 352,
  147. this.driftMax = 2133,
  148. this.dailyRepsGiveAway = 132,
  149. this.equipedProducts = "3-1-2-1,3-6-2-1,2-1-1-1",
  150. this.boughtProducts = "3-1-2-1,3-6-2-1,2-1-1-1";
  151. }
  152. // case 0
  153. function setPlayerData(sock, dataSent) { // update player data
  154. // parse json, then update player row in DB
  155. parseJSON(dataSent, function(err, playerDataSent) {
  156. if (err) {
  157. console.error('(setPlayerData) Error when trying to parse json received from switch statment, json received is ' + dataSent + ', and the error is ' + err);
  158. } else {
  159. pool.acquire(function(err, connection) { //acquire a db connection from connection pool
  160. if (err) {
  161. console.error('(setPlayerData) Error when trying to acquire a DB connection from pool, ' + err);
  162. return;
  163. }
  164. var sqlUpdatePlayerDataQuery = "UPDATE PlayerDataTable SET rep=" + playerDataSent.rep + ", driftDistance=" + playerDataSent.driftMax + ", coin = " + playerDataSent.coin + ", ruby = " + playerDataSent.ruby + ", dailyReps = " + playerDataSent.dailyRepsGiveAway + ", boughtProducts = '" + playerDataSent.boughtProducts + "', equippedProducts = '" + playerDataSent.equipedProducts + "', lastUpdated = GETDATE() WHERE UserName ='" + playerDataSent.userName + "'";
  165. var request = new Request(sqlUpdatePlayerDataQuery, function(err, rowCount) {
  166. if (err) {
  167. sock.write(encrypt('0'));
  168. console.error('(setPlayerData) Error when trying to execute SQL update player data, ' + err);
  169. return;
  170. }
  171. if (rowCount == 1) {
  172. // 1 row updated
  173. sock.write(encrypt('1'));
  174. } else {
  175. sock.write(encrypt('0'));
  176. }
  177. //release the connection back to the pool when finished
  178. connection.release();
  179. });
  180. connection.execSql(request);
  181. });
  182. }
  183. });
  184. }
  185. // case 1
  186. function getPlayerData(sock, dataSent) { // get player data when game starts
  187. // dataSent will have the username
  188. // get all player data, parse, then send
  189. // acquire a db connection from connection pool
  190. pool.acquire(function(err, connection) {
  191. if (err) {
  192. console.error('(getPlayerData) Error when trying to acquire a DB connection from pool, ' + err);
  193. return;
  194. }
  195. //use the connection as normal
  196. var request = new Request("select * from PlayerDataTable where UserName = '" + dataSent + "'", function(err, rowCount) {
  197. if (err) {
  198. sock.write(encrypt('0'));
  199. console.error('(getPlayerData) Error when trying to execute SQL select * from , ' + err);
  200. return;
  201. }
  202. if (rowCount < 1) {
  203. // error retrieving user
  204. sock.write(encrypt('0'));
  205. }
  206. //release the connection back to the pool when finished
  207. connection.release();
  208. });
  209. request.on('row', function(columns) {
  210. var playerData = new PlayerData();
  211. columns.forEach(function(column) {
  212. if (column.metadata.colName === "UserName") {
  213. playerData.userName = column.value;
  214. } else if (column.metadata.colName === "rep") {
  215. playerData.rep = column.value;
  216. } else if (column.metadata.colName === "driftDistance") {
  217. playerData.driftMax = column.value;
  218. } else if (column.metadata.colName === "coin") {
  219. playerData.coin = column.value;
  220. } else if (column.metadata.colName === "ruby") {
  221. playerData.ruby = column.value;
  222. } else if (column.metadata.colName === "boughtProducts") {
  223. playerData.boughtProducts = column.value;
  224. } else if (column.metadata.colName === "equippedProducts") {
  225. playerData.equipedProducts = column.value;
  226. } else if (column.metadata.colName === "dailyReps") {
  227. playerData.dailyRepsGiveAway = column.value;
  228. }
  229. });
  230.  
  231. asyncJSON.stringify(playerData, function(err, jsonValue) {
  232. if (err) {
  233. console.error('(getPlayerData) Error when trying to stringify json, json is ' + playerData + ', and the error is ' + err);
  234. } else {
  235. sock.write(encrypt(jsonValue));
  236. }
  237. });
  238. });
  239. connection.execSql(request);
  240. });
  241. }
  242. // case 2
  243. function createUser(sock, dataSent) { // create a new username for a player
  244. // dataSent will have the username
  245. // if query succeeded print 1 else 0
  246. //acquire a db connection from connection pool
  247. pool.acquire(function(err, connection) {
  248. if (err) {
  249. console.error('(createUser) Error when trying to acquire a DB connection from pool, ' + err);
  250. sock.write(encrypt('0'));
  251. return;
  252. }
  253. //console.error('name sent is ' + name);
  254. //use the connection as normal
  255. var request = new Request("INSERT INTO PlayerDataTable (username,coin,ruby) VALUES ('" + dataSent + "',150,20)", function(err, rowCount) {
  256. if (err) {
  257. console.error('(createUser) Error when trying to execute SQL INSERT INTO , ' + err);
  258. sock.write(encrypt('0'));
  259. } else {
  260. sock.write(encrypt('1'));
  261. }
  262. //release the connection back to the pool when finished
  263. connection.release();
  264. });
  265. connection.execSql(request);
  266. });
  267. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement