forked from CodingCatDev/codingcat.dev
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfirebase.ts
More file actions
143 lines (125 loc) · 4.41 KB
/
firebase.ts
File metadata and controls
143 lines (125 loc) · 4.41 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
import { browser } from '$app/environment';
import { toastStore } from '@codingcatdev/blackcatui';
import { initializeApp, getApps, FirebaseError } from 'firebase/app';
import { getAuth, setPersistence, browserSessionPersistence, signInWithEmailAndPassword, signInWithPopup, type AuthProvider, type Auth, createUserWithEmailAndPassword } from 'firebase/auth';
import { getFirestore, collection, doc, addDoc, onSnapshot, Firestore } from 'firebase/firestore';
import { httpsCallable, getFunctions, type Functions } from 'firebase/functions';
import { getAnalytics, type Analytics, logEvent, type AnalyticsCallOptions } from "firebase/analytics";
import { env } from '$env/dynamic/public';
export const firebaseConfig = {
apiKey: env.PUBLIC_FB_API_KEY,
authDomain: env.PUBLIC_FB_AUTH_DOMAIN,
projectId: env.PUBLIC_FB_PROJECT_ID,
storageBucket: env.PUBLIC_FB_STORAGE_BUCKET,
messagingSenderId: env.PUBLIC_FB_MESSAGE_SENDER_ID,
appId: env.PUBLIC_FB_APP_ID,
measurementId: env.PUBLIC_FB_MEASUREMENT_ID
};
let app = getApps().at(0);
let auth: Auth;
let db: Firestore;
let functions: Functions;
let analytics: Analytics;
if (!app &&
browser &&
firebaseConfig.apiKey &&
firebaseConfig.authDomain &&
firebaseConfig.projectId &&
firebaseConfig.storageBucket &&
firebaseConfig.messagingSenderId &&
firebaseConfig.appId &&
firebaseConfig.measurementId) {
app = initializeApp(firebaseConfig);
auth = getAuth(app);
// As httpOnly cookies are to be used, do not persist any state client side.
setPersistence(auth, browserSessionPersistence);
db = getFirestore(app);
functions = getFunctions(app);
analytics = getAnalytics(app);
} else {
console.debug('Skipping Firebase Initialization, check firebaseconfig.')
}
/* AUTH */
const setCookie = (idToken: string) => {
document.cookie = '__ccdlogin=' + idToken + ';max-age=3600';
}
export const ccdSignInWithEmailAndPassword = async ({ email, password }: { email: string, password: string }) => {
const userResponse = await signInWithEmailAndPassword(auth, email, password);
const idToken = await userResponse.user.getIdToken();
setCookie(idToken);
}
export const ccdSignUpWithEmailAndPassword = async ({ email, password }: { email: string, password: string }) => {
const userCredential = await createUserWithEmailAndPassword(auth, email, password);
const idToken = await userCredential.user.getIdToken();
setCookie(idToken);
}
export const ccdSignInWithPopUp = async (provider: AuthProvider) => {
try {
const result = await signInWithPopup(auth, provider)
const idToken = await result.user.getIdToken()
if (!idToken)
throw 'Missing id Token'
setCookie(idToken);
} catch (err) {
if (err instanceof FirebaseError) {
if (err.code === 'auth/account-exists-with-different-credential') {
toastStore.trigger({
message: 'Account Exists with Different Login Method. Please first login and then link within your Account page.',
background: 'variant-filled-warning',
})
} else {
toastStore.trigger({
message: err.message,
background: 'variant-filled-error'
})
}
} else {
console.error(err);
}
}
}
/* DB */
/* STRIPE */
export const addSubscription = async (price: string, uid: string) => {
const userDoc = doc(collection(db, 'stripe-customers'), uid)
const docRef = await addDoc(collection(userDoc, 'checkout_sessions'), {
price,
success_url: window.location.href,
cancel_url: window.location.href,
})
onSnapshot(docRef, (snap) => {
const { error, url } = snap.data() as { error: Error, url: string };
if (error) {
toastStore.trigger({
message: error.message,
background: 'variant-filled-error'
})
}
if (url) {
// We have a Stripe Checkout URL, let's redirect.
window.location.assign(url);
}
});
};
/* FUNCTIONS */
export const openStripePortal = async () => {
const functionRef = httpsCallable(functions, 'ext-firestore-stripe-payments-createPortalLink');
const { data } = await functionRef({
returnUrl: window.location.href,
}) as { data: { url: string } };
window.location.assign(data.url);
}
/* Analytics */
export const analyticsLogPageView = async (eventParams?: {
page_title?: string;
page_location?: string;
page_path?: string;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
[key: string]: any;
}, options?: AnalyticsCallOptions) => {
if (firebaseConfig.apiKey) {
logEvent(analytics, "page_view", eventParams, options)
} else {
console.debug('Skipping Firebase Analytics, no key specified.')
}
}