VirtWeb/virtweb_frontend/src/api/AuthApi.ts

102 lines
1.9 KiB
TypeScript
Raw Normal View History

2023-09-04 12:11:56 +00:00
import { APIClient } from "./ApiClient";
2023-09-04 13:12:00 +00:00
export interface AuthInfo {
id: string;
}
2023-09-04 12:11:56 +00:00
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 an username and a password
*
* @param username The username to use
* @param password The password to use
*/
static async LoginWithPassword(
username: string,
password: string
): Promise<void> {
await APIClient.exec({
uri: "/auth/local",
method: "POST",
jsonData: {
username: username,
password: password,
},
});
this.SetAuthenticated();
}
/**
* Start OpenID login
*/
static async StartOpenIDLogin(): Promise<{ url: string }> {
return (
await APIClient.exec({
uri: "/auth/start_oidc",
method: "GET",
})
).data;
}
/**
* Finish OpenID login
*/
static async FinishOpenIDLogin(code: string, state: string): Promise<void> {
await APIClient.exec({
uri: "/auth/finish_oidc",
method: "POST",
jsonData: { code: code, state: state },
});
this.SetAuthenticated();
}
2023-09-04 13:12:00 +00:00
/**
* Get auth information
*/
static async GetAuthInfo(): Promise<AuthInfo> {
return (
await APIClient.exec({
uri: "/auth/user",
method: "GET",
})
).data;
}
2023-09-04 12:11:56 +00:00
/**
* Sign out
*/
static async SignOut(): Promise<void> {
await APIClient.exec({
uri: "/auth/sign_out",
method: "GET",
});
this.UnsetAuthenticated();
}
}