Auth API Methods
Relevant source files
The following files were used as context for generating this wiki page:
The Auth API provides a high-level interface for interacting with the CellarNode authentication system. It abstracts the underlying HTTP communication and token management, offering methods for user registration, OTP (One-Time Password) lifecycle management, session termination, and user profile retrieval.
The system is designed to work in conjunction with an AuthClient for network requests and an AuthStore for persisting and refreshing access tokens. Most methods utilize a "skipAuth" strategy during the initial authentication phases (registration and login) and transition to authenticated requests once a token is established.
Sources: src/auth-api.ts:1-12, src/types.ts:74-80
Core API Structure
The createAuthApi factory function initializes the API by injecting a specialized client and a state store. This allows the API methods to focus on business logic while the client handles base URLs and headers, and the store manages token expiration timers.
The relationship between the API interface and its dependencies.
Sources: src/auth-api.ts:13-17, src/types.ts:63-80
Authentication Lifecycle Methods
User Registration
The register method submits user details to the /auth/register endpoint. It explicitly sets skipAuth: true because the user does not yet possess an access token during the registration phase.
| Parameter | Type | Description |
|---|---|---|
name | string | The user's full name |
email | string | Primary contact and login identifier |
phone | string (Optional) | Optional contact number |
userType | "importer" | "producer" | The role category for the new account |
Sources: src/auth-api.ts:20-29, src/types.ts:12-17
OTP Flow (Request and Verify)
The authentication flow follows a two-step OTP process. First, a request is sent to trigger the delivery of a code, followed by a verification call that establishes the session.
- requestOtp: Calls
POST /auth/request-otp. It returns an object containingexpiresAtandresendAvailableAttimestamps. - verifyOtp: Calls
POST /auth/verify-otp. Upon success, it extracts the access token from the response, updates theAuthStorewith the new token and its TTL (time-to-live), and returns the user object.
The sequence of calls for acquiring an authenticated session via OTP.
Sources: src/auth-api.ts:31-61, src/extract-token.ts:1-21, tests/auth-api.test.ts:71-85
Session Management
The logout and getMe methods handle the active session. logout performs a POST /auth/logout call, while getMe retrieves the current user's profile.
getMe supports two modes of operation:
- Explicit Token: If a token is passed as an argument, it performs an unauthenticated fetch with a manual
Authorizationheader. - Stored Token: If no token is passed, it relies on the
AuthClientto automatically inject the token currently held in theAuthStore.
Sources: src/auth-api.ts:63-78, tests/auth-api.test.ts:126-145
Data Models and Errors
AuthUser Object
The following table describes the structure of the user object returned by verifyOtp and getMe.
| Field | Type | Description |
|---|---|---|
id | string | Unique identifier for the user |
email | string | User email address |
userType | string | Restricted to "importer", "producer", or "admin" |
orgId | string | null | Associated organization identifier |
roles | string[] | List of assigned permission roles |
Sources: src/types.ts:1-10
Error Handling
The API uses a custom AuthError class. When the AuthClient encounters a non-2xx response, it parses the error body (often containing a machine-readable code and remainingAttempts) and throws an instance of this class.
// Example of error handling during OTP verification
try {
await authApi.verifyOtp(email, code);
} catch (err) {
if (err instanceof AuthError) {
console.error(`Error ${err.code}: ${err.message}`);
console.log(`Attempts left: ${err.remainingAttempts}`);
}
}
Sources: src/types.ts:40-51, src/auth-client.ts:62-67
Token Extraction Logic
The API employs a robust extraction utility to handle various backend response formats. It searches for tokens in top-level fields (e.g., accessToken, access_token) as well as nested objects like data or session.
Sources: src/extract-token.ts:1-21, tests/auth-api.test.ts:87-101
Conclusion
The Auth API Methods serve as the primary gateway for identity management in CellarNode applications. By encapsulating the complexities of OTP verification, token extraction, and automatic store updates, the module ensures a consistent and secure authentication experience across dashboards. Significant logic is dedicated to ensuring that tokens are correctly retrieved regardless of response nesting and that the local AuthStore remains synchronized with the server-side session state.