75 lines
1.3 KiB
TypeScript
75 lines
1.3 KiB
TypeScript
import { APIClient } from "./ApiClient";
|
|
|
|
export interface AuthInfo {
|
|
id: string;
|
|
}
|
|
|
|
const TokenStateKey = "auth-state";
|
|
|
|
export class AuthApi {
|
|
/**
|
|
* Check out whether user is signed in or not
|
|
*/
|
|
static get SignedIn(): boolean {
|
|
return localStorage.getItem(TokenStateKey) !== null;
|
|
}
|
|
|
|
/**
|
|
* Mark user as authenticated
|
|
*/
|
|
static SetAuthenticated() {
|
|
localStorage.setItem(TokenStateKey, "");
|
|
}
|
|
|
|
/**
|
|
* Un-mark user as authenticated
|
|
*/
|
|
static UnsetAuthenticated() {
|
|
localStorage.removeItem(TokenStateKey);
|
|
}
|
|
|
|
/**
|
|
* Authenticate using user and password
|
|
*/
|
|
static async AuthWithPassword(user: string, password: string): Promise<void> {
|
|
await APIClient.exec({
|
|
uri: "/auth/password_auth",
|
|
method: "POST",
|
|
jsonData: {
|
|
user,
|
|
password,
|
|
},
|
|
});
|
|
|
|
this.SetAuthenticated();
|
|
}
|
|
|
|
/**
|
|
* Get auth information
|
|
*/
|
|
static async GetAuthInfo(): Promise<AuthInfo> {
|
|
return (
|
|
await APIClient.exec({
|
|
uri: "/auth/info",
|
|
method: "GET",
|
|
})
|
|
).data;
|
|
}
|
|
|
|
/**
|
|
* Sign out
|
|
*/
|
|
static async SignOut(): Promise<void> {
|
|
this.UnsetAuthenticated();
|
|
|
|
try {
|
|
await APIClient.exec({
|
|
uri: "/auth/sign_out",
|
|
method: "GET",
|
|
});
|
|
} finally {
|
|
window.location.href = "/";
|
|
}
|
|
}
|
|
}
|