authorization-util.ts
Overview
The authorization-util.ts file provides utility functions and a storage abstraction layer to manage user authorization-related data within a web application. Its primary purpose is to interact with the browser's localStorage to persist and retrieve authentication tokens, user information, and language preferences. Additionally, it offers a helper function to extract authorization tokens from URL search parameters and a redirect utility to navigate users to the login page.
This file simplifies handling authorization state in client-side applications by encapsulating common operations like setting, getting, and removing authorization data, and it aids in maintaining a consistent approach to managing authentication-related local storage keys.
Detailed Explanation of Contents
Imports
Authorization, Token, UserInfo (from
'@/constants/authorization'):
Constants representing the keys used inlocalStoragefor storing authorization tokens, authentication tokens, and user information respectively.getSearchValue (from
'./common-util'):
A utility function to retrieve a value from the URL query parameters by key.
KeySet Constant
const KeySet = [Authorization, Token, UserInfo];
An array holding the main keys used for authorization-related storage.
Used primarily to remove all related items from
localStoragein batch.
storage Object
An encapsulated object exposing methods for interacting with localStorage for authorization-related data.
Methods
Method | Parameters | Returns | Description |
|---|---|---|---|
| None | `string \ | null` |
| None | `string \ | null` |
| None | `string \ | null` |
| None | `object \ | null` |
|
|
| Stores the authorization string under the |
|
|
| Stores the token string under the |
| `value: string \ | Record<string, unknown>` |
|
|
|
| Batch sets multiple key-value pairs into |
| None |
| Removes the |
| None |
| Removes all keys in |
|
|
| Sets the current language preference under the |
| None |
| Retrieves the language preference stored under the |
Usage Examples
// Store authorization token
storage.setAuthorization('Bearer abc123');
// Retrieve authorization token
const authToken = storage.getAuthorization();
// Set user info as an object
storage.setUserInfo({ id: 1, name: 'John Doe' });
// Get user info as an object
const userInfo = storage.getUserInfoObject();
// Remove all auth-related items (logout scenario)
storage.removeAll();
getAuthorization Function
export const getAuthorization = () => {
const auth = getSearchValue('auth');
const authorization = auth
? 'Bearer ' + auth
: storage.getAuthorization() || '';
return authorization;
};
Purpose: Determines the current authorization token to be used by checking the URL for an
authquery parameter.Behavior:
If an
authparameter exists in the URL, it prepends'Bearer 'to it and returns this value.Otherwise, it falls back to the token stored in
localStorageunder theAuthorizationkey.Returns an empty string if neither is found.
Returns:
string— the authorization token string with the'Bearer 'prefix or empty string.Example usage:
const authHeader = getAuthorization();
// e.g., "Bearer xyz123" or ""
redirectToLogin Function
export function redirectToLogin() {
window.location.href = location.origin + `/login`;
}
Purpose: Redirects the current browser window to the login page of the application.
Behavior: Changes
window.location.hrefto the/loginpath on the current origin.Usage:
redirectToLogin(); // Navigates user to https://currentdomain/login
This function is designed to be called when the user needs to be prompted to log in, for example, after an expired or invalid token is detected.
Important Implementation Details
LocalStorage Key Consistency: The file depends on predefined constants (
Authorization,Token,UserInfo) to ensure consistent usage of localStorage keys throughout the application.JSON Serialization/Deserialization: User info is stored as a JSON string and parsed back into an object when retrieved.
Graceful Fallbacks: The
getAuthorizationfunction checks URL parameters first, allowing for token overrides via query parameters, then falls back to stored tokens.Batch Operations:
setItemsandremoveAllallow efficient batch writes and removals, which can be useful for logout or reset scenarios.Language Preference Storage: Language is treated separately with dedicated get/set functions, making it easy to manage localization preferences.
Interaction with Other Parts of the System
Constants Dependency: Relies on authorization-related constants from
'@/constants/authorization'.URL Query Parsing: Uses
getSearchValuefrom'./common-util'to extract query parameters.Authentication Flow: This utility is a foundational tool used by authentication components, API clients (for injecting
Authorizationheaders), and UI components displaying user info.Login Redirection: The
redirectToLoginfunction is likely called by authentication guards or error handlers when unauthorized access is detected.
Visual Diagram
flowchart TD
A[getAuthorization()]
B[storage.getAuthorization()]
C[getSearchValue('auth')]
D[storage.setAuthorization(value)]
E[storage.getToken()]
F[storage.setToken(value)]
G[storage.getUserInfo()]
H[storage.getUserInfoObject()]
I[storage.setUserInfo(value)]
J[storage.setItems(pairs)]
K[storage.removeAuthorization()]
L[storage.removeAll()]
M[storage.setLanguage(lng)]
N[storage.getLanguage()]
O[redirectToLogin()]
A --> C
A --> B
D --> storage
E --> storage
F --> storage
G --> storage
H --> storage
I --> storage
J --> storage
K --> storage
L --> storage
M --> storage
N --> storage
O -->|Redirects| LoginPage[Login Page URL]
Summary
The authorization-util.ts file is a centralized utility module designed to manage authorization data in local storage and provide convenient accessors and mutators for tokens and user information. It also supports language preference storage and offers a helper to retrieve tokens from URL parameters. The included redirection utility facilitates navigating users to the login page when needed. This module plays a critical role in the authentication lifecycle and state management on the client side.