@umituz/react-native-firebase 1.13.152 → 1.13.153

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@umituz/react-native-firebase",
3
- "version": "1.13.152",
3
+ "version": "1.13.153",
4
4
  "description": "Unified Firebase package for React Native apps - Auth and Firestore services using Firebase JS SDK (no native modules).",
5
5
  "main": "./src/index.ts",
6
6
  "types": "./src/index.ts",
package/src/auth/index.ts CHANGED
@@ -138,3 +138,36 @@ export {
138
138
  } from './infrastructure/services/password.service';
139
139
  export type { PasswordUpdateResult } from './infrastructure/services/password.service';
140
140
 
141
+ // Email/Password Authentication
142
+ export {
143
+ signInWithEmail,
144
+ signUpWithEmail,
145
+ signOut,
146
+ linkAnonymousWithEmail,
147
+ } from './infrastructure/services/email-auth.service';
148
+ export type {
149
+ EmailCredentials,
150
+ EmailAuthResult,
151
+ } from './infrastructure/services/email-auth.service';
152
+
153
+ // Auth Listener
154
+ export {
155
+ setupAuthListener,
156
+ } from './infrastructure/services/auth-listener.service';
157
+ export type {
158
+ AuthListenerConfig,
159
+ AuthListenerResult,
160
+ } from './infrastructure/services/auth-listener.service';
161
+
162
+ // User Document Service
163
+ export {
164
+ ensureUserDocument,
165
+ markUserDeleted,
166
+ configureUserDocumentService,
167
+ } from './infrastructure/services/user-document.service';
168
+ export type {
169
+ UserDocumentUser,
170
+ UserDocumentConfig,
171
+ UserDocumentExtras,
172
+ } from './infrastructure/services/user-document.types';
173
+
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Auth Listener Service
3
+ * Manages Firebase auth state listener with timeout protection
4
+ */
5
+
6
+ import { onIdTokenChanged, type User } from "firebase/auth";
7
+ import { getFirebaseAuth } from "../config/FirebaseAuthClient";
8
+ import type { Result } from "../../../domain/utils";
9
+ import { successResult, failureResultFrom } from "../../../domain/utils";
10
+
11
+ export interface AuthListenerConfig {
12
+ /**
13
+ * Timeout in milliseconds before marking as initialized
14
+ * @default 10000 (10 seconds)
15
+ */
16
+ timeout?: number;
17
+ /**
18
+ * Callback when auth state changes
19
+ */
20
+ onAuthStateChange?: (user: User | null) => void;
21
+ /**
22
+ * Callback when listener is initialized
23
+ */
24
+ onInitialized?: () => void;
25
+ }
26
+
27
+ export interface AuthListenerResult extends Result<() => void> {
28
+ unsubscribe?: () => void;
29
+ }
30
+
31
+ /**
32
+ * Setup Firebase auth listener with timeout protection
33
+ */
34
+ export function setupAuthListener(
35
+ config: AuthListenerConfig = {}
36
+ ): AuthListenerResult {
37
+ const auth = getFirebaseAuth();
38
+ if (!auth) {
39
+ return failureResultFrom("auth/not-ready", "Firebase Auth not initialized");
40
+ }
41
+
42
+ const {
43
+ timeout = 10000,
44
+ onAuthStateChange,
45
+ onInitialized,
46
+ } = config;
47
+
48
+ let hasTriggered = false;
49
+ let unsubscribe: (() => void) | null = null;
50
+
51
+ // Safety timeout
52
+ const timeoutId = setTimeout(() => {
53
+ if (!hasTriggered) {
54
+ console.warn(
55
+ "[AuthListener] Auth listener timeout - marking as initialized"
56
+ );
57
+ hasTriggered = true;
58
+ onInitialized?.();
59
+ }
60
+ }, timeout);
61
+
62
+ try {
63
+ unsubscribe = onIdTokenChanged(auth, (user) => {
64
+ if (!hasTriggered) {
65
+ hasTriggered = true;
66
+ clearTimeout(timeoutId);
67
+ onInitialized?.();
68
+ }
69
+ onAuthStateChange?.(user);
70
+ });
71
+
72
+ const cleanup = () => {
73
+ clearTimeout(timeoutId);
74
+ unsubscribe?.();
75
+ };
76
+
77
+ return {
78
+ success: true,
79
+ data: cleanup,
80
+ unsubscribe: cleanup,
81
+ };
82
+ } catch (error) {
83
+ clearTimeout(timeoutId);
84
+ const err = error instanceof Error ? error : new Error(String(error));
85
+ return failureResultFrom(
86
+ "auth/listener-failed",
87
+ err.message
88
+ );
89
+ }
90
+ }
@@ -0,0 +1,140 @@
1
+ /**
2
+ * Email/Password Authentication Service
3
+ * Handles email/password sign in, sign up, and account linking
4
+ */
5
+
6
+ import {
7
+ createUserWithEmailAndPassword,
8
+ signInWithEmailAndPassword,
9
+ signOut as firebaseSignOut,
10
+ updateProfile,
11
+ EmailAuthProvider,
12
+ linkWithCredential,
13
+ type User,
14
+ } from "firebase/auth";
15
+ import { getFirebaseAuth } from "../config/FirebaseAuthClient";
16
+ import { executeOperation, failureResultFrom, successResult, type Result } from "../../../domain/utils";
17
+
18
+ export interface EmailCredentials {
19
+ email: string;
20
+ password: string;
21
+ displayName?: string;
22
+ }
23
+
24
+ export type EmailAuthResult = Result<User>;
25
+
26
+ /**
27
+ * Sign in with email and password
28
+ */
29
+ export async function signInWithEmail(
30
+ email: string,
31
+ password: string
32
+ ): Promise<EmailAuthResult> {
33
+ const auth = getFirebaseAuth();
34
+ if (!auth) {
35
+ return failureResultFrom("auth/not-ready", "Firebase Auth not initialized");
36
+ }
37
+
38
+ try {
39
+ const userCredential = await signInWithEmailAndPassword(
40
+ auth,
41
+ email.trim(),
42
+ password
43
+ );
44
+ return { success: true, data: userCredential.user };
45
+ } catch (error) {
46
+ const err = error instanceof Error ? error : new Error(String(error));
47
+ const code = (err as any).code || "auth/unknown";
48
+ return { success: false, error: { code, message: err.message } };
49
+ }
50
+ }
51
+
52
+ /**
53
+ * Sign up with email and password
54
+ * Automatically links with anonymous account if one exists
55
+ */
56
+ export async function signUpWithEmail(
57
+ credentials: EmailCredentials
58
+ ): Promise<EmailAuthResult> {
59
+ const auth = getFirebaseAuth();
60
+ if (!auth) {
61
+ return failureResultFrom("auth/not-ready", "Firebase Auth not initialized");
62
+ }
63
+
64
+ try {
65
+ const currentUser = auth.currentUser;
66
+ const isAnonymous = currentUser?.isAnonymous ?? false;
67
+ let userCredential;
68
+
69
+ if (currentUser && isAnonymous) {
70
+ // Link anonymous account with email
71
+ const credential = EmailAuthProvider.credential(
72
+ credentials.email.trim(),
73
+ credentials.password
74
+ );
75
+ userCredential = await linkWithCredential(currentUser, credential);
76
+ } else {
77
+ // Create new account
78
+ userCredential = await createUserWithEmailAndPassword(
79
+ auth,
80
+ credentials.email.trim(),
81
+ credentials.password
82
+ );
83
+ }
84
+
85
+ // Update display name if provided
86
+ if (credentials.displayName && userCredential.user) {
87
+ await updateProfile(userCredential.user, {
88
+ displayName: credentials.displayName.trim(),
89
+ });
90
+ }
91
+
92
+ return { success: true, data: userCredential.user };
93
+ } catch (error) {
94
+ const err = error instanceof Error ? error : new Error(String(error));
95
+ const code = (err as any).code || "auth/unknown";
96
+ return { success: false, error: { code, message: err.message } };
97
+ }
98
+ }
99
+
100
+ /**
101
+ * Sign out current user
102
+ */
103
+ export async function signOut(): Promise<Result<void>> {
104
+ const auth = getFirebaseAuth();
105
+ if (!auth) {
106
+ return successResult();
107
+ }
108
+
109
+ return executeOperation(async () => {
110
+ await firebaseSignOut(auth);
111
+ });
112
+ }
113
+
114
+ /**
115
+ * Link anonymous account with email/password
116
+ */
117
+ export async function linkAnonymousWithEmail(
118
+ email: string,
119
+ password: string
120
+ ): Promise<EmailAuthResult> {
121
+ const auth = getFirebaseAuth();
122
+ if (!auth || !auth.currentUser) {
123
+ return failureResultFrom("auth/not-ready", "No current user");
124
+ }
125
+
126
+ const currentUser = auth.currentUser;
127
+ if (!currentUser.isAnonymous) {
128
+ return failureResultFrom("auth/invalid-action", "User is not anonymous");
129
+ }
130
+
131
+ try {
132
+ const credential = EmailAuthProvider.credential(email.trim(), password);
133
+ const userCredential = await linkWithCredential(currentUser, credential);
134
+ return { success: true, data: userCredential.user };
135
+ } catch (error) {
136
+ const err = error instanceof Error ? error : new Error(String(error));
137
+ const code = (err as any).code || "auth/unknown";
138
+ return { success: false, error: { code, message: err.message } };
139
+ }
140
+ }
@@ -0,0 +1,110 @@
1
+ /**
2
+ * User Document Builder Utility
3
+ * Builds user document data for Firestore (max 100 lines)
4
+ */
5
+
6
+ import { serverTimestamp } from "firebase/firestore";
7
+ import type {
8
+ UserDocumentUser,
9
+ UserDocumentExtras,
10
+ } from "./user-document.types";
11
+
12
+ /**
13
+ * Gets the sign-up method from user provider data
14
+ */
15
+ export function getSignUpMethod(user: UserDocumentUser): string | undefined {
16
+ if (user.isAnonymous) return "anonymous";
17
+ if (user.email) {
18
+ const providerData = (
19
+ user as unknown as { providerData?: { providerId: string }[] }
20
+ ).providerData;
21
+ if (providerData && providerData.length > 0) {
22
+ const providerId = providerData[0]?.providerId;
23
+ if (providerId === "google.com") return "google";
24
+ if (providerId === "apple.com") return "apple";
25
+ if (providerId === "password") return "email";
26
+ }
27
+ return "email";
28
+ }
29
+ return undefined;
30
+ }
31
+
32
+ /**
33
+ * Builds base user data from user object and extras
34
+ */
35
+ export function buildBaseData(
36
+ user: UserDocumentUser,
37
+ extras?: UserDocumentExtras,
38
+ ): Record<string, unknown> {
39
+ const data: Record<string, unknown> = {
40
+ uid: user.uid,
41
+ displayName: user.displayName,
42
+ email: user.email,
43
+ photoURL: user.photoURL,
44
+ isAnonymous: user.isAnonymous,
45
+ };
46
+
47
+ if (extras) {
48
+ const internalFields = ["signUpMethod", "previousAnonymousUserId"];
49
+ Object.keys(extras).forEach((key) => {
50
+ if (!internalFields.includes(key)) {
51
+ const val = extras[key];
52
+ if (val !== undefined) {
53
+ data[key] = val;
54
+ }
55
+ }
56
+ });
57
+ }
58
+
59
+ return data;
60
+ }
61
+
62
+ /**
63
+ * Builds user document data for creation
64
+ */
65
+ export function buildCreateData(
66
+ baseData: Record<string, unknown>,
67
+ extraFields: Record<string, unknown> | undefined,
68
+ extras?: UserDocumentExtras,
69
+ ): Record<string, unknown> {
70
+ const createData: Record<string, unknown> = {
71
+ ...baseData,
72
+ ...extraFields,
73
+ createdAt: serverTimestamp(),
74
+ updatedAt: serverTimestamp(),
75
+ lastLoginAt: serverTimestamp(),
76
+ };
77
+
78
+ if (extras?.previousAnonymousUserId) {
79
+ createData.previousAnonymousUserId = extras.previousAnonymousUserId;
80
+ createData.convertedFromAnonymous = true;
81
+ createData.convertedAt = serverTimestamp();
82
+ }
83
+
84
+ if (extras?.signUpMethod) createData.signUpMethod = extras.signUpMethod;
85
+
86
+ return createData;
87
+ }
88
+
89
+ /**
90
+ * Builds user document data for update
91
+ */
92
+ export function buildUpdateData(
93
+ baseData: Record<string, unknown>,
94
+ extras?: UserDocumentExtras,
95
+ ): Record<string, unknown> {
96
+ const updateData: Record<string, unknown> = {
97
+ ...baseData,
98
+ lastLoginAt: serverTimestamp(),
99
+ updatedAt: serverTimestamp(),
100
+ };
101
+
102
+ if (extras?.previousAnonymousUserId) {
103
+ updateData.previousAnonymousUserId = extras.previousAnonymousUserId;
104
+ updateData.convertedFromAnonymous = true;
105
+ updateData.convertedAt = serverTimestamp();
106
+ if (extras?.signUpMethod) updateData.signUpMethod = extras.signUpMethod;
107
+ }
108
+
109
+ return updateData;
110
+ }
@@ -0,0 +1,85 @@
1
+ /**
2
+ * User Document Service
3
+ * Generic service for creating/updating user documents in Firestore
4
+ */
5
+
6
+ import { doc, getDoc, setDoc, serverTimestamp } from "firebase/firestore";
7
+ import type { User } from "firebase/auth";
8
+ import { getFirestore } from "../../../firestore";
9
+ import type {
10
+ UserDocumentUser,
11
+ UserDocumentConfig,
12
+ UserDocumentExtras,
13
+ } from "./user-document.types";
14
+ import {
15
+ getSignUpMethod,
16
+ buildBaseData,
17
+ buildCreateData,
18
+ buildUpdateData,
19
+ } from "./user-document-builder.util";
20
+
21
+ export type {
22
+ UserDocumentUser,
23
+ UserDocumentConfig,
24
+ UserDocumentExtras,
25
+ } from "./user-document.types";
26
+
27
+ declare const __DEV__: boolean;
28
+
29
+ let userDocumentConfig: UserDocumentConfig = {};
30
+
31
+ export function configureUserDocumentService(config: UserDocumentConfig): void {
32
+ userDocumentConfig = { ...config };
33
+ }
34
+
35
+ export async function ensureUserDocument(
36
+ user: UserDocumentUser | User,
37
+ extras?: UserDocumentExtras,
38
+ ): Promise<boolean> {
39
+ const db = getFirestore();
40
+ if (!db || !user.uid) return false;
41
+
42
+ try {
43
+ let allExtras = extras || {};
44
+ if (userDocumentConfig.collectExtras) {
45
+ const collectedExtras = await userDocumentConfig.collectExtras();
46
+ allExtras = { ...collectedExtras, ...allExtras };
47
+ }
48
+
49
+ if (!allExtras.signUpMethod) allExtras.signUpMethod = getSignUpMethod(user);
50
+
51
+ const collectionName = userDocumentConfig.collectionName || "users";
52
+ const userRef = doc(db, collectionName, user.uid);
53
+ const userDoc = await getDoc(userRef);
54
+ const baseData = buildBaseData(user, allExtras);
55
+
56
+ const docData = !userDoc.exists()
57
+ ? buildCreateData(baseData, userDocumentConfig.extraFields, allExtras)
58
+ : buildUpdateData(baseData, allExtras);
59
+
60
+ await setDoc(userRef, docData, { merge: true });
61
+ return true;
62
+ } catch (error) {
63
+ if (typeof __DEV__ !== "undefined" && __DEV__) {
64
+ console.error("[UserDocumentService] Failed:", error);
65
+ }
66
+ return false;
67
+ }
68
+ }
69
+
70
+ export async function markUserDeleted(userId: string): Promise<boolean> {
71
+ const db = getFirestore();
72
+ if (!db || !userId) return false;
73
+
74
+ try {
75
+ const userRef = doc(db, userDocumentConfig.collectionName || "users", userId);
76
+ await setDoc(userRef, {
77
+ isDeleted: true,
78
+ deletedAt: serverTimestamp(),
79
+ updatedAt: serverTimestamp(),
80
+ }, { merge: true });
81
+ return true;
82
+ } catch {
83
+ return false;
84
+ }
85
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * User Document Types and Configuration
3
+ */
4
+
5
+ /**
6
+ * Minimal user interface for document creation
7
+ * Compatible with both Firebase User and AuthUser
8
+ */
9
+ export interface UserDocumentUser {
10
+ uid: string;
11
+ displayName?: string | null;
12
+ email?: string | null;
13
+ photoURL?: string | null;
14
+ isAnonymous?: boolean;
15
+ }
16
+
17
+ /**
18
+ * Configuration for user document service
19
+ */
20
+ export interface UserDocumentConfig {
21
+ /** Firestore collection name (default: "users") */
22
+ collectionName?: string;
23
+ /** Additional fields to store with user document */
24
+ extraFields?: Record<string, unknown>;
25
+ /** Callback to collect device/app info */
26
+ collectExtras?: () => Promise<UserDocumentExtras>;
27
+ }
28
+
29
+ /**
30
+ * User document extras from device/app
31
+ */
32
+ export interface UserDocumentExtras {
33
+ [key: string]: string | number | boolean | null | undefined;
34
+ deviceId?: string;
35
+ persistentDeviceId?: string;
36
+ nativeDeviceId?: string;
37
+ platform?: string;
38
+ deviceModel?: string;
39
+ deviceBrand?: string;
40
+ deviceName?: string;
41
+ deviceType?: number | string;
42
+ deviceYearClass?: number | string;
43
+ isDevice?: boolean;
44
+ osName?: string;
45
+ osVersion?: string;
46
+ osBuildId?: string;
47
+ totalMemory?: number | string;
48
+ appVersion?: string;
49
+ buildNumber?: string;
50
+ locale?: string;
51
+ region?: string;
52
+ timezone?: string;
53
+ screenWidth?: number;
54
+ screenHeight?: number;
55
+ screenScale?: number;
56
+ fontScale?: number;
57
+ isLandscape?: boolean;
58
+ previousAnonymousUserId?: string;
59
+ signUpMethod?: string;
60
+ }