feathermost/main.js

105 lines
2.7 KiB
JavaScript

"use strict";
const LOCALSTORAGE_KEY_SERVERS = "mattermostServers";
function byId(id, nullOk=false) {
const el = document.getElementById(id);
if (!el && !nullOk) {
console.error(`No element #${id}`);
}
return el;
}
function storeCredentials(endpoint, login_id, token) {
let storedServers = JSON.parse(window.localStorage.getItem(LOCALSTORAGE_KEY_SERVERS) || "[]");
if (!(endpoint in storedServers)) storedServers.push(endpoint);
window.localStorage.setItem(LOCALSTORAGE_KEY_SERVERS, JSON.stringify(storedServers));
window.localStorage.setItem(`${LOCALSTORAGE_KEY_SERVERS}_${endpoint}`, JSON.stringify({login_id, token}));
}
function getCredentials(endpoint) {
return JSON.parse(window.localStorage.getItem(`${LOCALSTORAGE_KEY_SERVERS}_${endpoint}`) || "null");
}
class MattermostApi {
constructor(endpoint) {
this.endpoint = endpoint;
}
async validateToken(token) {
const response = await ajax.getJson(`${this.endpoint}/users/me`, {
headers: {
"Authorization": `Bearer ${token}`
}
});
if (!response.ok) {
throw response;
}
return response;
}
logIn(login_id, password) {
return ajax.postJson(`${this.endpoint}/users/login`, {login_id, password})
.then(response => {
let token = response.getHeader("Token");
storeCredentials(this.endpoint, login_id, token);
return response;
})
.then(response => {
document.body.innerHTML = "";
const pre = document.createElement("pre");
pre.innerText = JSON.stringify(response.json, null, 2);
document.body.appendChild(pre);
return response;
})
.catch(error => {
console.error(error);
document.body.innerText = `An error occurred: ${error}`;
});
}
}
/**
* Return an endpoint URL that has a protocol, domain and path
*/
function normalizedEndpoint(endpoint) {
let matches = endpoint.match(/^(https?:\/\/)?([^\/]+)(\/.*)?$/i);
if (!matches) throw Error("Invalid endpoint URL");
let protocol = matches[1] || "https://";
let domain = matches[2];
let path = matches[3] || "/api/v4";
return `${protocol}${domain}${path}`;
}
function logIn() {
let endpoint = normalizedEndpoint(byId("server").value);
let api = new MattermostApi(endpoint);
api.logIn(byId("username").value, byId("password").value);
}
function validateToken() {
let endpoint = normalizedEndpoint(byId("server").value);
let cred = getCredentials(endpoint);
if (!cred || !cred.token) {
byId("validate").value = "No token, log in first";
byId("validate").disabled = false;
}
let api = new MattermostApi(endpoint);
api.validateToken(cred.token)
.then(() => {
byId("validate").value = "Validation succeeded";
byId("validate").disabled = false;
})
.catch(() => {
byId("validate").value = "Validation failed";
byId("validate").disabled = false;
});
}