Page MenuHomeSealhub

auth.ts
No OneTemporary

import { useState, useEffect } from "./react-api/api";
import EventEmitter from "eventemitter3";
import axios from "axios";
import {
SealiousSingleResourceResponse,
SealiousUserRoleItem,
SealiousItem,
} from "./types";
import { UserFields } from "./users";
const e = new EventEmitter();
class Session {
logged_in = false;
initialized = false;
me_promise: null | Promise<void>;
user_data: (typeof UserFields & SealiousItem) | null;
async logIn(username: string, password: string) {
await axios.post("/api/v1/sessions", { username, password });
await this.init();
e.emit("change");
this.logged_in = true;
}
async init() {
if (!this.me_promise) {
this.me_promise = axios
.get("/api/v1/users/me?attachments[roles]=true")
.then(async (response) => {
const data: SealiousSingleResourceResponse<typeof UserFields> =
response.data;
this.user_data = {
...data.item,
roles: Object.entries(data.attachments).map(
([_, role_item]: [string, SealiousUserRoleItem]) =>
role_item.role
),
};
this.logged_in = true;
this.me_promise = null;
})
.catch(() => {
this.user_data = null;
this.logged_in = false;
this.me_promise = null;
});
}
await this.me_promise;
this.initialized = true;
e.emit("change");
}
getStatus(): SessionData {
return {
logged_in: this.initialized && this.logged_in,
initialized: this.initialized,
user_id: this.initialized ? this.user_data?.id : "",
prefered_hours_per_day:
(this.initialized && this?.user_data?.prefered_hours_per_day) ||
0,
roles: this.user_data?.roles || [],
username: (this.initialized && this?.user_data?.username) || "",
};
}
async register(email: string) {
return axios.post("/api/v1/collections/registration-intents", {
email,
});
}
async updateHours(hours: number) {
await axios.patch("/api/v1/users/me", {
prefered_hours_per_day: hours,
});
await this.init();
}
async logout() {
await axios.delete("/api/v1/sessions/current");
this.logged_in = false;
await this.init();
}
}
export const Auth = new Session();
interface SessionData {
logged_in: boolean;
initialized: boolean;
user_id?: string;
prefered_hours_per_day: number;
roles: string[];
username?: string;
}
export function useSession(): SessionData {
const [session, setSession] = useState<SessionData>(Auth.getStatus());
useEffect(() => {
const callback = () => {
setSession(Auth.getStatus());
};
e.on("change", callback);
if (!Auth.me_promise && !Auth.initialized) {
Auth.init();
}
return () => {
e.removeListener("change", callback);
};
}, []);
return session;
}

File Metadata

Mime Type
text/x-c++
Expires
Sat, Nov 8, 05:43 (1 d, 6 h)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
1034065
Default Alt Text
auth.ts (2 KB)

Event Timeline