@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,255 +1,299 @@
1
1
  # useAuth
2
2
 
3
- Primary authentication hook for managing auth state and operations.
3
+ Primary authentication hook for managing authentication state and operations.
4
4
 
5
- ## Features
5
+ ---
6
6
 
7
- - Centralized Zustand store for auth state
8
- - Email/password authentication
9
- - Anonymous mode support
10
- - Type-safe API
11
- - Automatic error handling
7
+ ## Strategy
12
8
 
13
- ## Usage
9
+ **Purpose**: Centralized authentication state management using Zustand with Firebase integration. Single source of truth for all authentication-related state and operations.
14
10
 
11
+ **When to Use**:
12
+ - Need to check if user is authenticated
13
+ - Require user information in components
14
+ - Need to perform sign in/sign up operations
15
+ - Want to handle anonymous users
16
+ - Need authentication state across app
17
+
18
+ **Import Path**:
15
19
  ```typescript
16
20
  import { useAuth } from '@umituz/react-native-auth';
17
-
18
- function MyComponent() {
19
- const {
20
- user,
21
- userId,
22
- userType,
23
- loading,
24
- isAuthReady,
25
- isAnonymous,
26
- isAuthenticated,
27
- error,
28
- signIn,
29
- signUp,
30
- signOut,
31
- continueAnonymously,
32
- setError,
33
- } = useAuth();
34
-
35
- // Handle loading state
36
- if (loading) return <LoadingSpinner />;
37
-
38
- // Redirect to login if not authenticated
39
- if (!isAuthenticated) {
40
- return <LoginScreen />;
41
- }
42
-
43
- return (
44
- <View>
45
- <Text>Welcome, {user?.email}</Text>
46
- <Button onPress={signOut}>Sign Out</Button>
47
- </View>
48
- );
49
- }
50
21
  ```
51
22
 
52
- ## API
23
+ **Hook Location**: `src/presentation/hooks/useAuth.ts`
53
24
 
54
- ### Return Value
25
+ **Store Location**: `src/presentation/stores/authStore.ts`
55
26
 
56
- | Prop | Type | Description |
57
- |------|------|-------------|
58
- | `user` | `AuthUser \| null` | Current authenticated user |
59
- | `userId` | `string \| null` | Current user ID (uid) |
60
- | `userType` | `UserType` | Current user type |
61
- | `loading` | `boolean` | Whether auth state is loading |
62
- | `isAuthReady` | `boolean` | Whether auth is ready (initialized and not loading) |
63
- | `isAnonymous` | `boolean` | Whether user is anonymous |
64
- | `isAuthenticated` | `boolean` | Whether user is authenticated (not anonymous) |
65
- | `error` | `string \| null` | Current error message |
66
- | `signIn` | `(email, password) => Promise<void>` | Sign in function |
67
- | `signUp` | `(email, password, displayName?) => Promise<void>` | Sign up function |
68
- | `signOut` | `() => Promise<void>` | Sign out function |
69
- | `continueAnonymously` | `() => Promise<void>` | Continue anonymously function |
70
- | `setError` | `(error: string \| null) => void` | Set error manually |
27
+ ---
71
28
 
72
- ## Examples
29
+ ## State Properties
73
30
 
74
- ### Login Form
31
+ ### Authentication State
75
32
 
76
- ```typescript
77
- function LoginForm() {
78
- const { signIn, loading, error } = useAuth();
79
- const [email, setEmail] = useState('');
80
- const [password, setPassword] = useState('');
81
-
82
- const handleLogin = async () => {
83
- try {
84
- await signIn(email, password);
85
- // Navigate to home on success
86
- } catch (err) {
87
- // Error is automatically set in error state
88
- }
89
- };
90
-
91
- return (
92
- <View>
93
- <TextInput
94
- value={email}
95
- onChangeText={setEmail}
96
- placeholder="Email"
97
- autoCapitalize="none"
98
- keyboardType="email-address"
99
- />
100
- <TextInput
101
- value={password}
102
- onChangeText={setPassword}
103
- placeholder="Password"
104
- secureTextEntry
105
- />
106
- {error && <Text style={{ color: 'red' }}>{error}</Text>}
107
- <Button onPress={handleLogin} disabled={loading}>
108
- {loading ? 'Signing in...' : 'Sign In'}
109
- </Button>
110
- </View>
111
- );
112
- }
113
- ```
33
+ **AVAILABLE PROPERTIES**:
34
+ - `user` - Full Firebase user object or null
35
+ - `userId` - User UID string or undefined
36
+ - `userType` - User type enum ('anonymous' | 'email' | 'social')
37
+ - `loading` - Boolean for initial auth check
38
+ - `isAuthReady` - Boolean indicating initial check complete
39
+ - `isAnonymous` - Boolean for anonymous user
40
+ - `isAuthenticated` - Boolean for authenticated user
41
+ - `error` - Error string or null
114
42
 
115
- ### Registration Form
43
+ **STATE RULES**:
44
+ - MUST check `isAuthReady` before using auth state
45
+ - MUST handle `loading` state appropriately
46
+ - MUST NOT assume user is authenticated without checking
47
+ - MUST handle `null` user values
116
48
 
117
- ```typescript
118
- function RegisterForm() {
119
- const { signUp, loading, error } = useAuth();
120
- const [email, setEmail] = useState('');
121
- const [password, setPassword] = useState('');
122
- const [displayName, setDisplayName] = useState('');
123
-
124
- const handleRegister = async () => {
125
- try {
126
- await signUp(email, password, displayName);
127
- // Success - user is automatically signed in
128
- } catch (err) {
129
- // Error handling
130
- }
131
- };
132
-
133
- return (
134
- <View>
135
- <TextInput
136
- value={displayName}
137
- onChangeText={setDisplayName}
138
- placeholder="Full Name"
139
- />
140
- <TextInput
141
- value={email}
142
- onChangeText={setEmail}
143
- placeholder="Email"
144
- keyboardType="email-address"
145
- />
146
- <TextInput
147
- value={password}
148
- onChangeText={setPassword}
149
- placeholder="Password"
150
- secureTextEntry
151
- />
152
- {error && <Text style={{ color: 'red' }}>{error}</Text>}
153
- <Button onPress={handleRegister} disabled={loading}>
154
- {loading ? 'Creating account...' : 'Sign Up'}
155
- </Button>
156
- </View>
157
- );
158
- }
159
- ```
49
+ **STATE CONSTRAINTS**:
50
+ - `loading` is `true` only during initial auth check
51
+ - `isAuthReady` becomes `true` after first auth check
52
+ - `user` is `null` for unauthenticated users
53
+ - `userId` is `undefined` for anonymous users
54
+ - `error` is auto-cleared after successful operations
160
55
 
161
- ### Anonymous Mode
56
+ ---
162
57
 
163
- ```typescript
164
- function AnonymousPrompt() {
165
- const { continueAnonymously, loading } = useAuth();
166
-
167
- return (
168
- <View>
169
- <Text>Continue without an account?</Text>
170
- <Button onPress={continueAnonymously} disabled={loading}>
171
- {loading ? 'Starting...' : 'Continue as Guest'}
172
- </Button>
173
- </View>
174
- );
175
- }
176
- ```
58
+ ## Authentication Methods
177
59
 
178
- ### Auth State Checking
60
+ ### signIn
179
61
 
180
- ```typescript
181
- function ProtectedContent() {
182
- const { isAuthenticated, isAuthReady, user } = useAuth();
183
-
184
- // Show loading while auth initializes
185
- if (!isAuthReady) {
186
- return <LoadingScreen />;
187
- }
188
-
189
- // Redirect if not authenticated
190
- if (!isAuthenticated) {
191
- return <LoginScreen />;
192
- }
193
-
194
- // Show protected content
195
- return (
196
- <View>
197
- <Text>Welcome, {user?.email}</Text>
198
- <ProtectedContent />
199
- </View>
200
- );
201
- }
202
- ```
62
+ **Purpose**: Authenticate user with email and password.
203
63
 
204
- ### Sign Out
64
+ **Parameters**:
65
+ - `email: string` - User email address
66
+ - `password: string` - User password
205
67
 
206
- ```typescript
207
- function ProfileScreen() {
208
- const { user, signOut } = useAuth();
209
- const navigation = useNavigation();
210
-
211
- const handleSignOut = async () => {
212
- Alert.alert(
213
- 'Sign Out',
214
- 'Are you sure you want to sign out?',
215
- [
216
- { text: 'Cancel', style: 'cancel' },
217
- {
218
- text: 'Sign Out',
219
- onPress: async () => {
220
- try {
221
- await signOut();
222
- navigation.reset({
223
- index: 0,
224
- routes: [{ name: 'Login' }],
225
- });
226
- } catch (error) {
227
- Alert.alert('Error', 'Failed to sign out');
228
- }
229
- },
230
- },
231
- ]
232
- );
233
- };
234
-
235
- return (
236
- <View>
237
- <Text>{user?.email}</Text>
238
- <Button onPress={handleSignOut}>Sign Out</Button>
239
- </View>
240
- );
241
- }
242
- ```
68
+ **Rules**:
69
+ - MUST validate email format before calling
70
+ - MUST validate password is not empty
71
+ - MUST handle loading state during call
72
+ - MUST display error messages on failure
73
+ - MUST NOT expose password in logs/errors
74
+
75
+ **Constraints**:
76
+ - Requires Firebase project configured
77
+ - Email must exist in Firebase Auth
78
+ - Password must match Firebase record
79
+ - Throws on network errors
80
+ - Auto-updates auth state on success
81
+
82
+ ---
83
+
84
+ ### signUp
85
+
86
+ **Purpose**: Create new user account with email, password, and display name.
87
+
88
+ **Parameters**:
89
+ - `email: string` - User email address
90
+ - `password: string` - User password
91
+ - `displayName: string` - User display name
92
+
93
+ **Rules**:
94
+ - MUST validate email format before calling
95
+ - MUST validate password meets requirements
96
+ - MUST validate display name not empty
97
+ - MUST handle loading state during call
98
+ - MUST display error messages on failure
99
+ - MUST NOT proceed if email already exists
100
+
101
+ **Constraints**:
102
+ - Email must be unique in Firebase Auth
103
+ - Password must meet complexity requirements
104
+ - Creates Firebase Auth user
105
+ - Creates user document in Firestore
106
+ - Auto-signs in after successful creation
107
+ - Sends email verification (if enabled)
108
+
109
+ ---
110
+
111
+ ### signOut
112
+
113
+ **Purpose**: Sign out current user and clear auth state.
114
+
115
+ **Parameters**: None
116
+
117
+ **Rules**:
118
+ - MUST confirm with user before signing out
119
+ - MUST handle loading state during call
120
+ - MUST clear local user data after sign out
121
+ - MUST navigate to login screen after sign out
122
+ - MUST handle errors gracefully
123
+
124
+ **Constraints**:
125
+ - Clears Firebase Auth session
126
+ - Resets auth store state
127
+ - Anonymous users: Loses all data
128
+ - Authenticated users: Can sign back in
129
+ - No server-side data deletion
130
+
131
+ ---
132
+
133
+ ### continueAnonymously
134
+
135
+ **Purpose**: Create anonymous user session without credentials.
136
+
137
+ **Parameters**: None
138
+
139
+ **Rules**:
140
+ - MUST inform user about anonymous limitations
141
+ - MUST offer upgrade path to full account
142
+ - MUST handle loading state during call
143
+ - MUST display error messages on failure
144
+ - MUST NOT expose this as primary auth method
145
+
146
+ **Constraints**:
147
+ - Creates temporary Firebase Auth user
148
+ - No email/password required
149
+ - User ID persists until sign out
150
+ - Can be upgraded to full account
151
+ - Data lost if user signs out
152
+ - Limited functionality compared to registered users
153
+
154
+ ---
155
+
156
+ ## Error Handling
157
+
158
+ ### setError
159
+
160
+ **Purpose**: Manually set or clear auth error state.
243
161
 
244
- ## Important Notes
162
+ **Parameters**:
163
+ - `error: string | null` - Error message or null to clear
245
164
 
246
- 1. **initializeAuthListener()**: Must be called once in app root
247
- 2. **Centralized State**: All components share the same state via Zustand
248
- 3. **Error Handling**: Errors are automatically set in the `error` state
249
- 4. **Loading States**: `loading` is true during operations
165
+ **Rules**:
166
+ - MUST use user-friendly error messages
167
+ - MUST clear errors after successful operations
168
+ - MUST NOT expose technical error details
169
+ - MUST localize error messages
170
+
171
+ **Constraints**:
172
+ - Auto-cleared by auth operations
173
+ - Displays in UI components
174
+ - Overwrites previous error
175
+ - null clears current error
176
+
177
+ ---
178
+
179
+ ## Loading States
180
+
181
+ ### Strategy
182
+
183
+ **Purpose**: Proper loading state management for better UX.
184
+
185
+ **Rules**:
186
+ - MUST show loading indicator during `loading = true`
187
+ - MUST NOT block UI for authentication operations
188
+ - MUST disable buttons during operations
189
+ - MUST handle loading errors gracefully
190
+
191
+ **Constraints**:
192
+ - `loading` = true only during initial auth check
193
+ - Individual operations handle their own loading
194
+ - `isAuthReady` ensures initial check complete
195
+ - Operation loading is method-specific
196
+
197
+ ---
198
+
199
+ ## Anonymous Users
200
+
201
+ ### Strategy
202
+
203
+ **Purpose**: Support anonymous users who can upgrade to registered accounts.
204
+
205
+ **Rules**:
206
+ - MUST clearly indicate anonymous status
207
+ - MUST offer upgrade path
208
+ - MUST explain limitations
209
+ - MUST preserve data during upgrade
210
+
211
+ **Constraints**:
212
+ - Cannot access all features
213
+ - Data lost if sign out occurs
214
+ - Must upgrade to keep data
215
+ - Limited account settings
216
+ - No password recovery possible
217
+
218
+ **UPGRADE PROCESS**:
219
+ - User initiates account creation
220
+ - Link credentials to anonymous account
221
+ - Preserve existing user ID
222
+ - Migrate any existing data
223
+ - Seamless transition for user
224
+
225
+ ---
226
+
227
+ ## Security Requirements
228
+
229
+ ### Strategy
230
+
231
+ **Purpose**: Ensure secure authentication handling.
232
+
233
+ **Rules**:
234
+ - MUST NEVER log passwords or tokens
235
+ - MUST handle errors without exposing details
236
+ - MUST use secure storage for tokens
237
+ - MUST implement proper error handling
238
+ - MUST validate all inputs
239
+
240
+ **MUST NOT**:
241
+ - Store passwords in AsyncStorage
242
+ - Log auth responses with sensitive data
243
+ - Expose tokens in error messages
244
+ - Bypass Firebase security rules
245
+ - Disable Firebase security features
246
+
247
+ **Constraints**:
248
+ - Firebase manages token refresh
249
+ - Tokens stored securely by Firebase SDK
250
+ - App cannot access refresh tokens
251
+ - ID tokens available for API calls
252
+ - Session managed automatically
253
+
254
+ ---
255
+
256
+ ## Platform Support
257
+
258
+ ### Strategy
259
+
260
+ **Purpose**: Ensure consistent behavior across platforms.
261
+
262
+ **Constraints**:
263
+ - iOS: ✅ Fully supported
264
+ - Android: ✅ Fully supported
265
+ - Web: ✅ Fully supported
266
+
267
+ **PLATFORM-SPECIFIC**:
268
+ - Web: Requires proper Firebase config
269
+ - iOS: Requires Info.plist configuration
270
+ - Android: Requires google-services.json
271
+
272
+ ---
273
+
274
+ ## Integration Points
275
+
276
+ ### Firebase Integration
277
+
278
+ **Requirements**:
279
+ - Firebase Auth must be initialized
280
+ - Firestore must be initialized (for user documents)
281
+ - Firebase config must be provided
282
+ - Auth persistence enabled by default
283
+
284
+ **Firebase Dependencies**:
285
+ - `@react-native-firebase/app`
286
+ - `@react-native-firebase/auth`
287
+ - `@react-native-firebase/firestore`
288
+
289
+ ---
250
290
 
251
291
  ## Related Hooks
252
292
 
253
- - [`useAuthRequired`](./useAuthRequired.md) - For components requiring auth
254
- - [`useRequireAuth`](./useAuthRequired.md#userequireauth) - Route protection
255
- - [`useUserProfile`](./useUserProfile.md) - User profile data
293
+ - **`useUserProfile`** (`src/presentation/hooks/useUserProfile.ts`) - Display profile data
294
+ - **`useAuthRequired`** (`src/presentation/hooks/useAuthRequired.ts`) - Require auth for components
295
+ - **`useAccountManagement`** (`src/presentation/hooks/useAccountManagement.ts`) - Account operations
296
+
297
+ ## Related Stores
298
+
299
+ - **`authStore`** (`src/presentation/stores/authStore.ts`) - Auth state management