@umituz/react-native-auth 3.6.74 → 3.6.76
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.
- package/package.json +4 -2
- package/src/infrastructure/providers/FirebaseAuthProvider.ts +17 -68
- package/src/infrastructure/services/AuthService.ts +1 -8
- package/src/presentation/hooks/useAuth.ts +5 -48
- package/src/presentation/hooks/useGoogleAuth.ts +12 -46
- package/src/presentation/utils/authOperation.util.ts +67 -0
- package/src/presentation/utils/form/formValidation.util.ts +9 -65
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@umituz/react-native-auth",
|
|
3
|
-
"version": "3.6.
|
|
3
|
+
"version": "3.6.76",
|
|
4
4
|
"description": "Authentication service for React Native apps - Secure, type-safe, and production-ready. Provider-agnostic design with dependency injection, configurable validation, and comprehensive error handling.",
|
|
5
5
|
"main": "./src/index.ts",
|
|
6
6
|
"types": "./src/index.ts",
|
|
@@ -93,7 +93,9 @@
|
|
|
93
93
|
"react-native-safe-area-context": "^5.6.2",
|
|
94
94
|
"react-native-svg": "^15.15.1",
|
|
95
95
|
"typescript": "^5.3.0",
|
|
96
|
-
"zustand": "^4.0.0"
|
|
96
|
+
"zustand": "^4.0.0",
|
|
97
|
+
"@react-native-community/datetimepicker": "^8.2.0",
|
|
98
|
+
"rn-emoji-keyboard": "^1.7.0"
|
|
97
99
|
},
|
|
98
100
|
"publishConfig": {
|
|
99
101
|
"access": "public"
|
|
@@ -13,12 +13,7 @@ import {
|
|
|
13
13
|
linkWithCredential,
|
|
14
14
|
type Auth,
|
|
15
15
|
} from "firebase/auth";
|
|
16
|
-
|
|
17
|
-
import type {
|
|
18
|
-
IAuthProvider,
|
|
19
|
-
AuthCredentials,
|
|
20
|
-
SignUpCredentials,
|
|
21
|
-
} from "../../application/ports/IAuthProvider";
|
|
16
|
+
import type { IAuthProvider, AuthCredentials, SignUpCredentials } from "../../application/ports/IAuthProvider";
|
|
22
17
|
import type { AuthUser } from "../../domain/entities/AuthUser";
|
|
23
18
|
import { mapFirebaseAuthError } from "../utils/AuthErrorMapper";
|
|
24
19
|
import { mapToAuthUser } from "../utils/UserMapper";
|
|
@@ -27,15 +22,11 @@ export class FirebaseAuthProvider implements IAuthProvider {
|
|
|
27
22
|
private auth: Auth | null = null;
|
|
28
23
|
|
|
29
24
|
constructor(auth?: Auth) {
|
|
30
|
-
if (auth)
|
|
31
|
-
this.auth = auth;
|
|
32
|
-
}
|
|
25
|
+
if (auth) this.auth = auth;
|
|
33
26
|
}
|
|
34
27
|
|
|
35
28
|
initialize(): Promise<void> {
|
|
36
|
-
if (!this.auth)
|
|
37
|
-
throw new Error("Firebase Auth instance must be provided");
|
|
38
|
-
}
|
|
29
|
+
if (!this.auth) throw new Error("Firebase Auth instance must be provided");
|
|
39
30
|
return Promise.resolve();
|
|
40
31
|
}
|
|
41
32
|
|
|
@@ -48,20 +39,12 @@ export class FirebaseAuthProvider implements IAuthProvider {
|
|
|
48
39
|
}
|
|
49
40
|
|
|
50
41
|
async signIn(credentials: AuthCredentials): Promise<AuthUser> {
|
|
51
|
-
if (!this.auth)
|
|
52
|
-
throw new Error("Firebase Auth is not initialized");
|
|
53
|
-
}
|
|
42
|
+
if (!this.auth) throw new Error("Firebase Auth is not initialized");
|
|
54
43
|
|
|
55
44
|
try {
|
|
56
|
-
const userCredential = await signInWithEmailAndPassword(
|
|
57
|
-
this.auth,
|
|
58
|
-
credentials.email.trim(),
|
|
59
|
-
credentials.password
|
|
60
|
-
);
|
|
45
|
+
const userCredential = await signInWithEmailAndPassword(this.auth, credentials.email.trim(), credentials.password);
|
|
61
46
|
const user = mapToAuthUser(userCredential.user);
|
|
62
|
-
if (!user)
|
|
63
|
-
throw new Error("Failed to sign in");
|
|
64
|
-
}
|
|
47
|
+
if (!user) throw new Error("Failed to sign in");
|
|
65
48
|
return user;
|
|
66
49
|
} catch (error: unknown) {
|
|
67
50
|
throw mapFirebaseAuthError(error);
|
|
@@ -69,55 +52,31 @@ export class FirebaseAuthProvider implements IAuthProvider {
|
|
|
69
52
|
}
|
|
70
53
|
|
|
71
54
|
async signUp(credentials: SignUpCredentials): Promise<AuthUser> {
|
|
72
|
-
if (!this.auth)
|
|
73
|
-
throw new Error("Firebase Auth is not initialized");
|
|
74
|
-
}
|
|
55
|
+
if (!this.auth) throw new Error("Firebase Auth is not initialized");
|
|
75
56
|
|
|
76
57
|
try {
|
|
77
58
|
const currentUser = this.auth.currentUser;
|
|
78
59
|
const isAnonymous = currentUser?.isAnonymous ?? false;
|
|
79
|
-
|
|
80
60
|
let userCredential;
|
|
81
61
|
|
|
82
|
-
// Convert anonymous user to permanent account
|
|
83
62
|
if (currentUser && isAnonymous) {
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
await currentUser.reload();
|
|
87
|
-
} catch {
|
|
88
|
-
// Reload failed, proceed with link anyway
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
const credential = EmailAuthProvider.credential(
|
|
92
|
-
credentials.email.trim(),
|
|
93
|
-
credentials.password
|
|
94
|
-
);
|
|
95
|
-
|
|
63
|
+
try { await currentUser.reload(); } catch { /* Reload failed, proceed */ }
|
|
64
|
+
const credential = EmailAuthProvider.credential(credentials.email.trim(), credentials.password);
|
|
96
65
|
userCredential = await linkWithCredential(currentUser, credential);
|
|
97
66
|
} else {
|
|
98
|
-
|
|
99
|
-
userCredential = await createUserWithEmailAndPassword(
|
|
100
|
-
this.auth,
|
|
101
|
-
credentials.email.trim(),
|
|
102
|
-
credentials.password
|
|
103
|
-
);
|
|
67
|
+
userCredential = await createUserWithEmailAndPassword(this.auth, credentials.email.trim(), credentials.password);
|
|
104
68
|
}
|
|
105
69
|
|
|
106
70
|
if (credentials.displayName && userCredential.user) {
|
|
107
71
|
try {
|
|
108
|
-
await updateProfile(userCredential.user, {
|
|
109
|
-
displayName: credentials.displayName.trim(),
|
|
110
|
-
});
|
|
72
|
+
await updateProfile(userCredential.user, { displayName: credentials.displayName.trim() });
|
|
111
73
|
} catch {
|
|
112
|
-
|
|
113
|
-
// only the display name update failed. User can update it later.
|
|
74
|
+
/* Display name update failed, account created successfully */
|
|
114
75
|
}
|
|
115
76
|
}
|
|
116
77
|
|
|
117
78
|
const user = mapToAuthUser(userCredential.user);
|
|
118
|
-
if (!user)
|
|
119
|
-
throw new Error("Failed to create user account");
|
|
120
|
-
}
|
|
79
|
+
if (!user) throw new Error("Failed to create user account");
|
|
121
80
|
return user;
|
|
122
81
|
} catch (error: unknown) {
|
|
123
82
|
throw mapFirebaseAuthError(error);
|
|
@@ -125,10 +84,7 @@ export class FirebaseAuthProvider implements IAuthProvider {
|
|
|
125
84
|
}
|
|
126
85
|
|
|
127
86
|
async signOut(): Promise<void> {
|
|
128
|
-
if (!this.auth)
|
|
129
|
-
return;
|
|
130
|
-
}
|
|
131
|
-
|
|
87
|
+
if (!this.auth) return;
|
|
132
88
|
try {
|
|
133
89
|
await firebaseSignOut(this.auth);
|
|
134
90
|
} catch (error: unknown) {
|
|
@@ -137,13 +93,9 @@ export class FirebaseAuthProvider implements IAuthProvider {
|
|
|
137
93
|
}
|
|
138
94
|
|
|
139
95
|
getCurrentUser(): AuthUser | null {
|
|
140
|
-
if (!this.auth)
|
|
141
|
-
return null;
|
|
142
|
-
}
|
|
96
|
+
if (!this.auth) return null;
|
|
143
97
|
const currentUser = this.auth.currentUser;
|
|
144
|
-
if (!currentUser)
|
|
145
|
-
return null;
|
|
146
|
-
}
|
|
98
|
+
if (!currentUser) return null;
|
|
147
99
|
return mapToAuthUser(currentUser);
|
|
148
100
|
}
|
|
149
101
|
|
|
@@ -152,9 +104,6 @@ export class FirebaseAuthProvider implements IAuthProvider {
|
|
|
152
104
|
callback(null);
|
|
153
105
|
return () => {};
|
|
154
106
|
}
|
|
155
|
-
|
|
156
|
-
return onAuthStateChanged(this.auth, (user) => {
|
|
157
|
-
callback(mapToAuthUser(user));
|
|
158
|
-
});
|
|
107
|
+
return onAuthStateChanged(this.auth, (user) => callback(mapToAuthUser(user)));
|
|
159
108
|
}
|
|
160
109
|
}
|
|
@@ -23,9 +23,7 @@ export class AuthService {
|
|
|
23
23
|
private config: AuthConfig;
|
|
24
24
|
|
|
25
25
|
constructor(config: Partial<AuthConfig> = {}, storageProvider?: IStorageProvider) {
|
|
26
|
-
// Validate and sanitize configuration
|
|
27
26
|
this.config = sanitizeAuthConfig(config);
|
|
28
|
-
|
|
29
27
|
this.anonymousModeService = new AnonymousModeService();
|
|
30
28
|
this.storageProvider = storageProvider;
|
|
31
29
|
}
|
|
@@ -87,17 +85,12 @@ export class AuthService {
|
|
|
87
85
|
}
|
|
88
86
|
|
|
89
87
|
async setAnonymousMode(): Promise<void> {
|
|
90
|
-
if (!this.storageProvider)
|
|
91
|
-
throw new Error("Storage provider is required for anonymous mode");
|
|
92
|
-
}
|
|
88
|
+
if (!this.storageProvider) throw new Error("Storage provider is required for anonymous mode");
|
|
93
89
|
await this.anonymousModeService.enable(this.storageProvider);
|
|
94
90
|
}
|
|
95
91
|
|
|
96
92
|
getCurrentUser(): AuthUser | null {
|
|
97
93
|
if (!this.initialized) return null;
|
|
98
|
-
// Return the actual Firebase user regardless of anonymous mode
|
|
99
|
-
// The caller should check the user's isAnonymous property if needed
|
|
100
|
-
// This ensures proper anonymous to registered user conversion
|
|
101
94
|
return this.repositoryInstance.getCurrentUser();
|
|
102
95
|
}
|
|
103
96
|
|
|
@@ -1,9 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* useAuth Hook
|
|
3
3
|
* React hook for authentication state management
|
|
4
|
-
*
|
|
5
|
-
* Uses centralized Zustand store for auth state.
|
|
6
|
-
* Single source of truth - no duplicate subscriptions.
|
|
7
4
|
*/
|
|
8
5
|
|
|
9
6
|
import { useCallback } from "react";
|
|
@@ -32,44 +29,23 @@ import {
|
|
|
32
29
|
import type { AuthUser } from "../../domain/entities/AuthUser";
|
|
33
30
|
|
|
34
31
|
export interface UseAuthResult {
|
|
35
|
-
/** Current authenticated user */
|
|
36
32
|
user: AuthUser | null;
|
|
37
|
-
/** Current user ID (uid) */
|
|
38
33
|
userId: string | null;
|
|
39
|
-
/** Current user type */
|
|
40
34
|
userType: UserType;
|
|
41
|
-
/** Whether auth state is loading */
|
|
42
35
|
loading: boolean;
|
|
43
|
-
/** Whether auth is ready (initialized and not loading) */
|
|
44
36
|
isAuthReady: boolean;
|
|
45
|
-
/** Whether user is anonymous */
|
|
46
37
|
isAnonymous: boolean;
|
|
47
|
-
/** Whether user is authenticated (not anonymous) */
|
|
48
38
|
isAuthenticated: boolean;
|
|
49
|
-
/** Whether user is a registered user (authenticated AND not anonymous) */
|
|
50
39
|
isRegisteredUser: boolean;
|
|
51
|
-
/** Current error message */
|
|
52
40
|
error: string | null;
|
|
53
|
-
/** Sign up function */
|
|
54
41
|
signUp: (email: string, password: string, displayName?: string) => Promise<void>;
|
|
55
|
-
/** Sign in function */
|
|
56
42
|
signIn: (email: string, password: string) => Promise<void>;
|
|
57
|
-
/** Sign out function */
|
|
58
43
|
signOut: () => Promise<void>;
|
|
59
|
-
/** Continue anonymously function */
|
|
60
44
|
continueAnonymously: () => Promise<void>;
|
|
61
|
-
/** Set error manually (for form validation, etc.) */
|
|
62
45
|
setError: (error: string | null) => void;
|
|
63
46
|
}
|
|
64
47
|
|
|
65
|
-
/**
|
|
66
|
-
* Hook for authentication state management
|
|
67
|
-
*
|
|
68
|
-
* Uses centralized Zustand store - all components share the same state.
|
|
69
|
-
* Must call initializeAuthListener() once in app root.
|
|
70
|
-
*/
|
|
71
48
|
export function useAuth(): UseAuthResult {
|
|
72
|
-
// State from store - using typed selectors
|
|
73
49
|
const user = useAuthStore(selectUser);
|
|
74
50
|
const loading = useAuthStore(selectLoading);
|
|
75
51
|
const error = useAuthStore(selectError);
|
|
@@ -79,13 +55,10 @@ export function useAuth(): UseAuthResult {
|
|
|
79
55
|
const isAnonymous = useAuthStore(selectIsAnonymous);
|
|
80
56
|
const isAuthReady = useAuthStore(selectIsAuthReady);
|
|
81
57
|
const isRegisteredUser = useAuthStore(selectIsRegisteredUser);
|
|
82
|
-
|
|
83
|
-
// Actions from store - using typed selectors
|
|
84
58
|
const setLoading = useAuthStore(selectSetLoading);
|
|
85
59
|
const setError = useAuthStore(selectSetError);
|
|
86
60
|
const setIsAnonymous = useAuthStore(selectSetIsAnonymous);
|
|
87
61
|
|
|
88
|
-
// Mutations
|
|
89
62
|
const signInMutation = useSignInMutation();
|
|
90
63
|
const signUpMutation = useSignUpMutation();
|
|
91
64
|
const signOutMutation = useSignOutMutation();
|
|
@@ -99,8 +72,7 @@ export function useAuth(): UseAuthResult {
|
|
|
99
72
|
await signUpMutation.mutateAsync({ email, password, displayName });
|
|
100
73
|
setIsAnonymous(false);
|
|
101
74
|
} catch (err: unknown) {
|
|
102
|
-
|
|
103
|
-
setError(errorMessage);
|
|
75
|
+
setError(err instanceof Error ? err.message : "Sign up failed");
|
|
104
76
|
throw err;
|
|
105
77
|
} finally {
|
|
106
78
|
setLoading(false);
|
|
@@ -117,8 +89,7 @@ export function useAuth(): UseAuthResult {
|
|
|
117
89
|
await signInMutation.mutateAsync({ email, password });
|
|
118
90
|
setIsAnonymous(false);
|
|
119
91
|
} catch (err: unknown) {
|
|
120
|
-
|
|
121
|
-
setError(errorMessage);
|
|
92
|
+
setError(err instanceof Error ? err.message : "Sign in failed");
|
|
122
93
|
throw err;
|
|
123
94
|
} finally {
|
|
124
95
|
setLoading(false);
|
|
@@ -133,8 +104,7 @@ export function useAuth(): UseAuthResult {
|
|
|
133
104
|
setError(null);
|
|
134
105
|
await signOutMutation.mutateAsync();
|
|
135
106
|
} catch (err: unknown) {
|
|
136
|
-
|
|
137
|
-
setError(errorMessage);
|
|
107
|
+
setError(err instanceof Error ? err.message : "Sign out failed");
|
|
138
108
|
throw err;
|
|
139
109
|
} finally {
|
|
140
110
|
setLoading(false);
|
|
@@ -147,7 +117,6 @@ export function useAuth(): UseAuthResult {
|
|
|
147
117
|
await anonymousModeMutation.mutateAsync();
|
|
148
118
|
setIsAnonymous(true);
|
|
149
119
|
} catch {
|
|
150
|
-
// Silently fail - anonymous mode is optional
|
|
151
120
|
setIsAnonymous(true);
|
|
152
121
|
} finally {
|
|
153
122
|
setLoading(false);
|
|
@@ -155,19 +124,7 @@ export function useAuth(): UseAuthResult {
|
|
|
155
124
|
}, [setIsAnonymous, setLoading, anonymousModeMutation]);
|
|
156
125
|
|
|
157
126
|
return {
|
|
158
|
-
user,
|
|
159
|
-
|
|
160
|
-
userType,
|
|
161
|
-
loading,
|
|
162
|
-
isAuthReady,
|
|
163
|
-
isAnonymous,
|
|
164
|
-
isAuthenticated,
|
|
165
|
-
isRegisteredUser,
|
|
166
|
-
error,
|
|
167
|
-
signUp,
|
|
168
|
-
signIn,
|
|
169
|
-
signOut,
|
|
170
|
-
continueAnonymously,
|
|
171
|
-
setError,
|
|
127
|
+
user, userId, userType, loading, isAuthReady, isAnonymous, isAuthenticated, isRegisteredUser, error,
|
|
128
|
+
signUp, signIn, signOut, continueAnonymously, setError,
|
|
172
129
|
};
|
|
173
130
|
}
|
|
@@ -1,19 +1,10 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* useGoogleAuth Hook
|
|
3
3
|
* Handles Google OAuth flow using expo-auth-session and Firebase auth
|
|
4
|
-
*
|
|
5
|
-
* This hook provides complete Google sign-in flow:
|
|
6
|
-
* 1. OAuth flow via expo-auth-session
|
|
7
|
-
* 2. Firebase authentication with the obtained token
|
|
8
4
|
*/
|
|
9
5
|
|
|
10
6
|
import { useState, useCallback, useEffect } from "react";
|
|
11
|
-
import {
|
|
12
|
-
useSocialAuth,
|
|
13
|
-
type SocialAuthConfig,
|
|
14
|
-
type SocialAuthResult,
|
|
15
|
-
} from "@umituz/react-native-firebase";
|
|
16
|
-
|
|
7
|
+
import { useSocialAuth, type SocialAuthConfig, type SocialAuthResult } from "@umituz/react-native-firebase";
|
|
17
8
|
import * as Google from "expo-auth-session/providers/google";
|
|
18
9
|
import * as WebBrowser from "expo-web-browser";
|
|
19
10
|
|
|
@@ -34,38 +25,25 @@ export interface UseGoogleAuthResult {
|
|
|
34
25
|
|
|
35
26
|
const PLACEHOLDER_CLIENT_ID = "000000000000-placeholder.apps.googleusercontent.com";
|
|
36
27
|
|
|
37
|
-
/**
|
|
38
|
-
* Validate Google auth config
|
|
39
|
-
*/
|
|
40
28
|
function validateGoogleConfig(config?: GoogleAuthConfig): boolean {
|
|
41
29
|
if (!config) return false;
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
return hasValidClientId;
|
|
30
|
+
return !!(
|
|
31
|
+
(config.iosClientId && config.iosClientId !== PLACEHOLDER_CLIENT_ID) ||
|
|
32
|
+
(config.webClientId && config.webClientId !== PLACEHOLDER_CLIENT_ID) ||
|
|
33
|
+
(config.androidClientId && config.androidClientId !== PLACEHOLDER_CLIENT_ID)
|
|
34
|
+
);
|
|
49
35
|
}
|
|
50
36
|
|
|
51
|
-
/**
|
|
52
|
-
* Hook for Google authentication with expo-auth-session
|
|
53
|
-
*/
|
|
54
37
|
export function useGoogleAuth(config?: GoogleAuthConfig): UseGoogleAuthResult {
|
|
55
38
|
const [isLoading, setIsLoading] = useState(false);
|
|
56
39
|
const [googleError, setGoogleError] = useState<string | null>(null);
|
|
57
|
-
|
|
58
40
|
const googleConfigured = validateGoogleConfig(config);
|
|
59
41
|
|
|
60
|
-
const
|
|
42
|
+
const { signInWithGoogleToken, googleLoading: firebaseLoading } = useSocialAuth({
|
|
61
43
|
google: config,
|
|
62
44
|
apple: { enabled: false },
|
|
63
|
-
};
|
|
64
|
-
|
|
65
|
-
const { signInWithGoogleToken, googleLoading: firebaseLoading } =
|
|
66
|
-
useSocialAuth(socialAuthConfig);
|
|
45
|
+
} as SocialAuthConfig);
|
|
67
46
|
|
|
68
|
-
// Use Google auth request if available
|
|
69
47
|
const authRequest = Google?.useAuthRequest({
|
|
70
48
|
iosClientId: config?.iosClientId || PLACEHOLDER_CLIENT_ID,
|
|
71
49
|
webClientId: config?.webClientId || PLACEHOLDER_CLIENT_ID,
|
|
@@ -76,7 +54,6 @@ export function useGoogleAuth(config?: GoogleAuthConfig): UseGoogleAuthResult {
|
|
|
76
54
|
const googleResponse = authRequest?.[1] ?? null;
|
|
77
55
|
const promptGoogleAsync = authRequest?.[2];
|
|
78
56
|
|
|
79
|
-
// Handle Google OAuth response
|
|
80
57
|
useEffect(() => {
|
|
81
58
|
if (googleResponse?.type === "success") {
|
|
82
59
|
const idToken = googleResponse.authentication?.idToken;
|
|
@@ -84,13 +61,8 @@ export function useGoogleAuth(config?: GoogleAuthConfig): UseGoogleAuthResult {
|
|
|
84
61
|
setIsLoading(true);
|
|
85
62
|
setGoogleError(null);
|
|
86
63
|
signInWithGoogleToken(idToken)
|
|
87
|
-
.catch((error) => {
|
|
88
|
-
|
|
89
|
-
setGoogleError(errorMessage);
|
|
90
|
-
})
|
|
91
|
-
.finally(() => {
|
|
92
|
-
setIsLoading(false);
|
|
93
|
-
});
|
|
64
|
+
.catch((error) => { setGoogleError(error instanceof Error ? error.message : "Firebase sign-in failed"); })
|
|
65
|
+
.finally(() => { setIsLoading(false); });
|
|
94
66
|
}
|
|
95
67
|
} else if (googleResponse?.type === "error") {
|
|
96
68
|
setGoogleError("Google authentication failed");
|
|
@@ -123,10 +95,7 @@ export function useGoogleAuth(config?: GoogleAuthConfig): UseGoogleAuthResult {
|
|
|
123
95
|
const result = await promptGoogleAsync();
|
|
124
96
|
|
|
125
97
|
if (result.type === "success" && result.authentication?.idToken) {
|
|
126
|
-
|
|
127
|
-
result.authentication.idToken,
|
|
128
|
-
);
|
|
129
|
-
return firebaseResult;
|
|
98
|
+
return await signInWithGoogleToken(result.authentication.idToken);
|
|
130
99
|
}
|
|
131
100
|
|
|
132
101
|
if (result.type === "cancel") {
|
|
@@ -141,10 +110,7 @@ export function useGoogleAuth(config?: GoogleAuthConfig): UseGoogleAuthResult {
|
|
|
141
110
|
} catch (error) {
|
|
142
111
|
const errorMessage = error instanceof Error ? error.message : "Google sign-in failed";
|
|
143
112
|
setGoogleError(errorMessage);
|
|
144
|
-
return {
|
|
145
|
-
success: false,
|
|
146
|
-
error: errorMessage,
|
|
147
|
-
};
|
|
113
|
+
return { success: false, error: errorMessage };
|
|
148
114
|
} finally {
|
|
149
115
|
setIsLoading(false);
|
|
150
116
|
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Auth Operation Utilities
|
|
3
|
+
* Shared error handling for authentication operations
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { useCallback } from "react";
|
|
7
|
+
|
|
8
|
+
export interface AuthOperationOptions {
|
|
9
|
+
setLoading: (loading: boolean) => void;
|
|
10
|
+
setError: (error: string | null) => void;
|
|
11
|
+
onSuccess?: () => void;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Create an auth operation wrapper with consistent error handling
|
|
16
|
+
*/
|
|
17
|
+
export function createAuthOperation<T>(
|
|
18
|
+
mutation: (params: T) => Promise<unknown>,
|
|
19
|
+
options: AuthOperationOptions
|
|
20
|
+
) {
|
|
21
|
+
const { setLoading, setError, onSuccess } = options;
|
|
22
|
+
|
|
23
|
+
return useCallback(
|
|
24
|
+
async (params: T) => {
|
|
25
|
+
try {
|
|
26
|
+
setLoading(true);
|
|
27
|
+
setError(null);
|
|
28
|
+
await mutation(params);
|
|
29
|
+
onSuccess?.();
|
|
30
|
+
} catch (err: unknown) {
|
|
31
|
+
const errorMessage = err instanceof Error ? err.message : "Operation failed";
|
|
32
|
+
setError(errorMessage);
|
|
33
|
+
throw err;
|
|
34
|
+
} finally {
|
|
35
|
+
setLoading(false);
|
|
36
|
+
}
|
|
37
|
+
},
|
|
38
|
+
[setLoading, setError, onSuccess, mutation]
|
|
39
|
+
);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Create auth operation that doesn't throw on failure
|
|
44
|
+
*/
|
|
45
|
+
export function createSilentAuthOperation<T>(
|
|
46
|
+
mutation: (params: T) => Promise<unknown>,
|
|
47
|
+
options: AuthOperationOptions
|
|
48
|
+
) {
|
|
49
|
+
const { setLoading, setError, onSuccess } = options;
|
|
50
|
+
|
|
51
|
+
return useCallback(
|
|
52
|
+
async (params?: T) => {
|
|
53
|
+
try {
|
|
54
|
+
setLoading(true);
|
|
55
|
+
setError(null);
|
|
56
|
+
await mutation(params as T);
|
|
57
|
+
onSuccess?.();
|
|
58
|
+
} catch {
|
|
59
|
+
// Silently fail
|
|
60
|
+
onSuccess?.();
|
|
61
|
+
} finally {
|
|
62
|
+
setLoading(false);
|
|
63
|
+
}
|
|
64
|
+
},
|
|
65
|
+
[setLoading, setError, onSuccess, mutation]
|
|
66
|
+
);
|
|
67
|
+
}
|
|
@@ -39,16 +39,7 @@ export interface ProfileFormValues {
|
|
|
39
39
|
email: string;
|
|
40
40
|
}
|
|
41
41
|
|
|
42
|
-
|
|
43
|
-
* Validate login form fields
|
|
44
|
-
* @param values - Form values to validate
|
|
45
|
-
* @param getErrorMessage - Function to get localized error messages
|
|
46
|
-
* @returns Validation result
|
|
47
|
-
*/
|
|
48
|
-
export function validateLoginForm(
|
|
49
|
-
values: LoginFormValues,
|
|
50
|
-
getErrorMessage: (key: string) => string
|
|
51
|
-
): FormValidationResult {
|
|
42
|
+
export function validateLoginForm(values: LoginFormValues, getErrorMessage: (key: string) => string): FormValidationResult {
|
|
52
43
|
const errors: FormValidationError[] = [];
|
|
53
44
|
|
|
54
45
|
const emailResult = validateEmail(values.email.trim());
|
|
@@ -61,19 +52,9 @@ export function validateLoginForm(
|
|
|
61
52
|
errors.push({ field: "password", message: getErrorMessage(passwordResult.error) });
|
|
62
53
|
}
|
|
63
54
|
|
|
64
|
-
return {
|
|
65
|
-
isValid: errors.length === 0,
|
|
66
|
-
errors,
|
|
67
|
-
};
|
|
55
|
+
return { isValid: errors.length === 0, errors };
|
|
68
56
|
}
|
|
69
57
|
|
|
70
|
-
/**
|
|
71
|
-
* Validate register form fields
|
|
72
|
-
* @param values - Form values to validate
|
|
73
|
-
* @param getErrorMessage - Function to get localized error messages
|
|
74
|
-
* @param passwordConfig - Password configuration
|
|
75
|
-
* @returns Validation result
|
|
76
|
-
*/
|
|
77
58
|
export function validateRegisterForm(
|
|
78
59
|
values: RegisterFormValues,
|
|
79
60
|
getErrorMessage: (key: string) => string,
|
|
@@ -96,17 +77,9 @@ export function validateRegisterForm(
|
|
|
96
77
|
errors.push({ field: "confirmPassword", message: getErrorMessage(confirmResult.error) });
|
|
97
78
|
}
|
|
98
79
|
|
|
99
|
-
return {
|
|
100
|
-
isValid: errors.length === 0,
|
|
101
|
-
errors,
|
|
102
|
-
};
|
|
80
|
+
return { isValid: errors.length === 0, errors };
|
|
103
81
|
}
|
|
104
82
|
|
|
105
|
-
/**
|
|
106
|
-
* Validate profile form fields
|
|
107
|
-
* @param values - Form values to validate
|
|
108
|
-
* @returns Validation result
|
|
109
|
-
*/
|
|
110
83
|
export function validateProfileForm(values: ProfileFormValues): FormValidationResult {
|
|
111
84
|
const errors: FormValidationError[] = [];
|
|
112
85
|
|
|
@@ -121,20 +94,10 @@ export function validateProfileForm(values: ProfileFormValues): FormValidationRe
|
|
|
121
94
|
}
|
|
122
95
|
}
|
|
123
96
|
|
|
124
|
-
return {
|
|
125
|
-
isValid: errors.length === 0,
|
|
126
|
-
errors,
|
|
127
|
-
};
|
|
97
|
+
return { isValid: errors.length === 0, errors };
|
|
128
98
|
}
|
|
129
99
|
|
|
130
|
-
|
|
131
|
-
* Convert validation errors to field error object
|
|
132
|
-
* @param errors - Validation errors
|
|
133
|
-
* @returns Object mapping field names to error messages
|
|
134
|
-
*/
|
|
135
|
-
export function errorsToFieldErrors(
|
|
136
|
-
errors: FormValidationError[]
|
|
137
|
-
): Record<string, string> {
|
|
100
|
+
export function errorsToFieldErrors(errors: FormValidationError[]): Record<string, string> {
|
|
138
101
|
const result: Record<string, string> = {};
|
|
139
102
|
for (const error of errors) {
|
|
140
103
|
result[error.field] = error.message;
|
|
@@ -142,32 +105,13 @@ export function errorsToFieldErrors(
|
|
|
142
105
|
return result;
|
|
143
106
|
}
|
|
144
107
|
|
|
145
|
-
/**
|
|
146
|
-
* Hook for form validation with error message resolution
|
|
147
|
-
* @param getErrorMessage - Function to get localized error messages
|
|
148
|
-
* @returns Validation functions
|
|
149
|
-
*/
|
|
150
108
|
export function useFormValidation(getErrorMessage: (key: string) => string) {
|
|
151
|
-
const validateLogin = useCallback(
|
|
152
|
-
(values: LoginFormValues) => validateLoginForm(values, getErrorMessage),
|
|
153
|
-
[getErrorMessage]
|
|
154
|
-
);
|
|
155
|
-
|
|
109
|
+
const validateLogin = useCallback((values: LoginFormValues) => validateLoginForm(values, getErrorMessage), [getErrorMessage]);
|
|
156
110
|
const validateRegister = useCallback(
|
|
157
|
-
(values: RegisterFormValues, passwordConfig: PasswordConfig) =>
|
|
158
|
-
validateRegisterForm(values, getErrorMessage, passwordConfig),
|
|
111
|
+
(values: RegisterFormValues, passwordConfig: PasswordConfig) => validateRegisterForm(values, getErrorMessage, passwordConfig),
|
|
159
112
|
[getErrorMessage]
|
|
160
113
|
);
|
|
114
|
+
const validateProfile = useCallback((values: ProfileFormValues) => validateProfileForm(values), []);
|
|
161
115
|
|
|
162
|
-
|
|
163
|
-
(values: ProfileFormValues) => validateProfileForm(values),
|
|
164
|
-
[]
|
|
165
|
-
);
|
|
166
|
-
|
|
167
|
-
return {
|
|
168
|
-
validateLogin,
|
|
169
|
-
validateRegister,
|
|
170
|
-
validateProfile,
|
|
171
|
-
errorsToFieldErrors,
|
|
172
|
-
};
|
|
116
|
+
return { validateLogin, validateRegister, validateProfile, errorsToFieldErrors };
|
|
173
117
|
}
|