Token login

This commit is contained in:
Philipp Heckel 2022-12-07 20:44:20 -05:00
parent 35657a7bbd
commit 8dcb4be8a8
11 changed files with 94 additions and 26 deletions

View file

@ -7,7 +7,7 @@ import {
topicUrlJsonPoll,
topicUrlJsonPollWithSince,
userAccountUrl,
userAuthUrl,
userTokenUrl,
userStatsUrl
} from "./utils";
import userManager from "./UserManager";
@ -119,8 +119,8 @@ class Api {
throw new Error(`Unexpected server response ${response.status}`);
}
async userAuth(baseUrl, user) {
const url = userAuthUrl(baseUrl);
async login(baseUrl, user) {
const url = userTokenUrl(baseUrl);
console.log(`[Api] Checking auth for ${url}`);
const response = await fetch(url, {
headers: maybeWithBasicAuth({}, user)
@ -135,6 +135,18 @@ class Api {
return json.token;
}
async logout(baseUrl, token) {
const url = userTokenUrl(baseUrl);
console.log(`[Api] Logging out from ${url} using token ${token}`);
const response = await fetch(url, {
method: "DELETE",
headers: maybeWithBearerAuth({}, token)
});
if (response.status !== 200) {
throw new Error(`Unexpected server response ${response.status}`);
}
}
async userStats(baseUrl) {
const url = userStatsUrl(baseUrl);
console.log(`[Api] Fetching user stats ${url}`);

View file

@ -9,6 +9,10 @@ class Session {
localStorage.removeItem("token");
}
exists() {
return this.username() && this.token();
}
username() {
return localStorage.getItem("user");
}

View file

@ -19,7 +19,7 @@ export const topicUrlJsonPollWithSince = (baseUrl, topic, since) => `${topicUrlJ
export const topicUrlAuth = (baseUrl, topic) => `${topicUrl(baseUrl, topic)}/auth`;
export const topicShortUrl = (baseUrl, topic) => shortUrl(topicUrl(baseUrl, topic));
export const userStatsUrl = (baseUrl) => `${baseUrl}/user/stats`;
export const userAuthUrl = (baseUrl) => `${baseUrl}/user/auth`;
export const userTokenUrl = (baseUrl) => `${baseUrl}/user/token`;
export const userAccountUrl = (baseUrl) => `${baseUrl}/user/account`;
export const shortUrl = (url) => url.replaceAll(/https?:\/\//g, "");
export const expandUrl = (url) => [`https://${url}`, `http://${url}`];