fix: connexion

This commit is contained in:
2023-11-29 16:05:49 +01:00
parent b5b54a98ba
commit 6dc0293455
9 changed files with 88 additions and 27 deletions

View File

@ -1,26 +1,27 @@
import { Accounts } from "./accounts.js";
function extract_token(response)
{
let cookies = response.headers.get("set-cookie");
if (cookies == null)
return null;
let token = cookies.slice(cookies.indexOf("=") + 1, cookies.indexOf(';'))
return token;
}
class Client
{
constructor(url)
{
this._url = url;
this.accounts = new Accounts(this);
this._token = undefined;
this._logged = undefined;
}
isAuthentificate()
async isAuthentificate()
{
return this.token != undefined;
if (this._logged == undefined)
this.logged = await this._test_logged();
return this.logged;
}
async _get(uri)
{
let response = await fetch(this._url + uri, {
method: "GET",
});
return response;
}
async _post(uri, data)
@ -29,19 +30,35 @@ class Client
method: "POST",
headers: {
"Content-Type": "application/json",
},
},
body: JSON.stringify(data),
});
let token = extract_token(response);
if (token != null)
this.token = token;
return response;
}
async login(username, password)
{
let response = await this._post("/api/accounts/login", {username: username, password: password})
return response
let data = await response.json();
if (data == "user connected")
{
this.logged = true;
return null;
}
return data;
}
async logout()
{
await this._get("/api/accounts/logout");
this.logged = false;
}
async _test_logged()
{
let response = await this._get("/api/accounts/logged");
let data = await response.json();
return data === "True";
}
}