Skip to content

Commit

Permalink
auth flow working very well with stripe
Browse files Browse the repository at this point in the history
  • Loading branch information
sahil-lalani committed Sep 17, 2024
1 parent 3f48a00 commit 8043d30
Show file tree
Hide file tree
Showing 5 changed files with 89 additions and 66 deletions.
41 changes: 1 addition & 40 deletions src/main/utils/stripe.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,9 @@
'use client';
import { FirebaseApp } from 'firebase/app';
import { getAuth } from 'firebase/auth';
import {
addDoc,
collection,
getFirestore,
onSnapshot,
query,
where,
doc,
getDoc,
} from 'firebase/firestore';
import { getFunctions, httpsCallable } from 'firebase/functions';
import app from '../../firebase';
Expand Down Expand Up @@ -59,7 +53,7 @@ export const getCheckoutUrl = async (
});
};

export const getPortalUrl = async (app: FirebaseApp): Promise<string> => {
export const getPortalUrl = async (): Promise<string> => {
const auth = getAuth(app);
const user = auth.currentUser;

Expand Down Expand Up @@ -91,36 +85,3 @@ export const getPortalUrl = async (app: FirebaseApp): Promise<string> => {
});
};

export const getPremiumStatus = async (app: FirebaseApp) => {
const auth = getAuth(app);
const userId = auth.currentUser?.uid;
if (!userId) throw new Error('User not logged in');

const db = getFirestore(app);
const subscriptionsRef = collection(db, 'Users', userId, 'subscriptions');
console.log(subscriptionsRef)
const q = query(
subscriptionsRef,
where('status', 'in', ['trialing', 'active']),
);

const premiumStatus = await new Promise<boolean>((resolve, reject) => {
const unsubscribe = onSnapshot(
q,
(snapshot) => {
if (snapshot.docs.length === 0) {
resolve(false);
} else {
resolve(true);
}
unsubscribe();
},
reject,
);
});

console.log('premium status: ', premiumStatus)

return premiumStatus;
};

14 changes: 11 additions & 3 deletions src/renderer/components/subscribe/Checkout.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { getCheckoutUrl, getPremiumStatus } from '@/src/main/utils/stripe';
import Tumbler from '../../animations/tumbler.gif';
import { useAuth } from '../../auth/FirebaseAuth';

const Checkout = () => {
const Checkout = ({handleSignOut}) => {
const [stripeURL, setStripeURL] = useState(null);
const [isLoading, setIsLoading] = useState(true);
const { currentUser } = useAuth();
Expand All @@ -23,9 +23,17 @@ const Checkout = () => {
fetchStripeURL();
}, [currentUser]);


return (
<Card>
<Card className="relative">
<Button
onClick={handleSignOut}
variant="outline"
size="sm"
className="absolute top-2 right-2"
>
Sign Out
</Button>
<CardContent>
<CardHeader>
<CardTitle>Upgrade to Premium</CardTitle>
Expand Down
3 changes: 3 additions & 0 deletions src/renderer/components/subscribe/SubscribeCard.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,9 @@ const SubscribeCard = () => {
>
Subscribe
</Button>
<Button className='w-full' onClick={handleSubscribeClick}>
Sign back in
</Button>
{!isProduction && showTokenInput && (
<form onSubmit={handleTokenSubmit} className="w-full space-y-2">
<p>Enter your user token (sign in on website + look at console for token)</p>
Expand Down
36 changes: 29 additions & 7 deletions src/renderer/pages/Chat.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,22 +7,44 @@ import { ScrollArea } from "../../renderer/components/ui/scroll-area";
import { Badge } from "../../renderer/components/ui/badge";
import { setCurrentRoute, updateBreadcrumb } from '../state/actions';
import SubscribeCard from '../components/subscribe/SubscribeCard';
// Remove unused import
// import { VectorStorage } from 'vector-storage';
import { similaritySearch } from '../vector_db';
import { useAuth } from '../auth/FirebaseAuth';
import { getFirestore, collection, query, where, onSnapshot } from 'firebase/firestore';
import app from '../../firebase'

const Chat = () => {
const [messages, setMessages] = useState([]);
const [inputMessage, setInputMessage] = useState('');
const scrollAreaRef = useRef(null);
const dispatch = useDispatch();
const [isSubscribed, setIsSubscribed] = useState(false);
const { currentUser } = useAuth();


useEffect(() => {
if (!currentUser) {
dispatch(setCurrentRoute('/profile'))
return;
}

const db = getFirestore(app);
const subscriptionsRef = collection(db, 'Users', currentUser.uid, 'subscriptions');
const q = query(subscriptionsRef, where('status', 'in', ['trialing', 'active']));

const unsubscribe = onSnapshot(q, async (snapshot) => {
const isActive = snapshot.docs.length > 0;
console.log('isActive: ', isActive);
setIsSubscribed(isActive);
if (!isActive) {
dispatch(setCurrentRoute('/profile'))
}
}, (error) => {
console.error("Error listening to subscription changes:", error);
});

return () => unsubscribe();
}, [currentUser]);

useEffect(() => {
if (!isSubscribed) {
dispatch(setCurrentRoute('/profile'))
}
}, [dispatch, isSubscribed])

useEffect(() => {
if (scrollAreaRef.current) {
Expand Down
61 changes: 45 additions & 16 deletions src/renderer/pages/UserProfile.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,16 @@ import { Card, CardContent, CardHeader, CardTitle } from "../components/ui/card"
import SubscribeCard from '../components/subscribe/SubscribeCard';
import Checkout from '../components/subscribe/Checkout'; // Import the Checkout component
import { useAuth } from '../auth/FirebaseAuth'
import app from '../../firebase';
import app from '../../firebase';
import { getAuth } from 'firebase/auth';
import { getPremiumStatus } from '@/src/main/utils/stripe';
import { getFirestore, collection, query, where, onSnapshot } from 'firebase/firestore';
import { getPremiumStatus, getPortalUrl } from '@/src/main/utils/stripe';
import { getFirestore, collection, query, where, onSnapshot, getDocs } from 'firebase/firestore';

const UserProfile = () => {
const [isSubscribed, setIsSubscribed] = useState(false);
const [showCheckout, setShowCheckout] = useState(false);
const [isCancelled, setIsCancelled] = useState(false);
const [subscriptionEndDate, setSubscriptionEndDate] = useState(null);
const { currentUser } = useAuth();
const auth = getAuth(app);

Expand All @@ -22,27 +24,50 @@ const UserProfile = () => {
const subscriptionsRef = collection(db, 'Users', currentUser.uid, 'subscriptions');
const q = query(subscriptionsRef, where('status', 'in', ['trialing', 'active']));

const unsubscribe = onSnapshot(q, (snapshot) => {
setIsSubscribed(snapshot.docs.length > 0);
setShowCheckout(snapshot.docs.length === 0);
const unsubscribe = onSnapshot(q, async (snapshot) => {
const isActive = snapshot.docs.length > 0;
setIsSubscribed(isActive);
setShowCheckout(!isActive);

if (isActive) {
const cancelledQuery = query(subscriptionsRef, where('cancel_at_period_end', '==', true));
const cancelledDocs = await getDocs(cancelledQuery);
const isCancelled = cancelledDocs.docs.length > 0;
setIsCancelled(isCancelled);

if (isCancelled) {
const subscriptionData = cancelledDocs.docs[0].data();
const endDate = subscriptionData.current_period_end?.toDate();
setSubscriptionEndDate(endDate);
} else {
setSubscriptionEndDate(null);
}
} else {
setIsCancelled(false);
setSubscriptionEndDate(null);
}
}, (error) => {
console.error("Error listening to subscription changes:", error);
});

// Clean up the listener when the component unmounts or currentUser changes
return () => unsubscribe();
}, [currentUser]);


const handleCancelSubscription = async () => {
console.log('Cancel subscription');
const portalUrl = await getPortalUrl(app);
window.electron.ipcRenderer.send('open-external', portalUrl);
};

const handleSignOut = async () => {
setIsSubscribed(false);
await auth.signOut();
};

const formatDate = (date) => {
return date ? date.toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' }) : '';
};

return (
<div className="container mx-auto py-10">
{isSubscribed ? (
Expand All @@ -53,7 +78,10 @@ const UserProfile = () => {
<CardContent className="space-y-4">
<div className="space-y-2">
<p><strong>Email:</strong> {currentUser.email}</p>
<p><strong>Subscription Status:</strong> Active</p>
<p><strong>Subscription Status:</strong> {isCancelled
? `Cancelled (Active until ${formatDate(subscriptionEndDate)})`
: 'Active'}
</p>
</div>
<div className="flex space-x-4">
<Button
Expand All @@ -62,17 +90,18 @@ const UserProfile = () => {
>
Sign Out
</Button>
<Button
onClick={handleCancelSubscription}
variant="destructive"
>
Cancel Subscription
</Button>

<Button
onClick={handleCancelSubscription}
>
Manage Subscription
</Button>

</div>
</CardContent>
</Card>
) : currentUser ? (
showCheckout ? <Checkout /> : <SubscribeCard />
showCheckout ? <Checkout handleSignOut={handleSignOut}/> : <SubscribeCard />
) : (
<SubscribeCard />
)}
Expand Down

0 comments on commit 8043d30

Please sign in to comment.