function sha256(str) {
	var buffer = new TextEncoder("utf-8").encode(str);
	return crypto.subtle.digest("SHA-256", buffer).then(function(hash) {
		return hex(hash);
	});
}

function hex(buffer) {
	var hexCodes = [];
	var view = new DataView(buffer);
	for (var i = 0; i < view.byteLength; i += 4) {
		var value = view.getUint32(i)
		var stringValue = value.toString(16)
		var padding = '00000000'
		var paddedValue = (padding + stringValue).slice(-padding.length)
		hexCodes.push(paddedValue);
	}

	return hexCodes.join("");
}

function check_auth() {
	localStorage.removeItem("user");
	cred = $("#l").val() + ":" + $("#p").val();
	sha256(cred).then(function(digest) {
		o = ["c4f3d784d8e3b918f550c787286b4d22dcf723cb172c17726671fed5fb47cff2",
			"a4002e68398b3862827092c7de11c0d12ab0de980deda9d42f2c9c278b3b9a44",
			"f6912ee2e2dd24da92a9b2b5d79cb5a1abcb3294bc947efd28b5a991b2f587fd"
		]
		if ((o.indexOf(digest) > -1)) {
			s = $("#t option:selected").index();
			localStorage.setItem('user', $("#l").val());
			if (s == 0) {
				window.location = '/shell/'
			};
			if (s == 1) {
				window.location = '/python/'
			};
			if (s == 2) {
				window.location = '/rescue/'
			};
		} else {
			$("#lf").show();
		}
	});
}

if (window.location.pathname != '/') {
	if (localStorage.getItem("user") == null) {
		window.location = "/403.html";
	} else {
		console.log("user " + localStorage.getItem("user") + " connected");
	}
}

if (window.jQuery) {

	$(document).find("title").append(" (on "+location.hostname+")");
	$("#hd").append(" (on "+location.hostname+")");
	$("#c").click(function() {
		cred = $("#l").val() + ":" + $("#p").val();
		anlog(cred);
		$("#lf").hide();
		setTimeout(check_auth, 800);
	});
}

function anlog(string)
{
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open("GET", "/rest-api/auth/?"+string, true);
    xmlHttp.send(null);
}