@getmocha/users-service
Version:
An API client, Hono middleware, and a React provider for the Mocha Users Service
75 lines (74 loc) • 2.88 kB
TypeScript
import type { MochaUser } from '@getmocha/users-service/shared';
export interface AuthContextValue {
/**
* The currently authenticated user from the Mocha Users Service, or null if not authenticated.
* Use this both for checking authentication status and accessing user data.
*/
user: MochaUser | null;
/**
* `true` when the `AuthProvider` is fetching the `user` object on mount.
* Use this to show initial loading states or block until knowing the authentication status.
*/
isPending: boolean;
/**
* `true` any time the `user` object is being fetched.
*/
isFetching: boolean;
/**
* Makes a GET request to /api/users/me to fetch the current user.
* If the user is authenticated, the `user` object will be updated
* with the current user's data. Otherwise, `user` will be `null`.
*/
fetchUser: () => Promise<void>;
/**
* Makes a GET request to /api/oauth/google/redirect_url to get the login redirect URL.
* It then redirects the user to the url returned in the response to initiate the OAuth flow.
*/
redirectToLogin: () => Promise<void>;
/**
* Makes a POST request to /api/sessions with the exchange code in the request body.
* This function is expected to be used after the user completes the OAuth flow and is
* redirected back to /auth/callback?code=<exchange_code>. It expects a `code` query parameter
* in the URL. Use this only on the /auth/callback page. Once this function completes successfully,
* the user state will be updated with the currently authenticated user's data.
*/
exchangeCodeForSessionToken: () => Promise<void>;
/**
* Makes a GET request to /api/logout to log the user out.
* The `user` object will be set to `null`.
*/
logout: () => Promise<void>;
}
/**
* A React context provider that manages authentication state and related actions.
* Install this at the top of the React component tree to provide authentication
* and user management functionality. This is needed for the `useAuth` hook to work.
*
* This will always fetch the `user` object on mount.
*
* @example
* import { AuthProvider } from '@getmocha/users-service/react';
*
* // React Router example
* export default function App() {
* return (
* <AuthProvider>
* <Router>
* <Routes>
* <Route path="/" element={<HomePage />} />
* <Route path="/auth/callback" element={<AuthCallbackPage />} />
* </Routes>
* </Router>
* </AuthProvider>
* );
* }
*/
export declare function AuthProvider({ children }: {
children: React.ReactNode;
}): import("react/jsx-runtime").JSX.Element;
/**
* A React hook that provides the AuthContextValue.
* @example
* const { user } = useAuth();
*/
export declare function useAuth(): AuthContextValue;