Advertisement
Guest User

sdsds

a guest
Aug 13th, 2017
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var client = require("socket.io").listen(8001).sockets;
  2. var mysql = require("mysql");
  3. var colors = require("colors");
  4. var crypto = require("crypto");
  5. var sanitizer = require("sanitizer");
  6. var fs = require("fs");
  7.  
  8. var config = {
  9.     host: "localhost",
  10.     user: "root",
  11.     password: "",
  12.     database: "melonpw",
  13.  
  14.     spamReset: 1000 * 30,
  15.     maxMsgLength: 60,
  16.     maxMsgs: 10,
  17.     rainTime: 1000 * 180,
  18.     rainAmount: 1
  19. };
  20.  
  21. var auth = {};
  22.  
  23. var con;
  24.  
  25. function log(text, color) {
  26.     var d = new Date();
  27.     var h = d.getHours();
  28.     var m = d.getMinutes();
  29.     var ap = "AM";
  30.     if (h > 12) {
  31.         h -= 12;
  32.         var ap = "PM";
  33.     }
  34.     if (m < 10) {
  35.         m = "0" + m;
  36.     }
  37.     time = h + ":" + m + " " + ap;
  38.  
  39.     if (typeof(color) == "undefined") {
  40.         display = colors.grey(time) + ": " + text;
  41.         console.log(display);
  42.     } else {
  43.         console.log(colors.grey(time) + ": " + colors[color](text));
  44.     }
  45. }
  46.  
  47. function handleConnection() {
  48.     con = mysql.createConnection(config);
  49.  
  50.     con.connect(function(err) {
  51.         if (err) {
  52.             log("An error has occurred while connection: " + err, "red");
  53.             setTimeout(handleConnection, 2000);
  54.         } else {
  55.             log("Connection successful.", "green");
  56.         }
  57.     });
  58.  
  59.     con.on("error", function(err) {
  60.         console.log("Error: " + err);
  61.         if (err.code === "PROTOCOL_CONNECTION_LOST") {
  62.             handleConnection();
  63.         } else {
  64.             throw err;
  65.         }
  66.     });
  67. }
  68.  
  69. function getCurrentTime() {
  70.     var date = new Date();
  71.     var hours = date.getHours();
  72.     var minutes = date.getMinutes();
  73.     var period = "AM";
  74.  
  75.     if (minutes < 10) {
  76.         minutes = "0" + minutes;
  77.     }
  78.  
  79.     if (hours > 12) {
  80.         hours -= 12;
  81.         period = "PM";
  82.     }
  83.  
  84.     return hours + ":" + minutes + " " + period;
  85. }
  86.  
  87. function genID(length) {
  88.     var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVYXYZ-_';
  89.     var result = '';
  90.     for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
  91.     return result;
  92. }
  93.  
  94. handleConnection();
  95.  
  96. //* Resets all users online when the server is restarted. *//
  97. con.query('UPDATE users SET online = 0 WHERE id >= 0',
  98. function(err, res) {
  99.     if (err) log(err, "red");
  100. });
  101.  
  102. // --- Earning Currency --- //
  103.  
  104. //* Starts a timer that regularly pings all clients to get their usernames. *//
  105. setInterval(function() {
  106.     client.emit('rain-ping');
  107.     log("Rain has started.", "magenta");
  108. }, config.rainTime);
  109.  
  110. // --- End of Earning Currency --- //
  111.  
  112. var online = [];
  113.  
  114. //* Active when the client is connected. *//
  115. client.on("connection", function(socket) {
  116.     client.emit('online-check');
  117.  
  118.     socket.on('online-check', function(data) {
  119.         con.query('SELECT * FROM users WHERE username = ?', data.username,
  120.         function(err, res) {
  121.             if (err) log(err, "red");
  122.             if (res.length == 1 && res[0].online == 0) {
  123.                 socket.emit('force-logout');
  124.                 online.pop(data.username);
  125.             } else {
  126.                 if (!online.includes(data.username)) online.push(data.username);
  127.             }
  128.  
  129.             socket.join(data.username);
  130.             update(data.username);
  131.         });
  132.     });
  133.  
  134.     // --- Updating --- //
  135.  
  136.     //* Sends the most recent stats of the user. *//
  137.     function update(username) {
  138.         con.query('SELECT * FROM users WHERE username = ?', username,
  139.         function(err, res) {
  140.             client.to(username).emit('update', {mln: res[0].mln});
  141.         });
  142.     }
  143.  
  144.     //* Active when the user requests an update. *//
  145.     socket.on("update", function(data) {
  146.         update(data.username);
  147.     });
  148.  
  149.     // --- End of Updating --- //
  150.  
  151.     // --- Earning Currency (continued) --- //
  152.  
  153.     //* Gives the user currency for being on the site. *//
  154.     socket.on('rain-pong', function(data) {
  155.         addMLN(data.username, config.rainAmount);
  156.     });
  157.  
  158.     //* Gives the user money and sends them an updated set of variables. *//
  159.     function addMLN(username, amount) {
  160.         con.query('UPDATE users SET mln = mln + ? WHERE username = ?', [amount, username],
  161.         function(err, res) {
  162.             if (err) log(err, "red");
  163.             update(username);
  164.         });
  165.     }
  166.  
  167.     // --- End of Earning Currency --- //
  168.  
  169.     // --- Chat --- //
  170.  
  171.     //* Active when the user requests all current messages. *//
  172.     socket.on('get-chat', function(data) {
  173.         returnChat("none.ogg");
  174.     });
  175.  
  176.     //* Active when the user sends a message to the server. *//
  177.     socket.on('send-chat', function(data) {
  178.         sendMessage(data);
  179.     });
  180.  
  181.     //* Returns the rank of the username provided. *//
  182.     function getRank(username, callback) {
  183.         con.query('SELECT * FROM users WHERE username = ?', [username],
  184.         function(err, res) {
  185.             if (err) log(err, "red");
  186.             if (res.length == 1) callback(res[0].rank);
  187.         });
  188.     }
  189.  
  190.     //* Inserts a message into the 'messages' table. *//
  191.     function sendMessage(data) {
  192.         // Check if the message is less than the specified length. //
  193.         if (data.message.length <= config.maxMsgLength) {
  194.             // Check if the message isn't whitespace. //
  195.             if (data.message.trim().length > 0) {
  196.                 getRank(message.username, function(rank) {
  197.                     let message = {
  198.                         username: data.username,
  199.                         message: data.message,
  200.                         rank: 0,
  201.                         time: data.time
  202.                     };
  203.                    
  204.                     message.rank = rank;
  205.                     commandCheck(message);
  206.                 });
  207.             } else {
  208.                 error("You cannot send blank space as a message.");
  209.             }
  210.         } else {
  211.             error("You cannot send messages longer than " + config.maxMsgLength + " characters.");
  212.         }
  213.     }
  214.  
  215.     //* Checks the message for possible commands and executes them. *//
  216.     function commandCheck(message) {
  217.         log("!");
  218.         switch (message.message.trim().toLowerCase().split(" ")[0]) {
  219.  
  220.             //* Clears the current chat. *//
  221.             case "/clear":
  222.                 if (message.rank > 0) {
  223.                     con.query('TRUNCATE TABLE messages',
  224.                     function(err, res) {
  225.                         if (err) log(err, "red");
  226.  
  227.                         log("Chat has been cleared.", "yellow");
  228.                         insertMessage({ username: "Bot",
  229.                             message: "Chat has been cleared by " + message.username + "." });
  230.                     });
  231.                 } else {
  232.                     error("You are not a high enough rank to use this command.");
  233.                 }
  234.             break;
  235.  
  236.             case "/give":
  237.             let splitMessage = message.message.trim().split(" ");
  238.                 if (splitMessage.length == 4) {
  239.                     let user = splitMessage[1];
  240.                     let amount = splitMessage[2];
  241.                     let type = splitMessage[3];
  242.  
  243.                     if (message.rank > 0) {
  244.                         if (type == "mln") addMLN(user, amount);
  245.                         if (type == "mln") insertMessage({ username: "Bot", message: message.username
  246.                          + " has gave " + user + " " + amount + " " + type.toUpperCase() + "." });
  247.                     } else {
  248.                         error("You are not a high enough rank to use this command.");
  249.                     }
  250.                 } else {
  251.                     error("Invalid command syntax: /give username amount type.");
  252.                 }
  253.             break;
  254.  
  255.             case "/online":
  256.                 let message = "Online users: ";
  257.                 for (let i = 0; i < online.length; i++) {
  258.                     if (i == online.length - 1) message += online[i] + ".";
  259.                     if (i < online.length - 1) message += online[i] + ", ";
  260.                 }
  261.                 info(message);
  262.             break;
  263.  
  264.             //* Add message to the database if there is no command found. *//
  265.             default:
  266.                 insertMessage(message);
  267.             break;
  268.         }
  269.     }
  270.  
  271.     //* Returns the message count of the selected user. *//
  272.     function checkMsgCount(username, callback) {
  273.         con.query('SELECT * FROM users WHERE username = ?', username,
  274.         function(err, res) {
  275.             if (err) log(err, "red");
  276.             if (res.length == 1) callback(res[0].msgCount);
  277.         });
  278.     }
  279.  
  280.     //* Inserts the message into the 'messages' table. *//
  281.     function insertMessage(message) {
  282.         con.query('UPDATE users SET msgCount = msgCount + 1 WHERE username = ?', message.username,
  283.         function(err, res) {
  284.             if (err) log(err, "red");
  285.             checkMsgCount(message.username, function(msgCount) {
  286.                 if (msgCount < config.maxMsgs) {
  287.                     con.query('INSERT INTO messages SET ?', message,
  288.                     function(err, res) {
  289.                         if (err) log(err, "red");
  290.                         returnChat("tick.ogg");
  291.                     });
  292.                 } else {
  293.                     error("You have been timed out, please try again later.");
  294.                 }
  295.             });
  296.         });
  297.  
  298.         // log("Attempted to insert message to database.", "yellow");
  299.     }
  300.  
  301.     //* Returns all messages in the 'messages' table to client(s). *//
  302.     function returnChat(sound) {
  303.         con.query('SELECT * FROM messages',
  304.         function(err, res) {
  305.             if (err) log(err, "red");
  306.  
  307.             // log("Attempted to return messages to clients.", "yellow");
  308.             client.emit('return-chat', { chat: res, sound: sound });
  309.         });
  310.     }
  311.  
  312.     //* Sends an error message to the socket it originated. *//
  313.     function error(message) {
  314.         socket.emit('error-message', { message: message });
  315.     }
  316.  
  317.     function info(message) {
  318.         socket.emit('info-message', { message: message });
  319.     }
  320.  
  321.     //* Resets the spam prevention variable every set amount of seconds. *//
  322.     setInterval(function() {
  323.         con.query('UPDATE users SET msgCount = 0 WHERE rank >= 0',
  324.         function(err, res) {
  325.             if (err) log(err, "red");
  326.  
  327.             // log("Spam prevention variable has been reset.", "yellow");
  328.         });
  329.     }, config.spamReset);
  330.  
  331.     // --- End of Chat --- //
  332.  
  333.     socket.on("logout", function(data) {
  334.         con.query('UPDATE users SET online = 0 WHERE username = ?', data.username,
  335.         function(err, res) {
  336.             if (err) log(err, "red");
  337.         });
  338.     });
  339.  
  340.     socket.on("attempt-login", function(data) {
  341.         var cleanedUsername = sanitizer.sanitize(data.username);
  342.         var secret = 'a42r7jf2849qjr89n2cm9';
  343.         var hashedPassword = crypto.createHmac('sha256', secret).update(data.password).digest('hex');
  344.         var post = {username: cleanedUsername, password: hashedPassword};
  345.  
  346.         var check = con.query('SELECT * FROM users WHERE username LIKE ?', cleanedUsername,
  347.             function(err, res) {
  348.                 if (res.length == 1) {
  349.                     if (hashedPassword == res[0].password && res[0].online == 0) {
  350.                         var code = genID(24);
  351.                         auth[cleanedUsername] = {
  352.                             code: code
  353.                         };
  354.  
  355.                         con.query('UPDATE users SET online = 1 WHERE username = ?', cleanedUsername,
  356.                         function(err, res) {
  357.                             if (err) log(err, "red");
  358.                         });
  359.  
  360.                         var data = {info: "success", username: cleanedUsername, code: code, rank: res[0].rank};
  361.                         socket.emit('login-result', data);
  362.                        
  363.                     } else if (res[0].online == 1) {
  364.                         var data = {info: "logged"};
  365.                         socket.emit('login-result', data);
  366.                     } else {
  367.                         var data = {info: "password"};
  368.                         socket.emit('login-result', data);
  369.                     }
  370.                    
  371.                 } else {
  372.                     var data = {info: "error"};
  373.                     socket.emit('login-result', data);
  374.                 }
  375.             });
  376.  
  377.         con.escape();
  378.     });
  379.  
  380.     socket.on("attempt-register", function(data) {
  381.         var cleanedUsername = sanitizer.sanitize(data.username);
  382.         var secret = 'a42r7jf2849qjr89n2cm9';
  383.         var hashedPassword = crypto.createHmac('sha256', secret).update(data.password).digest('hex');
  384.         var post = {username: cleanedUsername, password: hashedPassword};
  385.  
  386.         var check = con.query('SELECT * FROM users WHERE username LIKE ?', cleanedUsername,
  387.             function(err, res) {
  388.                 if (res.length == 0) {
  389.                     var query = con.query('INSERT INTO users SET ?', post,
  390.                         function(err, res) {
  391.                             var data = {info: "success"};
  392.                             socket.emit('register-result', data);
  393.                             log("New user has registered.", "green");
  394.                         });
  395.                 } else {
  396.                     var data = {info: "username"};
  397.                     socket.emit('register-result', data);
  398.                 }
  399.             });
  400.     });
  401.  
  402.     socket.on('authenticate', function(data) {
  403.         if (auth[data.username] != undefined) {
  404.             if (auth[data.username].code == data.code) {
  405.                 data = {info: "success"};
  406.                 socket.emit('authentication-result', data);
  407.  
  408.             } else {
  409.                 log("Authentication failed: auth code does not match.");
  410.             }
  411.         } else {
  412.             data = {info: "failure"};
  413.             socket.emit('authentication-result', data);
  414.         }
  415.     });
  416. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement