WIP: Auth

This commit is contained in:
Philipp Heckel 2022-02-25 13:40:03 -05:00
parent 42016f48ff
commit 1599793de2
5 changed files with 108 additions and 32 deletions

View file

@ -1,4 +1,4 @@
import {topicUrlJsonPoll, fetchLinesIterator, topicUrl} from "./utils";
import {topicUrlJsonPoll, fetchLinesIterator, topicUrl, topicUrlAuth} from "./utils";
class Api {
async poll(baseUrl, topic) {
@ -19,6 +19,20 @@ class Api {
body: message
});
}
async auth(baseUrl, topic, user) {
const url = topicUrlAuth(baseUrl, topic);
console.log(`[Api] Checking auth for ${url}`);
const response = await fetch(url);
if (response.status >= 200 && response.status <= 299) {
return true;
} else if (!user && response.status === 404) {
return true; // Special case: Anonymous login to old servers return 404 since /<topic>/auth doesn't exist
} else if (response.status === 401 || response.status === 403) { // See server/server.go
return false;
}
throw new Error(`Unexpected server response ${response.status}`);
}
}
const api = new Api();

View file

@ -10,8 +10,7 @@ class Subscriptions {
get(subscriptionId) {
const subscription = this.subscriptions.get(subscriptionId);
if (subscription === undefined) return null;
return subscription;
return (subscription) ? subscription : null;
}
update(subscription) {
@ -38,8 +37,7 @@ class Subscriptions {
firstOrNull() {
const first = this.subscriptions.values().next().value;
if (first === undefined) return null;
return first;
return (first) ? first : null;
}
size() {

View file

@ -7,6 +7,7 @@ export const topicUrlWs = (baseUrl, topic) => `${topicUrl(baseUrl, topic)}/ws`
export const topicUrlWsWithSince = (baseUrl, topic, since) => `${topicUrlWs(baseUrl, topic)}?since=${since}`;
export const topicUrlJson = (baseUrl, topic) => `${topicUrl(baseUrl, topic)}/json`;
export const topicUrlJsonPoll = (baseUrl, topic) => `${topicUrlJson(baseUrl, topic)}?poll=1`;
export const topicUrlAuth = (baseUrl, topic) => `${topicUrl(baseUrl, topic)}/auth`;
export const shortUrl = (url) => url.replaceAll(/https?:\/\//g, "");
export const shortTopicUrl = (baseUrl, topic) => shortUrl(topicUrl(baseUrl, topic));