hardlounge/client/js/socket-events/auth.js

91 lines
1.9 KiB
JavaScript
Raw Normal View History

2017-05-18 20:08:54 +00:00
"use strict";
const $ = require("jquery");
const socket = require("../socket");
const storage = require("../localStorage");
const utils = require("../utils");
2017-11-04 17:16:30 +00:00
const templates = require("../../views");
2017-05-18 20:08:54 +00:00
socket.on("auth", function(data) {
2017-08-28 20:06:28 +00:00
// If we reconnected and serverHash differs, that means the server restarted
// And we will reload the page to grab the latest version
if (utils.serverHash > -1 && data.serverHash > -1 && data.serverHash !== utils.serverHash) {
socket.disconnect();
2017-08-28 15:03:27 +00:00
$("#connection-error").text("Server restarted, reloading…");
location.reload(true);
return;
}
const login = $("#sign-in");
if (data.serverHash > -1) {
utils.serverHash = data.serverHash;
2017-05-18 20:08:54 +00:00
login.html(templates.windows.sign_in());
2017-11-11 18:33:21 +00:00
login.find("form").on("submit", function() {
const form = $(this);
2017-11-11 18:33:21 +00:00
form.find(".btn").prop("disabled", true);
2017-11-11 18:33:21 +00:00
const values = {};
$.each(form.serializeArray(), function(i, obj) {
values[obj.name] = obj.value;
});
2017-11-11 18:33:21 +00:00
storage.set("user", values.user);
2017-11-11 18:33:21 +00:00
socket.emit("auth", values);
2017-11-11 18:33:21 +00:00
return false;
});
} else {
login.find(".btn").prop("disabled", false);
}
let token;
const user = storage.get("user");
2017-05-18 20:08:54 +00:00
if (!data.success) {
if (login.length === 0) {
socket.disconnect();
$("#connection-error").text("Authentication failed, reloading…");
location.reload();
return;
}
2017-05-18 20:08:54 +00:00
storage.remove("token");
const error = login.find(".error");
error.show().closest("form").one("submit", function() {
error.hide();
});
} else if (user) {
2017-05-18 20:08:54 +00:00
token = storage.get("token");
2017-05-18 20:08:54 +00:00
if (token) {
2017-08-28 15:03:27 +00:00
$("#loading-page-message, #connection-error").text("Authorizing…");
socket.emit("auth", {
user: user,
token: token,
lastMessage: utils.lastMessageId,
});
2017-05-18 20:08:54 +00:00
}
}
if (user) {
login.find("input[name='user']").val(user);
2017-05-18 20:08:54 +00:00
}
2017-05-18 20:08:54 +00:00
if (token) {
return;
}
2017-09-12 12:52:16 +00:00
$("#footer")
.find(".sign-in")
2017-05-18 20:08:54 +00:00
.trigger("click", {
pushState: false,
2017-09-12 12:52:16 +00:00
});
2017-05-18 20:08:54 +00:00
});