2023-06-09 08:45:01 +00:00
|
|
|
import { atom } from "jotai";
|
|
|
|
import { APIClient } from "./ApiClient";
|
|
|
|
|
2023-06-12 14:25:38 +00:00
|
|
|
export interface CheckResetTokenResponse {
|
|
|
|
name: string;
|
|
|
|
}
|
|
|
|
|
2023-06-09 08:45:01 +00:00
|
|
|
const TokenStateKey = "auth-token";
|
|
|
|
|
2023-06-06 14:39:47 +00:00
|
|
|
export class AuthApi {
|
|
|
|
/**
|
|
|
|
* Check out whether user is signed in or not
|
|
|
|
*/
|
|
|
|
static get SignedIn(): boolean {
|
2023-06-09 08:45:01 +00:00
|
|
|
return sessionStorage.getItem(TokenStateKey) !== null;
|
|
|
|
}
|
|
|
|
|
|
|
|
static authStatus = atom(this.SignedIn);
|
|
|
|
|
2023-06-09 09:19:40 +00:00
|
|
|
/**
|
|
|
|
* Get user auth token
|
|
|
|
*/
|
|
|
|
static get AuthToken(): string {
|
|
|
|
if (!this.SignedIn) throw new Error("User is not authenticated!");
|
|
|
|
return sessionStorage.getItem(TokenStateKey)!;
|
|
|
|
}
|
|
|
|
|
2023-06-09 08:45:01 +00:00
|
|
|
/**
|
|
|
|
* Start OpenID login
|
|
|
|
*
|
|
|
|
* @param id The ID of the OIDC provider to use
|
|
|
|
*/
|
|
|
|
static async StartOpenIDLogin(id: string): Promise<{ url: string }> {
|
|
|
|
return (
|
|
|
|
await APIClient.exec({
|
|
|
|
uri: "/auth/start_openid_login",
|
|
|
|
method: "POST",
|
|
|
|
jsonData: { provider: id },
|
|
|
|
})
|
|
|
|
).data;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Finish OpenID login
|
|
|
|
*/
|
|
|
|
static async FinishOpenIDLogin(code: string, state: string): Promise<void> {
|
|
|
|
const res: { user_id: number; token: string } = (
|
|
|
|
await APIClient.exec({
|
|
|
|
uri: "/auth/finish_openid_login",
|
|
|
|
method: "POST",
|
|
|
|
jsonData: { code: code, state: state },
|
|
|
|
})
|
|
|
|
).data;
|
|
|
|
|
|
|
|
sessionStorage.setItem(TokenStateKey, res.token);
|
2023-06-06 14:39:47 +00:00
|
|
|
}
|
2023-06-09 16:27:03 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Sign out
|
|
|
|
*/
|
|
|
|
static async SignOut(): Promise<void> {
|
|
|
|
await APIClient.exec({
|
|
|
|
uri: "/auth/logout",
|
|
|
|
method: "GET",
|
|
|
|
});
|
|
|
|
|
|
|
|
sessionStorage.removeItem(TokenStateKey);
|
|
|
|
}
|
2023-06-09 16:55:36 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Request to reset password
|
|
|
|
*/
|
|
|
|
static async RequestResetPassword(mail: string): Promise<void> {
|
|
|
|
await APIClient.exec({
|
|
|
|
uri: "/auth/request_reset_password",
|
|
|
|
method: "POST",
|
|
|
|
jsonData: { mail: mail },
|
|
|
|
});
|
|
|
|
}
|
2023-06-12 14:25:38 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Check reset password token
|
|
|
|
*/
|
|
|
|
static async CheckResetPasswordToken(
|
|
|
|
token: string
|
|
|
|
): Promise<CheckResetTokenResponse> {
|
|
|
|
return (
|
|
|
|
await APIClient.exec({
|
|
|
|
uri: "/auth/check_reset_password_token",
|
|
|
|
method: "POST",
|
|
|
|
jsonData: { token: token },
|
|
|
|
})
|
|
|
|
).data;
|
|
|
|
}
|
2023-06-06 14:39:47 +00:00
|
|
|
}
|