2021-12-10 13:55:05 +00:00
|
|
|
import { makeAutoObservable, ObservableMap } from "mobx";
|
2021-12-10 12:53:41 +00:00
|
|
|
import { Session } from "revolt-api/types/Auth";
|
|
|
|
import { Nullable } from "revolt.js/dist/util/null";
|
|
|
|
|
|
|
|
import Persistent from "../Persistent";
|
|
|
|
import { deleteKey } from "../objectUtil";
|
|
|
|
|
|
|
|
interface Data {
|
|
|
|
sessions: Record<string, Session>;
|
|
|
|
current?: string;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Handles account authentication, managing multiple
|
|
|
|
* accounts and their sessions.
|
|
|
|
*/
|
|
|
|
export default class Auth implements Persistent<Data> {
|
2021-12-10 13:55:05 +00:00
|
|
|
private sessions: ObservableMap<string, Session>;
|
2021-12-10 12:53:41 +00:00
|
|
|
private current: Nullable<string>;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Construct new Auth store.
|
|
|
|
*/
|
|
|
|
constructor() {
|
2021-12-10 13:55:05 +00:00
|
|
|
this.sessions = new ObservableMap();
|
2021-12-10 12:53:41 +00:00
|
|
|
this.current = null;
|
|
|
|
makeAutoObservable(this);
|
|
|
|
}
|
|
|
|
|
|
|
|
// eslint-disable-next-line require-jsdoc
|
|
|
|
toJSON() {
|
|
|
|
return {
|
|
|
|
sessions: this.sessions,
|
|
|
|
current: this.current,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
// eslint-disable-next-line require-jsdoc
|
|
|
|
hydrate(data: Data) {
|
2021-12-10 13:55:05 +00:00
|
|
|
Object.keys(data.sessions).forEach((id) =>
|
|
|
|
this.sessions.set(id, data.sessions[id]),
|
|
|
|
);
|
|
|
|
|
|
|
|
if (data.current && this.sessions.has(data.current)) {
|
2021-12-10 12:53:41 +00:00
|
|
|
this.current = data.current;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Add a new session to the auth manager.
|
|
|
|
* @param session Session
|
|
|
|
*/
|
|
|
|
setSession(session: Session) {
|
2021-12-10 13:55:05 +00:00
|
|
|
this.sessions.set(session.user_id, session);
|
2021-12-10 12:53:41 +00:00
|
|
|
this.current = session.user_id;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Remove existing session by user ID.
|
|
|
|
* @param user_id User ID tied to session
|
|
|
|
*/
|
|
|
|
removeSession(user_id: string) {
|
|
|
|
this.sessions = deleteKey(this.sessions, user_id);
|
|
|
|
|
|
|
|
if (user_id == this.current) {
|
|
|
|
this.current = null;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|