Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Establishes all requirements for the server. */
- 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");
- /* Declares all variables for the server config "file". */
- var config = {
- host: "localhost",
- user: "root",
- password: "",
- database: "login"
- };
- /* Contains all users within the database. */
- var users = {};
- var awaitingReset = {};
- /* The connection variable for the SQL database. */
- var con;
- /* Used to log any information with the current time and coloring. */
- function log(text, color) {
- let d = new Date(),
- h = d.getHours(),
- m = d.getMinutes(),
- ap = "AM";
- if (h > 12) { h -= 12; ap = "PM"; }
- if (h === 12) { ap = "PM"; }
- if (m < 10) { m = "0" + m; }
- time = h + ":" + m + " " + ap;
- if (typeof(color) == "undefined") console.log(colors.grey(time) + ": " + text);
- console.log(colors.grey(time) + ": " + colors[color](text));
- }
- /* Attempts to establish a connection to the SQL database. */
- 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();
- }
- throw err;
- });
- }
- /* Updates the SQL database when called. */
- function updateSQLDatabase() {
- let set = [];
- for (let user in users) {
- set.push({username: user, password: users[user].password,
- question: users[user].question, answer: users[user].answer});
- }
- con.query("TRUNCATE TABLE user", function(err, res) {
- if (err) log(err, "red");
- });
- for (let i = 0; i < set.length; i++) {
- con.query("INSERT INTO user SET ?", set[i], function(err, res) {
- if (err) log(err, "red");
- });
- }
- }
- function login(socket, data) {
- let cleanedUsername = sanitizer.sanitize(data["username"]),
- secret = 'tcL7YThah4PzdjTDSfJT',
- salt = '1DNmIP5Y51xu5E9hggHU',
- hashedPassword = crypto.createHmac('sha256', salt + data.password).update(secret).digest('hex');
- if (users[cleanedUsername] !== undefined) {
- if (users[cleanedUsername].password === hashedPassword) {
- socket.emit("login", {result: 0, info: "Successfully logged in.", username: cleanedUsername, code: genID(20)});
- log("> LOGIN: " + cleanedUsername, "cyan");
- } else {
- socket.emit("login", {result: 1, info: "Username or password is incorrect."});
- }
- } else {
- socket.emit("login", {result: 1, info: "Username or password is incorrect."});
- }
- }
- function register(socket, data) {
- let cleanedUsername = sanitizer.sanitize(data["username"]),
- secret = 'tcL7YThah4PzdjTDSfJT',
- salt = '1DNmIP5Y51xu5E9hggHU',
- hashedConfirmation = crypto.createHmac('sha256', salt + data.confirm).update(secret).digest('hex');
- hashedPassword = crypto.createHmac('sha256', salt + data.password).update(secret).digest('hex');
- if (users[cleanedUsername] === undefined) {
- if (hashedConfirmation === hashedPassword) {
- users[cleanedUsername] = {
- password: hashedPassword,
- question: data.question,
- answer: data.answer
- };
- socket.emit("register", {result: 0, info: "Successfully registered."});
- log("> REGISTER: " + cleanedUsername, "cyan");
- login(socket, data);
- updateSQLDatabase();
- } else {
- socket.emit("register", {result: 1, info: "Passwords do not match."});
- }
- } else {
- socket.emit("register", {result: 1, info: "Username already exists."});
- }
- }
- /* Adds all users from the SQL database to the users variable. */
- function getUserList() {
- if (con) {
- con.query("SELECT * FROM user", function(err, res) {
- if (err) log(err, "red");
- for (let result in res) {
- users[res[result].username] = {
- password: res[result].password,
- question: res[result].question,
- answer: res[result].answer
- };
- }
- log("All current users have been loaded.", "green");
- });
- } else {
- log("Cannot load users as connection has not been established.", "red");
- }
- }
- /* Generates an alphanumeric string (also includes - and _) of desired length. */
- function genID(length) {
- let chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVYXYZ-_',
- result = '';
- for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
- return result;
- }
- /* Methods/functions called upon server start up. */
- handleConnection();
- getUserList();
- /* Declares all socket "on" and "emit" upon client connection. */
- client.on("connection", function(socket) {
- connectedClients.push(socket);
- socket.on("disconnect", function(data) {
- if (connectedClients.indexOf(socket) > -1) connectedClients.splice(socket, 1);
- });
- socket.on("login", function(data) {
- login(socket, data);
- });
- socket.on("register", function(data) {
- register(socket, data);
- });
- socket.on("recovery", function(data) {
- switch (data.type) {
- case 0:
- if (users[data.username] !== undefined) {
- socket.emit("recovery", {type: 0, question: users[data.username].question});
- }
- break;
- case 1:
- if (users[data.username] !== undefined) {
- if (users[data.username].answer === data.answer) {
- awaitingReset[data.username] = {code: genID(20)};
- socket.emit("recovery", {type: 2, resetCode: awaitingReset[data.username].code})
- } else {
- socket.emit("recovery", {type: 3, info: "You answered the security question incorrectly."});
- }
- }
- break;
- case 4:
- let secret = 'tcL7YThah4PzdjTDSfJT',
- salt = '1DNmIP5Y51xu5E9hggHU';
- if (awaitingReset[data.username] !== undefined) {
- if (data.resetCode === awaitingReset[data.username].code) {
- users[data.username].password = crypto.createHmac('sha256', salt + data.password).update(secret).digest('hex');
- updateSQLDatabase();
- socket.emit("recovery", {type: 5});
- awaitingReset[data.username] = null;
- log(data.username + " has recovered their password.", "cyan");
- } else {
- log("Reset code incorrect for " + data.username + " - potential hack attempt.", "yellow");
- }
- }
- break;
- }
- });
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement