From 15815acf0fd627a3246f574a6526af9733984e1e Mon Sep 17 00:00:00 2001 From: Midgard Date: Tue, 24 Mar 2020 22:47:39 +0100 Subject: [PATCH] Initial commit --- index.html | 11 +++++++ main.js | 84 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 95 insertions(+) create mode 100644 index.html create mode 100644 main.js diff --git a/index.html b/index.html new file mode 100644 index 0000000..e83b1f0 --- /dev/null +++ b/index.html @@ -0,0 +1,11 @@ + + + + + + Battermost + + + + + diff --git a/main.js b/main.js new file mode 100644 index 0000000..981fb1f --- /dev/null +++ b/main.js @@ -0,0 +1,84 @@ +//async function postJson(url, data = {}, options = {}) { + //const response = await fetch(url, { + //method: "POST", + //mode: "no-cors", + //credentials: "include", + //headers: { "Content-Type": "application/json" }, + //redirect: "follow", + //referrerPolicy: "no-referrer", + //body: JSON.stringify(data), + //...options + //}); + ////return await response.json(); + //return response; +//} + +//var endpoint = "https://mattermost.zeus.gent/api/v4"; // Must not end with slash +var endpoint = "http://localhost:8080"; // Must not end with slash +var username = "fill me in"; +var password = "fill me in"; + + +function scopeToArg(f) { + return function(...rest) { + return f(this, ...rest); + } +} + +function postJson(url, data={}, options={}) { + const prom = new Promise((resolve, reject) => { + let oReq = new XMLHttpRequest(); + oReq.addEventListener("load", scopeToArg(resolve)); + oReq.addEventListener("abort", scopeToArg(reject)); + oReq.addEventListener("error", scopeToArg(reject)); + oReq.addEventListener("timeout", scopeToArg(reject)); + oReq.open("POST", url); + oReq.send(JSON.stringify(data)); + + }); + return prom; +} + +var token = null; + +function printIt(response) { + console.log(response); + if (response.status == 0) { + document.body.innerText = "Network error"; + return; + } + + if (200 <= response.status && response.status < 300) { + try { + const json = JSON.parse(response.response); + document.body.innerHTML = ""; + const pre = document.createElement("pre"); + pre.innerText = "Received " + JSON.stringify(json, null, 2); + document.body.appendChild(pre); + + token = response.getResponseHeader("token"); + window.localStorage.setItem("token", token); + + return token; + } catch(e) { + document.body.innerText = "The server did not reply with a valid JSON object. Make sure the server URL points to a Mattermost instance that is working correctly."; + } + + } else { + console.log(response.getAllResponseHeaders()); + try { + const json = JSON.parse(response.response); + document.body.innerText = "Failed to log in: " + json.message; + } catch(e) { + document.body.innerText = "Error: " + response.statusText; + } + } +} + + +postJson(`${endpoint}/api/v4/users/login`, { + "login_id": username, + "password": password +}) + .then(printIt, printIt) + .then(token => console.log(token));