Skip to content

Commit 8355a49

Browse files
committed
allow local dev without firebase
1 parent 007d128 commit 8355a49

5 files changed

Lines changed: 88 additions & 84 deletions

File tree

‎apps/codingcatdev/src/lib/client/firebase.ts‎

Lines changed: 31 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,45 @@
11
import { toastStore } from '@codingcatdev/blackcatui';
22
import { initializeApp, getApps, FirebaseError } from 'firebase/app';
3-
import { getAuth, setPersistence, browserSessionPersistence, signInWithEmailAndPassword, signInWithPopup, type AuthProvider, GoogleAuthProvider } from 'firebase/auth';
4-
import { getFirestore, collection, doc, addDoc, onSnapshot } from 'firebase/firestore';
5-
import { httpsCallable, getFunctions } from 'firebase/functions';
3+
import { getAuth, setPersistence, browserSessionPersistence, signInWithEmailAndPassword, signInWithPopup, type AuthProvider, type Auth } from 'firebase/auth';
4+
import { getFirestore, collection, doc, addDoc, onSnapshot, Firestore } from 'firebase/firestore';
5+
import { httpsCallable, getFunctions, type Functions } from 'firebase/functions';
66

7-
import {
8-
PUBLIC_FB_API_KEY,
9-
PUBLIC_FB_AUTH_DOMAIN,
10-
PUBLIC_FB_PROJECT_ID,
11-
PUBLIC_FB_STORAGE_BUCKET,
12-
PUBLIC_FB_MESSAGE_SENDER_ID,
13-
PUBLIC_FB_APP_ID,
14-
PUBLIC_FB_MEASUREMENT_ID
15-
} from '$env/static/public';
7+
import { env } from '$env/dynamic/public';
168

179
const firebaseConfig = {
18-
apiKey: PUBLIC_FB_API_KEY,
19-
authDomain: PUBLIC_FB_AUTH_DOMAIN,
20-
projectId: PUBLIC_FB_PROJECT_ID,
21-
storageBucket: PUBLIC_FB_STORAGE_BUCKET,
22-
messagingSenderId: PUBLIC_FB_MESSAGE_SENDER_ID,
23-
appId: PUBLIC_FB_APP_ID,
24-
measurementId: PUBLIC_FB_MEASUREMENT_ID
10+
apiKey: env.PUBLIC_FB_API_KEY,
11+
authDomain: env.PUBLIC_FB_AUTH_DOMAIN,
12+
projectId: env.PUBLIC_FB_PROJECT_ID,
13+
storageBucket: env.PUBLIC_FB_STORAGE_BUCKET,
14+
messagingSenderId: env.PUBLIC_FB_MESSAGE_SENDER_ID,
15+
appId: env.PUBLIC_FB_APP_ID,
16+
measurementId: env.PUBLIC_FB_MEASUREMENT_ID
2517
};
2618

27-
export let app = getApps().at(0);
28-
if (!app) {
19+
let app = getApps().at(0);
20+
let auth: Auth;
21+
let db: Firestore;
22+
let functions: Functions;
23+
24+
if (!app &&
25+
firebaseConfig.apiKey &&
26+
firebaseConfig.authDomain &&
27+
firebaseConfig.projectId &&
28+
firebaseConfig.storageBucket &&
29+
firebaseConfig.messagingSenderId &&
30+
firebaseConfig.appId &&
31+
firebaseConfig.measurementId) {
32+
2933
app = initializeApp(firebaseConfig);
34+
35+
auth = getAuth(app);
36+
// As httpOnly cookies are to be used, do not persist any state client side.
37+
setPersistence(auth, browserSessionPersistence);
38+
db = getFirestore(app);
39+
functions = getFunctions(app);
3040
}
3141

3242
/* AUTH */
33-
export const auth = getAuth(app);
34-
// As httpOnly cookies are to be used, do not persist any state client side.
35-
setPersistence(auth, browserSessionPersistence);
3643

3744
const setCookie = (idToken: string) => {
3845
document.cookie = '__ccdlogin=' + idToken + ';max-age=3600';
@@ -70,7 +77,6 @@ export const ccdSignInWithPopUp = async (provider: AuthProvider) => {
7077
}
7178

7279
/* DB */
73-
export const db = getFirestore(app);
7480

7581
/* STRIPE */
7682
export const addSubscription = async (price: string, uid: string) => {
@@ -96,8 +102,6 @@ export const addSubscription = async (price: string, uid: string) => {
96102
};
97103

98104
/* FUNCTIONS */
99-
export const functions = getFunctions(app);
100-
101105
export const openStripePortal = async () => {
102106
const functionRef = httpsCallable(functions, 'ext-firestore-stripe-payments-createPortalLink');
103107
const { data } = await functionRef({

‎apps/codingcatdev/src/lib/server/content.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,9 @@ const LIMIT = 20;
88
// Will show for vercel previews unless forced to false
99
export const preview = env.PREVIEW === "false" ? false : env.VERCEL_ENV === "preview" || import.meta.env.DEV;
1010

11+
// While developing locally this allows you to see pages without setting up firebase.
12+
export const allowLocal = env.PREVIEW === "false" ? false : import.meta.env.DEV;
13+
1114
export const parseModules = async (modules: Record<string, () => Promise<unknown>>) => {
1215
const contentList: Content[] = [];
1316
for (const path in modules) {

‎apps/codingcatdev/src/lib/server/firebase.ts‎

Lines changed: 45 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,32 @@
11
import { initializeApp, getApps, cert } from 'firebase-admin/app';
2-
import { getAuth } from 'firebase-admin/auth';
3-
import { getFirestore } from 'firebase-admin/firestore';
2+
import { Auth, getAuth } from 'firebase-admin/auth';
3+
import { Firestore, getFirestore } from 'firebase-admin/firestore';
44

55
import {
6-
PUBLIC_FB_PROJECT_ID,
7-
} from '$env/static/public';
6+
env as publicEnv,
7+
} from '$env/dynamic/public';
88

9-
import {
10-
PRIVATE_FB_CLIENT_EMAIL,
11-
PRIVATE_FB_PRIVATE_KEY
12-
} from '$env/static/private';
9+
import { env as privateEnv } from '$env/dynamic/private';
1310

1411
export let app = getApps().at(0);
15-
if (!app) {
12+
13+
let auth: Auth;
14+
let db: Firestore;
15+
16+
if (!app && publicEnv.PUBLIC_FB_PROJECT_ID && privateEnv.PRIVATE_FB_CLIENT_EMAIL && privateEnv.PRIVATE_FB_PRIVATE_KEY) {
1617
app = initializeApp({
1718
credential: cert({
18-
projectId: PUBLIC_FB_PROJECT_ID,
19-
clientEmail: PRIVATE_FB_CLIENT_EMAIL,
20-
privateKey: PRIVATE_FB_PRIVATE_KEY
19+
projectId: publicEnv.PUBLIC_FB_PROJECT_ID,
20+
clientEmail: privateEnv.PRIVATE_FB_CLIENT_EMAIL,
21+
privateKey: privateEnv.PRIVATE_FB_PRIVATE_KEY
2122
})
2223
});
24+
25+
auth = getAuth(app);
26+
db = getFirestore(app);
2327
}
2428

25-
export const auth = getAuth(app);
26-
export const db = getFirestore(app);
29+
/* AUTH */
2730

2831
export const ccdCreateSessionCookie = async (idToken: string) => {
2932
// Set session expiration to 5 days.
@@ -47,4 +50,32 @@ export const ccdValidateSessionCookie = async (session: string) => {
4750
export const validateStripeRole = async (uid: string) => {
4851
const user = await auth.getUser(uid);
4952
return user.customClaims?.['stripeRole']
53+
}
54+
55+
export const isAdmin = async (uid: string) => {
56+
// Check if user is admin
57+
const doc = await db.collection('admins').doc(uid).get();
58+
return doc.exists;
59+
}
60+
61+
/* DB */
62+
63+
export const getStripeProducts = async () => {
64+
const products: any = [];
65+
if (!db) return products;
66+
67+
const snapshot = await db.collection('stripe-products').where('active', '==', true).get();
68+
69+
for (const doc of snapshot.docs) {
70+
const priceSnapshot = await doc.ref.collection('prices').where('active', '==', true).get();
71+
72+
for (const price of priceSnapshot.docs) {
73+
products.push({
74+
id: doc.id,
75+
...doc.data(),
76+
price: price.id
77+
})
78+
}
79+
}
80+
return products;
5081
}

‎apps/codingcatdev/src/routes/(content-single)/course/[slug]/lesson/[lessonSlug]/+page.server.ts‎

Lines changed: 5 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
1-
import { env } from '$env/dynamic/private';
2-
import { getLessonFromCourseSlug } from '$lib/server/content';
3-
import { db } from '$lib/server/firebase';
1+
import { allowLocal, getLessonFromCourseSlug } from '$lib/server/content';
2+
import { getStripeProducts, isAdmin } from '$lib/server/firebase';
43
import { ContentType } from '$lib/types';
54
import { error, redirect } from '@sveltejs/kit';
65

@@ -17,40 +16,21 @@ export const load = (async ({ params, parent, url }) => {
1716
});
1817
}
1918

20-
if (content.locked) {
19+
if (!allowLocal && content.locked) {
2120
// Locked but needs to be logged in
2221
if (!user?.uid) {
2322
throw redirect(307, `/login?redirectTo=${url.pathname}`);
2423
}
2524

26-
// Check if user is admin
27-
const doc = await db.collection('admins').doc(user.uid).get();
28-
const isAdmin = doc.exists;
29-
3025
// User should have stripeRole or be admin
31-
if (user?.stripeRole || isAdmin) {
26+
if (user?.stripeRole || await isAdmin(user.uid)) {
3227
return {
3328
contentType,
3429
content
3530
};
3631
} else {
37-
const snapshot = await db.collection('stripe-products').where('active', '==', true).get();
38-
const products = [];
39-
40-
for (const doc of snapshot.docs) {
41-
const priceSnapshot = await doc.ref.collection('prices').where('active', '==', true).get();
42-
43-
for (const price of priceSnapshot.docs) {
44-
products.push({
45-
id: doc.id,
46-
...doc.data(),
47-
price: price.id
48-
})
49-
}
50-
}
51-
5232
return {
53-
products,
33+
products: await getStripeProducts(),
5434
locked: content?.locked,
5535
title: content?.title
5636
};
Lines changed: 4 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,14 @@
1-
import { db } from '$lib/server/firebase';
1+
import { allowLocal } from '$lib/server/content';
2+
import { getStripeProducts } from '$lib/server/firebase';
23
import { redirect } from '@sveltejs/kit';
34

45
export const load = (async ({ url, parent }) => {
56
const data = await parent();
6-
if (!data?.user?.uid) {
7+
if (!allowLocal && !data?.user?.uid) {
78
throw redirect(307, `/login?redirectTo=${url.pathname}`);
89
}
9-
10-
const snapshot = await db.collection('stripe-products').where('active', '==', true).get();
11-
const products = [];
12-
13-
for (const doc of snapshot.docs) {
14-
const priceSnapshot = await doc.ref.collection('prices').where('active', '==', true).get();
15-
16-
for (const price of priceSnapshot.docs) {
17-
products.push({
18-
id: doc.id,
19-
...doc.data(),
20-
price: price.id
21-
})
22-
}
23-
}
2410
return {
25-
products
11+
products: await getStripeProducts()
2612
};
2713

2814
});

0 commit comments

Comments
 (0)