@fluoce/auth-react 1.2.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/README.md +349 -0
  2. package/package.json +1 -1
package/README.md ADDED
@@ -0,0 +1,349 @@
1
+ # @fluoce/auth-react
2
+
3
+ **React authentication for applications powered by Fluoce Auth.**
4
+
5
+ Provider, guard, hook, and code-exchange flow — four lightweight pieces, zero boilerplate.
6
+
7
+ [GitHub](https://github.com/Ashit-mulani/SDK/tree/main/%40fluoce/auth_react) · [Ashit Mulani](https://me.fluoce.com)
8
+
9
+ ---
10
+
11
+ ## 📋 Table of Contents
12
+
13
+ - [Why This SDK](#-why-this-sdk)
14
+ - [📦 Installation](#-installation)
15
+ - [🛠️ Quick Start](#-quick-start)
16
+ - [🧩 Core Primitives](#-core-primitives)
17
+ - [1. FluoceAuthProvider](#1-fluoceauthprovider)
18
+ - [2. useFluoceAuth()](#2-usefluoceauth)
19
+ - [3. FluoceAuthGuard](#3-fluoceauthguard)
20
+ - [4. FluoceAuthFlow](#4-fluoceauthflow)
21
+ - [🔄 Authentication Flow Diagram](#-authentication-flow-diagram)
22
+ - [💻 Full Implementation Example](#-full-implementation-example)
23
+ - [💡 Best Practices](#-best-practices)
24
+ - [🏷️ Type Reference](#%EF%B8%8F-type-reference)
25
+
26
+ ---
27
+
28
+ ## 🚀 Why This SDK
29
+
30
+ `@fluoce/auth-react` completely abstracts the Fluoce Auth lifecycle—session bootstrapping, token refresh management, route guarding, and login token exchanges—into a developer-friendly React ecosystem.
31
+
32
+ | Component / Hook | Primary Purpose |
33
+ | -------------------- | --------------------------------------------------------------------------------------------- |
34
+ | `FluoceAuthProvider` | Injects global auth context, orchestrates tokens, and initializes sessions on mount. |
35
+ | `useFluoceAuth()` | Consumes user metadata, async loading states, and programmatic actions (`logout`, `refresh`). |
36
+ | `FluoceAuthGuard` | Protects specific route trees and manages automated redirection gates. |
37
+ | `FluoceAuthFlow` | Concludes the handshake sequence by exchanging temporary URL codes for active sessions. |
38
+
39
+ No manual token parsing, no custom `fetch` interceptors, and no complex state synchronization.
40
+
41
+ ---
42
+
43
+ ## 📦 Installation
44
+
45
+ Ensure your project has the minimum peer dependencies met (`react >= 18` and `react-dom >= 18`).
46
+
47
+ ```bash
48
+ npm install @fluoce/auth-react
49
+ # or
50
+ pnpm add @fluoce/auth-react
51
+ # or
52
+ yarn add @fluoce/auth-react
53
+ ```
54
+
55
+ ---
56
+
57
+ ## 🛠️ Quick Start
58
+
59
+ Setting up authentication requires only three structural steps: wrapping your application tree, protecting target views, and mounting an exchange callback route.
60
+
61
+ ### Configure the Root Provider
62
+
63
+ Wrap your main application layout inside a routing tree using `FluoceAuthProvider`.
64
+
65
+ ```tsx
66
+ // main.tsx or index.tsx
67
+ import { createRoot } from "react-dom/client";
68
+ import { BrowserRouter } from "react-router-dom";
69
+ import { FluoceAuthProvider } from "@fluoce/auth-react";
70
+ import App from "./App.tsx";
71
+
72
+ createRoot(document.getElementById("root")!).render(
73
+ <BrowserRouter>
74
+ <FluoceAuthProvider
75
+ app_url="https://your-app-domain.com" // Use only the root domain (no trailing slash)
76
+ on_unauthorized_redirect={{ type: "fluoce" }}
77
+ on_error={(error) => console.error("Fluoce Auth Error:", error)}
78
+ >
79
+ <App />
80
+ </FluoceAuthProvider>
81
+ </BrowserRouter>,
82
+ );
83
+ ```
84
+
85
+ ---
86
+
87
+ ## 🧩 Core Primitives
88
+
89
+ ### 1. `FluoceAuthProvider`
90
+
91
+ The parent context engine. It evaluates active storage footprints at startup, resolves token validity, and powers down-stream child elements.
92
+
93
+ ```typescript
94
+ interface FluoceAuthProviderType {
95
+ children: ReactNode;
96
+ app_url: string;
97
+ on_error?: (error: unknown) => void;
98
+ on_unauthorized_redirect?: FluoceRedirectType;
99
+ }
100
+ ```
101
+
102
+ | Prop | Type | Required | Description |
103
+ | -------------------------- | -------------------------- | -------- | -------------------------------------------------------------------------------------------------------- |
104
+ | `children` | `ReactNode` | Yes | The inner application component tree. |
105
+ | `app_url` | `string` | Yes | **Your app's public base address**, where users are returned following an active login session. |
106
+ | `on_error` | `(error: unknown) => void` | No | Triggered on token rotation failures, validation anomalies, or connection dropouts. |
107
+ | `on_unauthorized_redirect` | `FluoceRedirectType` | No | Policy detailing how unauthenticated guard interventions are resolved. Defaults to `{"type": "fluoce"}`. |
108
+
109
+ #### `FluoceRedirectType`
110
+
111
+ ```typescript
112
+ type FluoceRedirectType =
113
+ | { type: "fluoce" }
114
+ | { type: "custom"; redirect: (error: unknown) => void }
115
+ | { type: "none" };
116
+ ```
117
+
118
+ - `"fluoce"`: Instantly pivots unauthenticated instances outward to your hosted Fluoce identification interface.
119
+ - `"custom"`: Intercepts structural redirection routines, enabling user loops back to custom internal routes (e.g., `/login`) or firing specific analytics tracking hooks.
120
+ - `"none"`: Freezes routing layers in place with no automated interventions.
121
+
122
+ ---
123
+
124
+ ### 2. `useFluoceAuth()`
125
+
126
+ Hook interface mapping states and functional operations out of context. Must be invoked inside components within the provider tree.
127
+
128
+ ```typescript
129
+ interface FluoceAuthContextType {
130
+ user: FluoceUserType | null;
131
+ safe_loading: boolean;
132
+ auth_flow_loading: boolean;
133
+ app_url: string;
134
+ on_unauthorized_redirect: FluoceRedirectType | undefined | null;
135
+ logout(): Promise<boolean>;
136
+ refresh(): Promise<boolean>;
137
+ auth_flow({ code }: { code: string }): Promise<boolean>;
138
+ get_safe_user(): Promise<FluoceUserType | null>;
139
+ refresh_token: string | null;
140
+ access_token: string | null;
141
+ }
142
+ ```
143
+
144
+ | Property / Method | Returns | Description |
145
+ | -------------------------------- | ----------------------- | ----------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
146
+ | `user` | `FluoceUserType | null` | Read-only object containing active profile values, or `null` if unauthenticated. |
147
+ | `safe_loading` | `boolean` | `true` exclusively during standard initialization boots. Block layouts using this to eliminate rendering flashes. |
148
+ | `auth_flow_loading` | `boolean` | `true` while the system actively exchanges the code query param for production keys. |
149
+ | `logout()` | `Promise<boolean>` | Destroys token signatures, invalidates memory blocks, and signs out users. |
150
+ | `refresh()` | `Promise<boolean>` | Forces the runtime engine to prompt refresh sequences against token services. |
151
+ | `auth_flow({ code })` | `Promise<boolean>` | Exchanges the code for production session, usually internal use only. |
152
+ | `get_safe_user()` | `Promise<FluoceUserType | null>` | Re-fetch safely the active user, returns user or null. |
153
+ | `access_token` / `refresh_token` | `string | null` | Raw context variables exposed if tokens are required inside distinct back-end network headers. |
154
+
155
+ ---
156
+
157
+ ### 3. `FluoceAuthGuard`
158
+
159
+ Shield component designed to block unauthorized access to target page views.
160
+
161
+ ```typescript
162
+ interface auth_guard_interface {
163
+ children: ReactNode;
164
+ fallback?: ReactNode;
165
+ can_redirect?: boolean;
166
+ }
167
+ ```
168
+
169
+ - `fallback`: Target loader or custom component array to show while evaluation cycles process.
170
+ - `can_redirect`: When true, users missing credentials automatically trigger behaviors configured inside the parent `on_unauthorized_redirect` configuration block.
171
+
172
+ > ⚠️ **CRITICAL ARCHITECTURAL WARNING**
173
+ >
174
+ > **Never wrap the** `/auth` **callback pathway inside** `FluoceAuthGuard`**.** When users pass authenticators, they arrive at the application as an unauthenticated shell delivering a one-time token (`?code=...`). Guarding that target entry component blocks the `FluoceAuthFlow` context from receiving and resolving the hash string, resulting in an endless loop.
175
+
176
+ ---
177
+
178
+ ### 4. `FluoceAuthFlow`
179
+
180
+ The structural landing handler dedicated exclusively to reading and resolving handshakes.
181
+
182
+ ```typescript
183
+ declare const FluoceAuthFlow: (props: {
184
+ code: string;
185
+ redirect: string;
186
+ fallback?: ReactNode;
187
+ }) => JSX.Element;
188
+ ```
189
+
190
+ | Prop | Required | Description |
191
+ | ---------- | -------- | ------------------------------------------------------------------------------------------------------------------- |
192
+ | `code` | ✅ | The individual string argument read from your router's query params. |
193
+ | `redirect` | ✅ | Internal application route path to forward users toward upon authentication validation (e.g., `/` or `/dashboard`). |
194
+ | `fallback` | ❌ | Custom element tree rendered while background network validations resolve. |
195
+
196
+ ---
197
+
198
+ ## 🔄 Authentication Flow Diagram
199
+
200
+ ```text
201
+ Protected Route
202
+
203
+
204
+ FluoceAuthGuard
205
+
206
+
207
+ Authenticated?
208
+ ├── Yes ──> Render Component View
209
+ └── No
210
+
211
+
212
+ Redirect to Fluoce Login
213
+
214
+
215
+ User Signs In
216
+
217
+
218
+ /auth?code=YOUR_CODE
219
+
220
+
221
+ FluoceAuthFlow <─── (Keep this route UNGUARDED!)
222
+
223
+
224
+ Exchange Code Flow
225
+
226
+
227
+ Redirect to Application Target (e.g., "/")
228
+ ```
229
+
230
+ ---
231
+
232
+ ## 💻 Full Implementation Example
233
+
234
+ Here is a full integration architecture mapping an application utilizing `react-router-dom`:
235
+
236
+ ### `App.tsx`
237
+
238
+ ```tsx
239
+ import { Routes, Route } from "react-router-dom";
240
+ import { FluoceAuthGuard, useFluoceAuth } from "@fluoce/auth-react";
241
+ import Dashboard from "./Dashboard";
242
+ import AuthCallback from "./AuthCallback";
243
+
244
+ export default function App() {
245
+ const { safe_loading } = useFluoceAuth();
246
+
247
+ // Keep app in a holding state while initial session validation completes
248
+ if (safe_loading) {
249
+ return <div className="spinner">Initializing Secure Session...</div>;
250
+ }
251
+
252
+ return (
253
+ <Routes>
254
+ <Route
255
+ path="/"
256
+ element={
257
+ <FluoceAuthGuard
258
+ can_redirect={true}
259
+ fallback={<p>Redirecting to login...</p>}
260
+ >
261
+ <Dashboard />
262
+ </FluoceAuthGuard>
263
+ }
264
+ />
265
+ {/* Absolute public route for handling OAuth callbacks */}
266
+ <Route path="/auth" element={<AuthCallback />} />
267
+ </Routes>
268
+ );
269
+ }
270
+ ```
271
+
272
+ ### `AuthCallback.tsx`
273
+
274
+ ```tsx
275
+ import { useSearchParams } from "react-router-dom";
276
+ import { FluoceAuthFlow } from "@fluoce/auth-react";
277
+
278
+ export default function AuthCallback() {
279
+ const [searchParams] = useSearchParams();
280
+ const code = searchParams.get("code");
281
+
282
+ if (!code) {
283
+ return (
284
+ <div className="error">
285
+ Authentication failed. Missing authorization code parameter.
286
+ </div>
287
+ );
288
+ }
289
+
290
+ return (
291
+ <FluoceAuthFlow
292
+ code={code}
293
+ redirect="/"
294
+ fallback={<div>Verifying credentials, finalizing authorization...</div>}
295
+ />
296
+ );
297
+ }
298
+ ```
299
+
300
+ ### `Dashboard.tsx`
301
+
302
+ ```tsx
303
+ import { useFluoceAuth } from "@fluoce/auth-react";
304
+
305
+ export default function Dashboard() {
306
+ const { user, logout } = useFluoceAuth();
307
+
308
+ return (
309
+ <main style={{ padding: "2rem" }}>
310
+ <h1>Welcome back, {user?.name}!</h1>
311
+ <p>Registered Email: {user?.email}</p>
312
+ <button onClick={() => logout()} className="btn-logout">
313
+ Sign Out
314
+ </button>
315
+ </main>
316
+ );
317
+ }
318
+ ```
319
+
320
+ ---
321
+
322
+ ## 💡 Best Practices
323
+
324
+ 1. **Wrap At the True Root**: Place `FluoceAuthProvider` inside your router component configuration blocks to ensure contextual redirections fire cleanly without throwing layout exceptions.
325
+ 2. **Utilize** `safe_loading` **Flags**: Always lock initialization screens behind the `safe_loading` boolean parameter to give your layout time to discover existing tokens from memory frames cleanly.
326
+ 3. **Isolate Callbacks**: Dedicate a pure `/auth` layout page solely to processing the `FluoceAuthFlow` payload string. Keep it structurally clear of custom middleware actions or layout elements.
327
+
328
+ ---
329
+
330
+ ## 🏷️ Type Reference
331
+
332
+ ### `FluoceUserType`
333
+
334
+ ```typescript
335
+ type FluoceUserType = {
336
+ id: string;
337
+ name: string;
338
+ email: string | null;
339
+ phone: string | null;
340
+ photo: string | null;
341
+ createdAt: Date;
342
+ updatedAt: Date;
343
+ };
344
+ ```
345
+
346
+ ---
347
+
348
+ Built with ❤️ by **[Ashit Mulani](https://github.com/Ashit-mulani)**
349
+ Portfolio: [me.fluoce.com](https://me.fluoce.com)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fluoce/auth-react",
3
- "version": "1.2.0",
3
+ "version": "1.2.1",
4
4
  "description": "React SDK for Fluoce Auth",
5
5
  "license": "MIT",
6
6
  "type": "module",