mirror of
https://github.com/shishantbiswas/bknd.git
synced 2026-03-15 20:17:22 +00:00
67 lines
1.6 KiB
TypeScript
67 lines
1.6 KiB
TypeScript
import type { AuthState } from "Api";
|
|
import type { AuthResponse } from "bknd";
|
|
import { useApi, useInvalidate, useClientContext } from "bknd/client";
|
|
|
|
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;
|
|
local: boolean;
|
|
};
|
|
|
|
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,
|
|
local: !!api.options.storage,
|
|
};
|
|
};
|