48 lines
1.1 KiB
TypeScript
48 lines
1.1 KiB
TypeScript
import { invoke } from "@tauri-apps/api/core";
|
|
import { ref } from "vue";
|
|
|
|
const TOKEN_STORAGE_KEY = "ewa-mobile.authToken";
|
|
const authToken = ref(localStorage.getItem(TOKEN_STORAGE_KEY) ?? "");
|
|
let restored = false;
|
|
|
|
interface AuthTokenResponse {
|
|
token: string;
|
|
}
|
|
|
|
export function useAuth() {
|
|
async function login(username: string, password: string) {
|
|
const response = await invoke<AuthTokenResponse>("auth_login", { username, password });
|
|
authToken.value = response.token;
|
|
localStorage.setItem(TOKEN_STORAGE_KEY, response.token);
|
|
restored = true;
|
|
}
|
|
|
|
async function logout() {
|
|
authToken.value = "";
|
|
localStorage.removeItem(TOKEN_STORAGE_KEY);
|
|
restored = false;
|
|
await invoke("auth_logout");
|
|
}
|
|
|
|
async function restoreToken() {
|
|
if (restored || !authToken.value) {
|
|
return;
|
|
}
|
|
|
|
await invoke("auth_set_token", { token: authToken.value });
|
|
restored = true;
|
|
}
|
|
|
|
return {
|
|
authToken,
|
|
isAuthenticated,
|
|
login,
|
|
logout,
|
|
restoreToken,
|
|
};
|
|
}
|
|
|
|
export function isAuthenticated() {
|
|
return Boolean(authToken.value);
|
|
}
|