auth-hooks.ts
Overview
The auth-hooks.ts file provides React custom hooks designed to handle OAuth-based authentication flows within a React application using the Umi framework. It manages the OAuth callback parameters in the URL, processes errors or successful authentication tokens, updates authorization state in the application, and facilitates user login state detection.
This file primarily offers two hooks:
useOAuthCallback: Handles the OAuth callback URL parameters (authtoken orerror), manages side effects such as displaying error messages, updating authorization tokens, URL cleanup, and navigation.useAuth: LeveragesuseOAuthCallbackand tracks whether the user is currently authenticated, exposing a simpleisLoginstate for use in components.
Detailed Descriptions
1. useOAuthCallback
Purpose
Handles processing of OAuth callback URL parameters after a user attempts to authenticate via OAuth. It detects errors or authorization tokens in the URL, triggers side effects such as error message display, token storage, URL cleanup, and navigation redirects.
Usage
This hook is intended to be used on pages that serve as OAuth redirect/callback endpoints. It abstracts the logic for handling query parameters and authorization state updates.
Implementation Details
Uses Umi's
useSearchParamsto read and manipulate the current URL query parameters.Checks for the presence of an
errorparameter, displays an error message, and redirects the user back to the login page after cleanup.Checks for the presence of an
authparameter, saves the authorization token usingauthorizationUtil, removes theauthparameter from the URL, and navigates to the root page/.Returns the
authtoken if found, otherwisenull.Uses React hooks (
useEffect,useMemo) and Umi navigation hooks (useNavigate) to manage side effects and state.
Parameters
None.
Returns
string | null: Theauthtoken retrieved from the URL query parameters, ornullif none is present.
Example Usage
const authToken = useOAuthCallback();
if (authToken) {
console.log('User authenticated with token:', authToken);
}
2. useAuth
Purpose
Provides a simple interface to check the current login status of the user by utilizing the useOAuthCallback hook and the internal authorization storage utility.
Usage
Can be used in any React component that needs to know whether the user is logged in or not.
Implementation Details
Calls
useOAuthCallbackto trigger OAuth callback processing and retrieve the current auth token.Uses local state
isLoginto store a boolean representing login status.Sets
isLogintotrueif an authorization token exists either in the URL (auth) or in persistent storage (authorizationUtil.getAuthorization()).Returns an object containing
isLoginstate.
Parameters
None.
Returns
{ isLogin: boolean | null }: An object containing the login status.nullindicates unknown or uninitialized state.
Example Usage
const { isLogin } = useAuth();
if (isLogin === true) {
console.log('User is logged in');
} else if (isLogin === false) {
console.log('User is not logged in');
}
Important Implementation Details
The hooks rely on
authorizationUtil, a utility module (presumably) responsible for persisting and retrieving authorization tokens (e.g., from localStorage or cookies). This abstraction isolates token management.Error handling is done via a UI message component
message.error(), showing the OAuth error to the user, then redirecting to the login page.URL query parameters are carefully handled to remove sensitive information (
authtoken) or error messages after processing, preventing them from lingering in the URL.Navigation is performed via Umi's
useNavigatehook to programmatically route users after authentication or errors.The hooks use React's
useEffectfor side effects anduseMemoto memoize query parameter objects for performance and stability in dependencies.
Interaction with Other Parts of the Application
UI Layer: Displays error messages using the
messagecomponent from the UI library (@/components/ui/message).Authorization Storage: Uses
authorizationUtilfrom@/utils/authorization-utilto store and retrieve authorization tokens.Routing: Uses Umi's
useNavigateanduseSearchParamshooks for navigation and URL query parameter management, integrating tightly with the app's routing.OAuth Flow: Designed to be used on the OAuth callback endpoint/page where the OAuth provider redirects after login or failure.
Login State: The
useAuthhook can be used throughout the app to gate access to components or routes based on login status.
Mermaid Diagram: Flowchart of Functions and Relationships
flowchart TD
A[useOAuthCallback] --> B[Read URL query parameters]
B -->|If error param exists| C[Show error message]
C --> D[Redirect to /login after 1s]
B -->|If auth param exists| E[Store auth token via authorizationUtil]
E --> F[Remove auth param from URL]
F --> G[Navigate to / (home)]
A --> H[Return auth token]
I[useAuth] --> J[Call useOAuthCallback]
J --> K[Get auth token]
K --> L[Check authorizationUtil for token]
L --> M[Set isLogin state]
M --> N[Return { isLogin }]
Summary
The auth-hooks.ts file encapsulates OAuth callback handling and login state detection in React hooks, providing a clean and reusable interface for integrating OAuth authentication flows within a Umi-based React application. It carefully manages URL parameters, authorization token storage, error display, and user navigation to ensure a smooth authentication experience.
If you need further details about the related authorizationUtil or message components, please refer to their respective documentation files.