@umituz/react-native-auth 3.4.32 → 3.4.33

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.
@@ -1,248 +1,362 @@
1
1
  # useAuthRequired & useRequireAuth
2
2
 
3
- Two hooks for authentication requirements in components.
3
+ Hooks for authentication requirements in components.
4
4
 
5
5
  ---
6
6
 
7
7
  ## useAuthRequired
8
8
 
9
- Check auth requirements and show modal if needed.
9
+ Check auth requirements and trigger auth modal if needed.
10
10
 
11
- ### Usage
11
+ ### Strategy
12
12
 
13
+ **Purpose**: Provides functionality to check authentication status and automatically show auth modal when user is not authenticated. Ideal for protecting specific actions.
14
+
15
+ **When to Use**:
16
+ - Protecting specific actions (like, comment, save)
17
+ - Need to show auth modal on demand
18
+ - Want to defer auth requirement until action
19
+ - Conditional auth based on user interaction
20
+
21
+ **Import Path**:
13
22
  ```typescript
14
23
  import { useAuthRequired } from '@umituz/react-native-auth';
15
-
16
- function LikeButton() {
17
- const { isAllowed, isLoading, requireAuth, checkAndRequireAuth } = useAuthRequired();
18
-
19
- const handleLike = () => {
20
- if (checkAndRequireAuth()) {
21
- // User is authenticated, proceed
22
- likePost();
23
- }
24
- // Otherwise, auth modal is shown automatically
25
- };
26
-
27
- return (
28
- <Button onPress={handleLike} disabled={isLoading}>
29
- {isAllowed ? 'Like' : 'Sign in to like'}
30
- </Button>
31
- );
32
- }
33
24
  ```
34
25
 
35
- ### API
26
+ **Hook Location**: `src/presentation/hooks/useAuthRequired.ts`
36
27
 
37
- | Prop | Type | Description |
38
- |------|------|-------------|
39
- | `isAllowed` | `boolean` | Whether user is authenticated (not anonymous) |
40
- | `isLoading` | `boolean` | Whether auth is still loading |
41
- | `userId` | `string \| null` | Current user ID (null if not authenticated) |
42
- | `requireAuth` | `() => void` | Show auth modal |
43
- | `checkAndRequireAuth` | `() => boolean` | Check and show modal if needed, returns true/false |
28
+ **Modal Store**: `src/presentation/stores/authModalStore.ts`
44
29
 
45
- ### Examples
30
+ ### Rules
46
31
 
47
- #### Add to Favorites
32
+ **MUST**:
33
+ - Call `checkAndRequireAuth()` before protected action
34
+ - Handle `isLoading` state appropriately
35
+ - Check `isAllowed` before granting access
36
+ - Provide clear indication that auth is required
37
+ - Respect user cancellation of auth modal
48
38
 
49
- ```typescript
50
- function AddToFavoritesButton({ postId }) {
51
- const { isAllowed, checkAndRequireAuth } = useAuthRequired();
52
-
53
- const handleAddToFavorites = () => {
54
- if (!checkAndRequireAuth()) {
55
- return; // Auth modal opened, stop here
56
- }
57
-
58
- // User authenticated, proceed
59
- addToFavorites(postId);
60
- };
61
-
62
- return (
63
- <TouchableOpacity onPress={handleAddToFavorites}>
64
- <HeartIcon filled={isAllowed} />
65
- </TouchableOpacity>
66
- );
67
- }
68
- ```
39
+ **MUST NOT**:
40
+ - Perform protected action without auth check
41
+ - Show auth modal unnecessarily
42
+ - Block user actions indefinitely
43
+ - Ignore auth check results
69
44
 
70
- #### Post Comment
45
+ ### Constraints
71
46
 
72
- ```typescript
73
- function CommentForm({ postId }) {
74
- const { isAllowed, requireAuth, userId } = useAuthRequired();
75
- const [comment, setComment] = useState('');
76
-
77
- const handleSubmit = () => {
78
- if (!isAllowed) {
79
- requireAuth(); // Open auth modal
80
- return;
81
- }
82
-
83
- // Submit comment
84
- submitComment(postId, userId, comment);
85
- setComment('');
86
- };
87
-
88
- return (
89
- <View>
90
- <TextInput
91
- value={comment}
92
- onChangeText={setComment}
93
- placeholder={isAllowed ? "Write your comment..." : "Sign in to comment"}
94
- editable={isAllowed}
95
- />
96
- <Button onPress={handleSubmit} disabled={!isAllowed}>
97
- {isAllowed ? 'Submit' : 'Sign In'}
98
- </Button>
99
- </View>
100
- );
101
- }
102
- ```
47
+ **RETURN VALUES**:
48
+ - `isAllowed: boolean` - Whether user can proceed
49
+ - `isLoading: boolean` - Auth check in progress
50
+ - `requireAuth: () => void` - Show auth modal
51
+ - `checkAndRequireAuth: () => boolean` - Check and show modal if needed
52
+
53
+ **AUTH MODAL BEHAVIOR**:
54
+ - Automatically shown when `checkAndRequireAuth()` called for unauthenticated user
55
+ - User can cancel modal
56
+ - Returns `false` if user cancels
57
+ - Returns `true` if user authenticates
58
+ - Modal managed by `authModalStore`
59
+
60
+ **PLATFORM SUPPORT**:
61
+ - iOS: ✅ Fully supported
62
+ - Android: ✅ Fully supported
63
+ - Web: ✅ Fully supported
103
64
 
104
65
  ---
105
66
 
106
67
  ## useRequireAuth
107
68
 
108
- For components that **must** have an authenticated user. Throws if not authenticated.
69
+ Hook-based pattern for conditional rendering and auth checks.
70
+
71
+ ### Strategy
109
72
 
110
- ### Usage
73
+ **Purpose**: Provides authentication status for conditional rendering and inline auth checks. More flexible than modal-based approach.
111
74
 
75
+ **When to Use**:
76
+ - Need conditional rendering based on auth state
77
+ - Want to check auth without showing modal
78
+ - Prefer hook-based API over modal
79
+ - Need fine-grained control over auth flow
80
+
81
+ **Import Path**:
112
82
  ```typescript
113
83
  import { useRequireAuth } from '@umituz/react-native-auth';
84
+ ```
114
85
 
115
- function UserProfile() {
116
- const userId = useRequireAuth(); // string, not null
86
+ **Hook Location**: `src/presentation/hooks/useAuthRequired.ts`
117
87
 
118
- useEffect(() => {
119
- // userId is guaranteed to be string
120
- fetchUserData(userId);
121
- }, [userId]);
88
+ ### Rules
122
89
 
123
- return <ProfileContent userId={userId} />;
124
- }
125
- ```
90
+ **MUST**:
91
+ - Check `isAuthReady` before making decisions
92
+ - Handle `isLoading` state appropriately
93
+ - Use return values for conditional logic
94
+ - Provide clear UI feedback for auth requirements
95
+ - Not render protected content before auth ready
126
96
 
127
- ### useUserId (Safe Alternative)
97
+ **MUST NOT**:
98
+ - Assume authentication without checking
99
+ - Show protected content during loading
100
+ - Create confusing mixed auth states
101
+ - Ignore `isAuthReady` state
128
102
 
129
- Returns null if user is not authenticated:
103
+ ### Constraints
130
104
 
131
- ```typescript
132
- import { useUserId } from '@umituz/react-native-auth';
105
+ **RETURN VALUES**:
106
+ - `isAuthenticated: boolean` - Auth status
107
+ - `isAuthReady: boolean` - Initial check complete
108
+ - `isLoading: boolean` - Currently checking auth
109
+ - `user: User | null` - User object if authenticated
133
110
 
134
- function MaybeUserProfile() {
135
- const userId = useUserId(); // string | null
111
+ **USAGE PATTERNS**:
112
+ - Early return if not authenticated
113
+ - Conditional rendering based on auth state
114
+ - Show loading during initial check
115
+ - Navigate or show modal if needed
136
116
 
137
- if (!userId) {
138
- return <LoginPrompt />;
139
- }
117
+ **PERFORMANCE**:
118
+ - Single auth check per component mount
119
+ - Memoized return values
120
+ - No unnecessary re-renders
121
+ - Efficient state updates
140
122
 
141
- return <ProfileContent userId={userId} />;
142
- }
143
- ```
123
+ ---
144
124
 
145
- ### Examples
125
+ ## Comparison: useAuthRequired vs useRequireAuth
146
126
 
147
- #### Order History
127
+ ### Strategy
148
128
 
149
- ```typescript
150
- function OrderHistory() {
151
- const userId = useRequireAuth(); // User must be authenticated
152
-
153
- const { data: orders, isLoading } = useQuery({
154
- queryKey: ['orders', userId],
155
- queryFn: () => fetchOrders(userId),
156
- });
157
-
158
- if (isLoading) return <LoadingSpinner />;
159
-
160
- return (
161
- <FlatList
162
- data={orders}
163
- renderItem={({ item }) => <OrderCard order={item} />}
164
- />
165
- );
166
- }
167
- ```
129
+ **Purpose**: Choose the right hook for your use case.
168
130
 
169
- #### User Settings
131
+ **Selection Guide**:
170
132
 
171
- ```typescript
172
- function UserSettings() {
173
- const userId = useRequireAuth();
133
+ **useAuthRequired** - Use when:
134
+ - Want automatic modal on auth failure
135
+ - Protecting button clicks or actions
136
+ - Need simple auth check + modal flow
137
+ - Don't need custom auth handling
174
138
 
175
- const updateSettings = async (settings: UserSettings) => {
176
- await updateUserSettings(userId, settings);
177
- };
139
+ **useRequireAuth** - Use when:
140
+ - Need conditional rendering
141
+ - Want to check auth without modal
142
+ - Require custom auth handling
143
+ - Need more control over auth flow
178
144
 
179
- return <SettingsForm onSave={updateSettings} />;
180
- }
181
- ```
145
+ **KEY DIFFERENCES**:
146
+ - `useAuthRequired`: Shows modal automatically
147
+ - `useRequireAuth`: Returns status for custom handling
148
+ - Can be used together if needed
149
+ - Choose based on desired UX pattern
182
150
 
183
- ### Error Handling
151
+ ---
184
152
 
185
- Wrap components using `useRequireAuth` with Error Boundary:
153
+ ## Loading States
186
154
 
187
- ```typescript
188
- function App() {
189
- return (
190
- <ErrorBoundary fallback={<LoginScreen />}>
191
- <Routes>
192
- <Route path="/settings" element={<UserSettings />} />
193
- <Route path="/orders" element={<OrderHistory />} />
194
- </Routes>
195
- </ErrorBoundary>
196
- );
197
- }
198
- ```
155
+ ### Strategy
199
156
 
200
- ## Comparison Table
157
+ **Purpose**: Proper UX during authentication state checks.
201
158
 
202
- | Situation | Hook | Why |
203
- |-----------|------|-----|
204
- | Check auth before action | `useAuthRequired` | Can show modal, graceful degradation |
205
- | Show auth modal | `useAuthRequired` | Has `requireAuth()` method |
206
- | Component requires auth | `useRequireAuth` | Type-safe, non-null userId |
207
- | Optional auth | `useUserId` | Safe, can return null |
159
+ **Rules**:
160
+ - MUST handle `isLoading = true` appropriately
161
+ - MUST show loading indication for slow checks
162
+ - MUST NOT block entire UI during loading
163
+ - MUST disable protected actions during loading
208
164
 
209
- ## Code Comparison
165
+ **MUST NOT**:
166
+ - Ignore loading state
167
+ - Allow actions during auth check
168
+ - Show blank screens indefinitely
169
+ - Skip loading indicators
210
170
 
211
- ```typescript
212
- // ❌ Wrong - useRequireAuth with modal attempt
213
- function BadComponent() {
214
- const userId = useRequireAuth(); // Will throw!
215
-
216
- const handleClick = () => {
217
- // Never reaches here
218
- };
219
- }
220
-
221
- // Good - useAuthRequired with modal
222
- function GoodComponent() {
223
- const { isAllowed, requireAuth } = useAuthRequired();
224
-
225
- const handleClick = () => {
226
- if (!isAllowed) {
227
- requireAuth(); // Show modal
228
- return;
229
- }
230
- // Perform action
231
- };
232
- }
233
-
234
- // ✅ Good - useRequireAuth for required auth
235
- function ProtectedComponent() {
236
- const userId = useRequireAuth(); // Type-safe: string
237
-
238
- // Use userId
239
- useEffect(() => {
240
- fetchUserData(userId);
241
- }, [userId]);
242
- }
243
- ```
171
+ ### Constraints
172
+
173
+ **LOADING SOURCES**:
174
+ - Initial auth state check
175
+ - Auth modal display
176
+ - Authentication operation
177
+ - State updates
178
+
179
+ **LOADING DURATION**:
180
+ - Typically < 500ms for state check
181
+ - Modal display: User-controlled
182
+ - Auth operation: Variable (network dependent)
183
+ - Timeout after 10 seconds
184
+
185
+ **UI PATTERNS**:
186
+ - Disable button during loading
187
+ - Show spinner or skeleton
188
+ - Prevent duplicate actions
189
+ - Clear completion feedback
190
+
191
+ ---
192
+
193
+ ## Auth Modal Integration
194
+
195
+ ### Strategy
196
+
197
+ **Purpose**: Seamless integration with auth modal for user authentication.
198
+
199
+ **Rules**:
200
+ - MUST use `authModalStore` for modal management
201
+ - MUST handle modal dismiss events
202
+ - MUST respect user cancellation
203
+ - MUST update auth state after successful auth
204
+
205
+ **MUST NOT**:
206
+ - Show multiple modals simultaneously
207
+ - Block modal dismissal
208
+ - Ignore auth results
209
+ - Trap user in modal
210
+
211
+ ### Constraints
212
+
213
+ **MODAL STORE**:
214
+ - Managed by Zustand store
215
+ - Single modal instance
216
+ - Global state across app
217
+ - Accessible from any component
218
+
219
+ **MODAL BEHAVIOR**:
220
+ - Shows on `checkAndRequireAuth()` call
221
+ - Covers entire screen
222
+ - Dismissible by user
223
+ - Contains login/register forms
224
+ - Auto-closes on successful auth
225
+
226
+ **INTEGRATION POINTS**:
227
+ - `useAuthRequired` triggers modal
228
+ - `authModalStore` manages state
229
+ - `AuthBottomSheet` renders modal
230
+ - `useAuth` provides auth state
231
+
232
+ ---
233
+
234
+ ## Error Handling
235
+
236
+ ### Strategy
237
+
238
+ **Purpose**: Graceful handling of auth check failures.
239
+
240
+ **Rules**:
241
+ - MUST handle auth check errors gracefully
242
+ - MUST show user-friendly error messages
243
+ - MUST allow retry after failures
244
+ - MUST not crash on auth failures
245
+
246
+ **MUST NOT**:
247
+ - Show raw error messages
248
+ - Block app functionality
249
+ - Crash on auth errors
250
+ - Expose sensitive error details
251
+
252
+ ### Constraints
253
+
254
+ **ERROR SCENARIOS**:
255
+ - Network error during auth check
256
+ - Auth service unavailable
257
+ - Corrupted auth state
258
+ - Modal display failure
259
+
260
+ **RECOVERY OPTIONS**:
261
+ - Retry auth check automatically
262
+ - Show error with retry option
263
+ - Allow guest access (if applicable)
264
+ - Graceful degradation
265
+
266
+ **ERROR DISPLAY**:
267
+ - Inline message for minor issues
268
+ - Modal for critical errors
269
+ - Toast for transient issues
270
+ - Console logging for debugging
271
+
272
+ ---
273
+
274
+ ## Security Considerations
275
+
276
+ ### Strategy
277
+
278
+ **Purpose**: Ensure auth requirement enforcement is secure.
279
+
280
+ **Rules**:
281
+ - MUST enforce auth requirement at component level
282
+ - MUST validate auth state before protected actions
283
+ - MUST not rely solely on UI protection
284
+ - MUST implement backend auth validation
285
+
286
+ **MUST NOT**:
287
+ - Rely only on client-side checks
288
+ - Assume UI protection is sufficient
289
+ - Skip backend validation
290
+ - Expose protected data without auth
291
+
292
+ ### Constraints
293
+
294
+ **DEFENSE IN DEPTH**:
295
+ - Client-side: These hooks enforce UI protection
296
+ - API-level: Token validation on requests
297
+ - Data-level: Firebase security rules
298
+ - Backend: Server-side auth checks
299
+
300
+ **LIMITATIONS**:
301
+ - Client-side checks can be bypassed
302
+ - Not a replacement for backend security
303
+ - UI protection only, not data protection
304
+ - Must complement with server-side validation
305
+
306
+ **BEST PRACTICES**:
307
+ - Use hooks for UX, not security
308
+ - Validate on backend always
309
+ - Implement proper API auth
310
+ - Use Firebase security rules
311
+
312
+ ---
313
+
314
+ ## Performance Optimization
315
+
316
+ ### Strategy
317
+
318
+ **Purpose**: Efficient auth state management for smooth UX.
319
+
320
+ **Rules**:
321
+ - MUST minimize unnecessary auth checks
322
+ - MUST memoize expensive computations
323
+ - MUST avoid redundant re-renders
324
+ - MUST optimize auth state subscriptions
325
+
326
+ **MUST NOT**:
327
+ - Check auth on every render
328
+ - Create multiple auth listeners
329
+ - Cause cascading re-renders
330
+ - Block main thread with auth checks
331
+
332
+ ### Constraints
333
+
334
+ **OPTIMIZATION TECHNIQUES**:
335
+ - Single auth state store
336
+ - Memoized selectors
337
+ - Efficient state updates
338
+ - Batched state changes
339
+ - Lazy modal rendering
340
+
341
+ **PERFORMANCE METRICS**:
342
+ - Auth check: < 50ms after initial load
343
+ - Re-render impact: Minimal
344
+ - Memory usage: Constant
345
+ - Modal display: Smooth animation
346
+
347
+ ---
244
348
 
245
349
  ## Related Hooks
246
350
 
247
- - [`useAuth`](./useAuth.md) - Main auth state management
248
- - [`useAuthModalStore`](../stores/authModalStore.ts) - Auth modal state
351
+ - **`useAuth`** (`src/presentation/hooks/useAuth.ts`) - Core authentication state
352
+ - **`useUserProfile`** (`src/presentation/hooks/useUserProfile.ts`) - Profile data access
353
+ - **`useAuthBottomSheet`** (`src/presentation/hooks/useAuthBottomSheet.md`) - Modal management
354
+
355
+ ## Related Stores
356
+
357
+ - **`authModalStore`** (`src/presentation/stores/authModalStore.ts`) - Auth modal state
358
+ - **`authStore`** (`src/presentation/stores/authStore.ts`) - Auth state management
359
+
360
+ ## Related Components
361
+
362
+ - **`AuthBottomSheet`** (`src/presentation/components/AuthBottomSheet.tsx`) - Auth modal UI