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:


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

Parameters

Returns

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

Parameters

Returns

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


Interaction with Other Parts of the Application


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.