GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Refactor user access checks and improve premium content handling · aidrivencoder/master-git-github@4fce455

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • src
    • components
      • premium
        • PremiumContent.tsx
      • providers
        • AuthProvider.tsx
    • lib
      • firebase
        • user.ts
      • hooks
        • useTutorialProgress.ts
    • types
      • user.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎src/components/premium/PremiumContent.tsx‎

Copy file name to clipboardExpand all lines: src/components/premium/PremiumContent.tsx
+27-3Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
import { useEffect, useState } from 'react'
44
import { useAuth } from '../providers/AuthProvider'
5-
import { checkPremiumAccess } from '@/lib/firebase/user'
5+
import { checkPremiumAccess } from '../../lib/firebase/user'
66
import Link from 'next/link'
77

88
interface PremiumContentProps {
@@ -14,13 +14,37 @@ export function PremiumContent({ children }: PremiumContentProps) {
1414
const [hasPremiumAccess, setHasPremiumAccess] = useState<boolean | null>(null)
1515

1616
useEffect(() => {
17+
let mounted = true;
18+
1719
async function checkAccess() {
1820
if (user) {
19-
const hasAccess = await checkPremiumAccess(user.id)
20-
setHasPremiumAccess(hasAccess)
21+
try {
22+
const hasAccess = await checkPremiumAccess(user.uid)
23+
if (mounted) {
24+
setHasPremiumAccess(hasAccess)
25+
}
26+
} catch (error) {
27+
console.error('Error checking premium access:', error)
28+
if (mounted) {
29+
setHasPremiumAccess(false)
30+
}
31+
}
32+
} else {
33+
if (mounted) {
34+
setHasPremiumAccess(false)
35+
}
2136
}
2237
}
38+
2339
checkAccess()
40+
41+
// Set up an interval to periodically check access
42+
const intervalId = setInterval(checkAccess, 5000)
43+
44+
return () => {
45+
mounted = false
46+
clearInterval(intervalId)
47+
}
2448
}, [user])
2549

2650
if (hasPremiumAccess === null) {
Collapse file

‎src/components/providers/AuthProvider.tsx‎

Copy file name to clipboardExpand all lines: src/components/providers/AuthProvider.tsx
+2-1Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
2929
const userData = userDoc.data()
3030
// Convert Firestore Timestamps to Dates
3131
const user: User = {
32+
uid: firebaseUser.uid,
3233
...userData,
3334
subscription: {
3435
...userData.subscription,
@@ -41,7 +42,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
4142
} else {
4243
// Fallback to basic user data if Firestore document doesn't exist
4344
const userData: User = {
44-
id: firebaseUser.uid,
45+
uid: firebaseUser.uid,
4546
email: firebaseUser.email || '',
4647
displayName: firebaseUser.displayName || '',
4748
photoURL: firebaseUser.photoURL || undefined,
Collapse file

‎src/lib/firebase/user.ts‎

Copy file name to clipboardExpand all lines: src/lib/firebase/user.ts
+43-7Lines changed: 43 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
import { updateProfile } from 'firebase/auth'
2-
import { doc, getDoc, setDoc, updateDoc } from 'firebase/firestore'
2+
import { doc, getDoc, setDoc, updateDoc, collection } from 'firebase/firestore'
33
import { auth, db } from './config'
44
import { Logger } from '../utils/logger'
5-
import { User } from '@/types/user'
5+
import { User } from '../../types/user'
66

77
async function createStripeCustomer(email: string) {
88
try {
@@ -29,15 +29,51 @@ async function createStripeCustomer(email: string) {
2929

3030
export async function checkPremiumAccess(userId: string): Promise<boolean> {
3131
try {
32+
// First check the user document
3233
const userRef = doc(db, 'users', userId);
3334
const userDoc = await getDoc(userRef);
34-
35+
3536
if (!userDoc.exists()) {
37+
Logger.info(`User document not found for ID: ${userId}`, 'PremiumAccess');
38+
return false;
39+
}
40+
41+
// Then check the subscriptions collection
42+
const subscriptionRef = doc(db, 'subscriptions', userId);
43+
const subscriptionDoc = await getDoc(subscriptionRef);
44+
45+
if (!subscriptionDoc.exists()) {
46+
Logger.info(`Subscription document not found for user ID: ${userId}`, 'PremiumAccess');
3647
return false;
3748
}
3849

39-
const userData = userDoc.data() as User;
40-
return userData.subscription.tier === 'premium';
50+
const subscriptionData = subscriptionDoc.data();
51+
console.log('subscriptionData', subscriptionData)
52+
const now = new Date();
53+
54+
// Log subscription data for debugging
55+
const subscriptionInfo = JSON.stringify({
56+
status: subscriptionData.status,
57+
planName: subscriptionData.plan?.name,
58+
currentPeriodEnd: subscriptionData.currentPeriod?.end?.toDate(),
59+
cancelAtPeriodEnd: subscriptionData.cancelAtPeriodEnd
60+
});
61+
Logger.info(`Checking subscription data: ${subscriptionInfo}`, 'PremiumAccess');
62+
63+
// Check if:
64+
// 1. Subscription is active
65+
// 2. Plan includes 'premium'
66+
// 3. Current period hasn't ended
67+
// 4. Not scheduled for cancellation at period end OR if it is, we're still within the current period
68+
const hasAccess = (
69+
subscriptionData.status === 'active' &&
70+
subscriptionData.plan?.name.toLowerCase().includes('premium') &&
71+
now <= subscriptionData.currentPeriod?.end?.toDate() &&
72+
(!subscriptionData.cancelAtPeriodEnd || now <= subscriptionData.currentPeriod?.end?.toDate())
73+
);
74+
75+
Logger.info(`Premium access result: ${hasAccess}`, 'PremiumAccess');
76+
return hasAccess;
4177
} catch (error) {
4278
Logger.error('Failed to check premium access', 'PremiumAccess', error);
4379
return false;
@@ -59,7 +95,7 @@ export async function createUserDocument(uid: string, email: string) {
5995

6096
// Create new user document with Stripe customer ID
6197
const userData: User = {
62-
id: uid,
98+
uid: uid,
6399
email,
64100
displayName: email.split('@')[0], // Default display name
65101
subscription: {
@@ -105,7 +141,7 @@ export async function updateUserDisplayName(displayName: string) {
105141
if (!userDoc.exists()) {
106142
// Create new user document
107143
const userData: User = {
108-
id: user.uid,
144+
uid: user.uid,
109145
email: user.email || '',
110146
displayName,
111147
subscription: {
Collapse file

‎src/lib/hooks/useTutorialProgress.ts‎

Copy file name to clipboardExpand all lines: src/lib/hooks/useTutorialProgress.ts
+3-3Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ export function useTutorialProgress(tutorialId: string) {
1212
useEffect(() => {
1313
if (!user) return
1414

15-
const progressRef = doc(db, 'progress', `${user.id}_${tutorialId}`)
15+
const progressRef = doc(db, 'progress', `${user.uid}_${tutorialId}`)
1616

1717
const unsubscribe = onSnapshot(progressRef, (doc) => {
1818
if (doc.exists()) {
@@ -30,7 +30,7 @@ export function useTutorialProgress(tutorialId: string) {
3030

3131
setLoading(true)
3232
try {
33-
const progressRef = doc(db, 'progress', `${user.id}_${tutorialId}`)
33+
const progressRef = doc(db, 'progress', `${user.uid}_${tutorialId}`)
3434
await updateDoc(progressRef, {
3535
currentStep: step,
3636
lastAccessed: serverTimestamp()
@@ -47,7 +47,7 @@ export function useTutorialProgress(tutorialId: string) {
4747

4848
setLoading(true)
4949
try {
50-
const progressRef = doc(db, 'progress', `${user.id}_${tutorialId}`)
50+
const progressRef = doc(db, 'progress', `${user.uid}_${tutorialId}`)
5151
await updateDoc(progressRef, {
5252
completedSteps: arrayUnion(stepId),
5353
lastAccessed: serverTimestamp()
Collapse file

‎src/types/user.ts‎

Copy file name to clipboardExpand all lines: src/types/user.ts
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { Achievement } from './achievement'
22

33
export interface User {
4-
id: string
4+
uid: string
55
email: string
66
displayName: string
77
photoURL?: string

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.