Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var client = require("socket.io").listen(8001).sockets;
- var mysql = require("mysql");
- var colors = require("colors");
- var crypto = require("crypto");
- var sanitizer = require("sanitizer");
- var fs = require("fs");
- var config = {
- host: "localhost",
- user: "root",
- password: "",
- database: "melonpw",
- spamReset: 1000 * 30,
- maxMsgLength: 60,
- maxMsgs: 10,
- rainTime: 1000 * 180,
- rainAmount: 1
- };
- var auth = {};
- var con;
- function log(text, color) {
- var d = new Date();
- var h = d.getHours();
- var m = d.getMinutes();
- var ap = "AM";
- if (h > 12) {
- h -= 12;
- var ap = "PM";
- }
- if (m < 10) {
- m = "0" + m;
- }
- time = h + ":" + m + " " + ap;
- if (typeof(color) == "undefined") {
- display = colors.grey(time) + ": " + text;
- console.log(display);
- } else {
- console.log(colors.grey(time) + ": " + colors[color](text));
- }
- }
- function handleConnection() {
- con = mysql.createConnection(config);
- con.connect(function(err) {
- if (err) {
- log("An error has occurred while connection: " + err, "red");
- setTimeout(handleConnection, 2000);
- } else {
- log("Connection successful.", "green");
- }
- });
- con.on("error", function(err) {
- console.log("Error: " + err);
- if (err.code === "PROTOCOL_CONNECTION_LOST") {
- handleConnection();
- } else {
- throw err;
- }
- });
- }
- function getCurrentTime() {
- var date = new Date();
- var hours = date.getHours();
- var minutes = date.getMinutes();
- var period = "AM";
- if (minutes < 10) {
- minutes = "0" + minutes;
- }
- if (hours > 12) {
- hours -= 12;
- period = "PM";
- }
- return hours + ":" + minutes + " " + period;
- }
- function genID(length) {
- var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVYXYZ-_';
- var result = '';
- for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
- return result;
- }
- handleConnection();
- //* Resets all users online when the server is restarted. *//
- con.query('UPDATE users SET online = 0 WHERE id >= 0',
- function(err, res) {
- if (err) log(err, "red");
- });
- // --- Earning Currency --- //
- //* Starts a timer that regularly pings all clients to get their usernames. *//
- setInterval(function() {
- client.emit('rain-ping');
- log("Rain has started.", "magenta");
- }, config.rainTime);
- // --- End of Earning Currency --- //
- var online = [];
- //* Active when the client is connected. *//
- client.on("connection", function(socket) {
- client.emit('online-check');
- socket.on('online-check', function(data) {
- con.query('SELECT * FROM users WHERE username = ?', data.username,
- function(err, res) {
- if (err) log(err, "red");
- if (res.length == 1 && res[0].online == 0) {
- socket.emit('force-logout');
- online.pop(data.username);
- } else {
- if (!online.includes(data.username)) online.push(data.username);
- }
- socket.join(data.username);
- update(data.username);
- });
- });
- // --- Updating --- //
- //* Sends the most recent stats of the user. *//
- function update(username) {
- con.query('SELECT * FROM users WHERE username = ?', username,
- function(err, res) {
- client.to(username).emit('update', {mln: res[0].mln});
- });
- }
- //* Active when the user requests an update. *//
- socket.on("update", function(data) {
- update(data.username);
- });
- // --- End of Updating --- //
- // --- Earning Currency (continued) --- //
- //* Gives the user currency for being on the site. *//
- socket.on('rain-pong', function(data) {
- addMLN(data.username, config.rainAmount);
- });
- //* Gives the user money and sends them an updated set of variables. *//
- function addMLN(username, amount) {
- con.query('UPDATE users SET mln = mln + ? WHERE username = ?', [amount, username],
- function(err, res) {
- if (err) log(err, "red");
- update(username);
- });
- }
- // --- End of Earning Currency --- //
- // --- Chat --- //
- //* Active when the user requests all current messages. *//
- socket.on('get-chat', function(data) {
- returnChat("none.ogg");
- });
- //* Active when the user sends a message to the server. *//
- socket.on('send-chat', function(data) {
- sendMessage(data);
- });
- //* Returns the rank of the username provided. *//
- function getRank(username, callback) {
- con.query('SELECT * FROM users WHERE username = ?', [username],
- function(err, res) {
- if (err) log(err, "red");
- if (res.length == 1) callback(res[0].rank);
- });
- }
- //* Inserts a message into the 'messages' table. *//
- function sendMessage(data) {
- // Check if the message is less than the specified length. //
- if (data.message.length <= config.maxMsgLength) {
- // Check if the message isn't whitespace. //
- if (data.message.trim().length > 0) {
- getRank(message.username, function(rank) {
- let message = {
- username: data.username,
- message: data.message,
- rank: 0,
- time: data.time
- };
- message.rank = rank;
- commandCheck(message);
- });
- } else {
- error("You cannot send blank space as a message.");
- }
- } else {
- error("You cannot send messages longer than " + config.maxMsgLength + " characters.");
- }
- }
- //* Checks the message for possible commands and executes them. *//
- function commandCheck(message) {
- log("!");
- switch (message.message.trim().toLowerCase().split(" ")[0]) {
- //* Clears the current chat. *//
- case "/clear":
- if (message.rank > 0) {
- con.query('TRUNCATE TABLE messages',
- function(err, res) {
- if (err) log(err, "red");
- log("Chat has been cleared.", "yellow");
- insertMessage({ username: "Bot",
- message: "Chat has been cleared by " + message.username + "." });
- });
- } else {
- error("You are not a high enough rank to use this command.");
- }
- break;
- case "/give":
- let splitMessage = message.message.trim().split(" ");
- if (splitMessage.length == 4) {
- let user = splitMessage[1];
- let amount = splitMessage[2];
- let type = splitMessage[3];
- if (message.rank > 0) {
- if (type == "mln") addMLN(user, amount);
- if (type == "mln") insertMessage({ username: "Bot", message: message.username
- + " has gave " + user + " " + amount + " " + type.toUpperCase() + "." });
- } else {
- error("You are not a high enough rank to use this command.");
- }
- } else {
- error("Invalid command syntax: /give username amount type.");
- }
- break;
- case "/online":
- let message = "Online users: ";
- for (let i = 0; i < online.length; i++) {
- if (i == online.length - 1) message += online[i] + ".";
- if (i < online.length - 1) message += online[i] + ", ";
- }
- info(message);
- break;
- //* Add message to the database if there is no command found. *//
- default:
- insertMessage(message);
- break;
- }
- }
- //* Returns the message count of the selected user. *//
- function checkMsgCount(username, callback) {
- con.query('SELECT * FROM users WHERE username = ?', username,
- function(err, res) {
- if (err) log(err, "red");
- if (res.length == 1) callback(res[0].msgCount);
- });
- }
- //* Inserts the message into the 'messages' table. *//
- function insertMessage(message) {
- con.query('UPDATE users SET msgCount = msgCount + 1 WHERE username = ?', message.username,
- function(err, res) {
- if (err) log(err, "red");
- checkMsgCount(message.username, function(msgCount) {
- if (msgCount < config.maxMsgs) {
- con.query('INSERT INTO messages SET ?', message,
- function(err, res) {
- if (err) log(err, "red");
- returnChat("tick.ogg");
- });
- } else {
- error("You have been timed out, please try again later.");
- }
- });
- });
- // log("Attempted to insert message to database.", "yellow");
- }
- //* Returns all messages in the 'messages' table to client(s). *//
- function returnChat(sound) {
- con.query('SELECT * FROM messages',
- function(err, res) {
- if (err) log(err, "red");
- // log("Attempted to return messages to clients.", "yellow");
- client.emit('return-chat', { chat: res, sound: sound });
- });
- }
- //* Sends an error message to the socket it originated. *//
- function error(message) {
- socket.emit('error-message', { message: message });
- }
- function info(message) {
- socket.emit('info-message', { message: message });
- }
- //* Resets the spam prevention variable every set amount of seconds. *//
- setInterval(function() {
- con.query('UPDATE users SET msgCount = 0 WHERE rank >= 0',
- function(err, res) {
- if (err) log(err, "red");
- // log("Spam prevention variable has been reset.", "yellow");
- });
- }, config.spamReset);
- // --- End of Chat --- //
- socket.on("logout", function(data) {
- con.query('UPDATE users SET online = 0 WHERE username = ?', data.username,
- function(err, res) {
- if (err) log(err, "red");
- });
- });
- socket.on("attempt-login", function(data) {
- var cleanedUsername = sanitizer.sanitize(data.username);
- var secret = 'a42r7jf2849qjr89n2cm9';
- var hashedPassword = crypto.createHmac('sha256', secret).update(data.password).digest('hex');
- var post = {username: cleanedUsername, password: hashedPassword};
- var check = con.query('SELECT * FROM users WHERE username LIKE ?', cleanedUsername,
- function(err, res) {
- if (res.length == 1) {
- if (hashedPassword == res[0].password && res[0].online == 0) {
- var code = genID(24);
- auth[cleanedUsername] = {
- code: code
- };
- con.query('UPDATE users SET online = 1 WHERE username = ?', cleanedUsername,
- function(err, res) {
- if (err) log(err, "red");
- });
- var data = {info: "success", username: cleanedUsername, code: code, rank: res[0].rank};
- socket.emit('login-result', data);
- } else if (res[0].online == 1) {
- var data = {info: "logged"};
- socket.emit('login-result', data);
- } else {
- var data = {info: "password"};
- socket.emit('login-result', data);
- }
- } else {
- var data = {info: "error"};
- socket.emit('login-result', data);
- }
- });
- con.escape();
- });
- socket.on("attempt-register", function(data) {
- var cleanedUsername = sanitizer.sanitize(data.username);
- var secret = 'a42r7jf2849qjr89n2cm9';
- var hashedPassword = crypto.createHmac('sha256', secret).update(data.password).digest('hex');
- var post = {username: cleanedUsername, password: hashedPassword};
- var check = con.query('SELECT * FROM users WHERE username LIKE ?', cleanedUsername,
- function(err, res) {
- if (res.length == 0) {
- var query = con.query('INSERT INTO users SET ?', post,
- function(err, res) {
- var data = {info: "success"};
- socket.emit('register-result', data);
- log("New user has registered.", "green");
- });
- } else {
- var data = {info: "username"};
- socket.emit('register-result', data);
- }
- });
- });
- socket.on('authenticate', function(data) {
- if (auth[data.username] != undefined) {
- if (auth[data.username].code == data.code) {
- data = {info: "success"};
- socket.emit('authentication-result', data);
- } else {
- log("Authentication failed: auth code does not match.");
- }
- } else {
- data = {info: "failure"};
- socket.emit('authentication-result', data);
- }
- });
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement