Files
bknd/app/src/ui/client/schema/auth/use-auth.ts
dswbx 9070f96571 feat: enhance API and AuthApi with credentials support and async storage handling
- Added `credentials` option to `ApiOptions` and `BaseModuleApiOptions` for better request handling.
- Updated `AuthApi` to pass `verified` status during token updates.
- Refactored storage handling in `Api` to support async operations using a Proxy.
- Improved `Authenticator` to handle cookie domain configuration and JSON request detection.
- Adjusted `useAuth` to ensure logout and verify methods return promises for better async handling.
- Fixed navigation URL construction in `useNavigate` and updated context menu actions in `_data.root.tsx`.
2025-10-15 18:41:04 +02:00

66 lines
1.6 KiB
TypeScript

import type { AuthState } from "Api";
import type { AuthResponse } from "bknd";
import { useApi, useInvalidate } from "ui/client";
import { useClientContext } from "ui/client/ClientProvider";
type LoginData = {
email: string;
password: string;
[key: string]: any;
};
type UseAuth = {
data: Partial<AuthState> | undefined;
user: AuthState["user"] | undefined;
token: AuthState["token"] | undefined;
verified: boolean;
login: (data: LoginData) => Promise<AuthResponse>;
register: (data: LoginData) => Promise<AuthResponse>;
logout: () => Promise<void>;
verify: () => Promise<void>;
setToken: (token: string) => void;
};
export const useAuth = (options?: { baseUrl?: string }): UseAuth => {
const api = useApi(options?.baseUrl);
const invalidate = useInvalidate();
const { authState } = useClientContext();
const verified = authState?.verified ?? false;
async function login(input: LoginData) {
const res = await api.auth.login("password", input);
return res.data;
}
async function register(input: LoginData) {
const res = await api.auth.register("password", input);
return res.data;
}
function setToken(token: string) {
api.updateToken(token);
}
async function logout() {
await api.auth.logout();
await invalidate();
}
async function verify() {
await api.verifyAuth();
await invalidate();
}
return {
data: authState,
user: authState?.user,
token: authState?.token,
verified,
login,
register,
logout,
setToken,
verify,
};
};