forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfirebase.ts
More file actions
365 lines (321 loc) · 9.91 KB
/
Copy pathfirebase.ts
File metadata and controls
365 lines (321 loc) · 9.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
import { initializeApp, getApps } from 'firebase/app';
import {
getAuth,
GoogleAuthProvider,
OAuthProvider,
signInWithPopup,
signOut,
onAuthStateChanged,
User,
} from 'firebase/auth';
import {
getMessaging,
getToken,
onMessage,
isSupported,
Messaging,
MessagePayload,
} from 'firebase/messaging';
// Firebase configuration from environment variables
const firebaseConfig = {
apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
measurementId: process.env.NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID,
};
export const isFirebaseAuthConfigured =
Boolean(
firebaseConfig.apiKey &&
firebaseConfig.authDomain &&
firebaseConfig.projectId &&
firebaseConfig.storageBucket &&
firebaseConfig.messagingSenderId &&
firebaseConfig.appId,
) &&
firebaseConfig.apiKey !== 'preview' &&
firebaseConfig.authDomain !== 'preview.local';
// Initialize Firebase (prevent multiple initializations)
const app =
typeof window === 'undefined' || !isFirebaseAuthConfigured
? null
: getApps().length === 0
? initializeApp(firebaseConfig)
: getApps()[0];
// Initialize Firebase Auth
export const auth = app ? getAuth(app) : (null as unknown as ReturnType<typeof getAuth>);
// Google Auth Provider
const googleProvider = new GoogleAuthProvider();
googleProvider.setCustomParameters({
prompt: 'select_account',
});
// Apple Auth Provider
const appleProvider = new OAuthProvider('apple.com');
appleProvider.addScope('email');
appleProvider.addScope('name');
/**
* Sign in with Google
*/
export const signInWithGoogle = async (): Promise<User | null> => {
try {
if (!isFirebaseAuthConfigured) {
throw Object.assign(new Error('Firebase sign-in is not configured'), {
code: 'auth/configuration-not-found',
});
}
if (!app) throw new Error('Firebase auth is only available in a browser');
const result = await signInWithPopup(auth, googleProvider);
return result.user;
} catch (error) {
console.error('Google sign-in error:', error);
throw error;
}
};
/**
* Sign in with Apple
*/
export const signInWithApple = async (): Promise<User | null> => {
try {
if (!isFirebaseAuthConfigured) {
throw Object.assign(new Error('Firebase sign-in is not configured'), {
code: 'auth/configuration-not-found',
});
}
if (!app) throw new Error('Firebase auth is only available in a browser');
const result = await signInWithPopup(auth, appleProvider);
return result.user;
} catch (error) {
console.error('Apple sign-in error:', error);
throw error;
}
};
/**
* Sign out the current user
*/
export const signOutUser = async (): Promise<void> => {
try {
if (!app) return;
await signOut(auth);
} catch (error) {
console.error('Sign out error:', error);
throw error;
}
};
/**
* Get the current user's ID token for API calls
* Always call this fresh before API requests (don't cache)
*/
export const getIdToken = async (): Promise<string | null> => {
const user = auth.currentUser;
if (!user) return null;
try {
// Force refresh if token is expired
const token = await user.getIdToken();
return token;
} catch (error) {
console.error('Get ID token error:', error);
return null;
}
};
/**
* Subscribe to auth state changes
*/
export const onAuthStateChange = (callback: (user: User | null) => void) => {
// No Firebase app means no session can exist, and that is an answer the
// subscriber is owed. Returning a bare unsubscribe emits nothing, so
// `AuthProvider` never leaves `loading`, `ProtectedRoute` renders its
// spinner forever, and the local preview build (`apiKey=preview`) boots to a
// blank page instead of the login screen it ships a message for.
if (!app) {
queueMicrotask(() => callback(null));
return () => {};
}
return onAuthStateChanged(auth, callback);
};
// ============================================
// Firebase Cloud Messaging (FCM) for Push Notifications
// ============================================
// VAPID key for web push
const VAPID_KEY = process.env.NEXT_PUBLIC_FIREBASE_VAPID_KEY;
// Cached messaging instance
let messagingInstance: Messaging | null = null;
/**
* Check if the browser supports Firebase Cloud Messaging
*/
export const isMessagingSupported = async (): Promise<boolean> => {
if (typeof window === 'undefined') return false;
try {
return await isSupported();
} catch {
return false;
}
};
/**
* Get the Firebase Messaging instance (lazy initialization)
* Returns null if messaging is not supported
*/
export const getMessagingInstance = async (): Promise<Messaging | null> => {
if (typeof window === 'undefined') return null;
if (messagingInstance) return messagingInstance;
const supported = await isMessagingSupported();
if (!supported) {
console.warn('Firebase Messaging is not supported in this browser');
return null;
}
try {
if (!app) return null;
messagingInstance = getMessaging(app);
return messagingInstance;
} catch (error) {
console.error('Failed to initialize Firebase Messaging:', error);
return null;
}
};
/**
* Register the service worker for FCM and wait for it to be active
*/
const registerServiceWorker = async (): Promise<ServiceWorkerRegistration | null> => {
if (typeof window === 'undefined' || !('serviceWorker' in navigator)) {
return null;
}
try {
const registration = await navigator.serviceWorker.register(
'/firebase-messaging-sw.js',
);
// Wait for the service worker to be active
const installingWorker = registration.installing;
if (installingWorker) {
await new Promise<void>((resolve) => {
const handler = (e: Event) => {
if ((e.target as ServiceWorker).state === 'activated') {
installingWorker.removeEventListener('statechange', handler);
resolve();
}
};
installingWorker.addEventListener('statechange', handler);
});
} else {
const waitingWorker = registration.waiting;
if (waitingWorker) {
await new Promise<void>((resolve) => {
const handler = (e: Event) => {
if ((e.target as ServiceWorker).state === 'activated') {
waitingWorker.removeEventListener('statechange', handler);
resolve();
}
};
waitingWorker.addEventListener('statechange', handler);
});
}
}
// Also ensure the service worker is ready
await navigator.serviceWorker.ready;
return registration;
} catch (error) {
console.error('Service Worker registration failed:', error);
return null;
}
};
/**
* Request notification permission and get FCM token
* @returns The FCM token if permission granted, null otherwise
*/
export const requestNotificationPermission = async (): Promise<string | null> => {
if (typeof window === 'undefined') return null;
// Check if notifications are supported
if (!('Notification' in window)) {
console.warn('This browser does not support notifications');
return null;
}
// Check if service workers are supported
if (!('serviceWorker' in navigator)) {
console.warn('Service workers are not supported');
return null;
}
// Register service worker FIRST (before calling getMessaging)
const swRegistration = await registerServiceWorker();
if (!swRegistration) return null;
// Request permission
const permission = await Notification.requestPermission();
if (permission !== 'granted') {
return null;
}
// Now get messaging instance (after SW is registered)
const messaging = await getMessagingInstance();
if (!messaging) return null;
// Get FCM token
try {
const token = await getToken(messaging, {
vapidKey: VAPID_KEY,
serviceWorkerRegistration: swRegistration,
});
if (token) {
return token;
} else {
return null;
}
} catch (error) {
console.error('Failed to get FCM token:', error);
return null;
}
};
/**
* Get the current FCM token without requesting permission
* Useful for checking if we already have a valid token
*/
export const getCurrentFCMToken = async (): Promise<string | null> => {
if (typeof window === 'undefined') return null;
// Check current permission status
if (Notification.permission !== 'granted') {
return null;
}
// Check if service workers are supported
if (!('serviceWorker' in navigator)) {
return null;
}
// Register service worker FIRST
const swRegistration = await registerServiceWorker();
if (!swRegistration) return null;
// Then get messaging instance
const messaging = await getMessagingInstance();
if (!messaging) return null;
try {
const token = await getToken(messaging, {
vapidKey: VAPID_KEY,
serviceWorkerRegistration: swRegistration,
});
return token || null;
} catch (error) {
console.error('Failed to get current FCM token:', error);
return null;
}
};
/**
* Subscribe to foreground messages
* These are messages received while the app is in focus
* @param callback Function to call when a message is received
* @returns Unsubscribe function
*/
export const onForegroundMessage = async (
callback: (payload: MessagePayload) => void,
): Promise<(() => void) | null> => {
const messaging = await getMessagingInstance();
if (!messaging) {
return null;
}
return onMessage(messaging, (payload) => {
callback(payload);
});
};
/**
* Get the current notification permission status
*/
export const getNotificationPermission = (): NotificationPermission | 'unsupported' => {
if (typeof window === 'undefined' || !('Notification' in window)) {
return 'unsupported';
}
return Notification.permission;
};
export default app;