Spaces:
Running
Running
Ctrl+K
I noticed a lot of anomalies in the work. The bible books are not complete, the languages included are not present, the early access code for early users instead of paying to access all premium features are not present and more so, many other features like theological and lexicons are not present. - Follow Up Deployment
0a3ccfa verified - 1.52 kB initial commit
- 217 Bytes name = "faithbank-api" main = "src/index.js" compatibility_date = "2023-10-30" [vars] JWT_SECRET = "YOUR_OWN_SUPER_SECRET_KEY_FOR_JWT" STRIPE_SECRET_KEY = "YOUR_STRIPE_SECRET_API_KEY" BIBLE_API_KEY = "YOUR_API_BIBLE_KEY" [[d1_databases]] binding = "DB" database_name = "faithbank-database" database_id = "YOUR_CLOUDFLARE_D1_DATABASE_ID"import { Router } from 'itty-router'; import { handleCors } from './cors'; // Import all route handlers import { handleSignup, handleLogin } from './handlers/authHandler'; import { getBibleVersions, getBibleContent, getAudioContent } from './handlers/bibleHandler'; import { getConnections } from './handlers/connectionsHandler'; import { getResources, getResourceById, searchResources } from './handlers/libraryHandler'; import { getUserNotes, addNote, deleteNote } from './handlers/notesHandler'; import { getUserPlans, addPlan, logSession } from './handlers/plansHandler'; import { handleStripeCheckout, handlePromoCode } from './handlers/paymentHandler'; import { authenticateRequest } from './authMiddleware'; const router = Router(); // CORS Preflight Handler router.all('*', handleCors); // --- PUBLIC ROUTES --- // Auth router.post('/api/v1/auth/signup', handleSignup); router.post('/api/v1/auth/login', handleLogin); // Bible Content (Publicly accessible) router.get('/api/v1/bible/versions', getBibleVersions); router.get('/api/v1/bible/content', getBibleContent); router.get('/api/v1/bible/audio', getAudioContent); // Connections & Library (Publicly accessible) router.get('/api/v1/connections', getConnections); router.get('/api/v1/resources', getResources); router.get('/api/v1/resources/search', searchResources); router.get('/api/v1/resources/:id', getResourceById); // --- PROTECTED ROUTES (Authentication Required) --- // Notes router.get('/api/v1/notes', authenticateRequest, getUserNotes); router.post('/api/v1/notes', authenticateRequest, addNote); router.delete('/api/v1/notes/:id', authenticateRequest, deleteNote); // Study Plans router.get('/api/v1/plans', authenticateRequest, getUserPlans); router.post('/api/v1/plans', authenticateRequest, addPlan); router.post('/api/v1/plans/log', authenticateRequest, logSession); // Payments router.post('/api/v1/payments/create-checkout-session', authenticateRequest, handleStripeCheckout); router.post('/api/v1/payments/redeem-promo', authenticateRequest, handlePromoCode); // 404 Handler router.all('*', () => new Response('404, Not Found.', { status: 404 })); export default { fetch: router.handle };import { sign } from '@tsndr/cloudflare-worker-jwt'; import { v4 as uuidv4 } from 'uuid'; // A simplified representation of password hashing. // In a real app, use a robust library like bcrypt, but that's not available in CF Workers. // This is a placeholder for a more secure hashing mechanism. async function hashPassword(password) { const encoder = new TextEncoder(); const data = encoder.encode(password); const hash = await crypto.subtle.digest('SHA-256', data); return btoa(String.fromCharCode(...new Uint8Array(hash))); } export async function handleSignup(request, env) { const { email, password, name } = await request.json(); if (!email || !password || !name) { return new Response(JSON.stringify({ error: 'Missing required fields' }), { status: 400, headers: { 'Content-Type': 'application/json' } }); } const hashedPassword = await hashPassword(password); const userId = uuidv4(); try { await env.DB.prepare( 'INSERT INTO Users (id, email, password_hash, name, premium_status) VALUES (?, ?, ?, ?, ?)' ).bind(userId, email, hashedPassword, name, 0).run(); return new Response(JSON.stringify({ message: 'User created successfully' }), { status: 201, headers: { 'Content-Type': 'application/json' } }); } catch (e) { if (e.message.includes('UNIQUE constraint failed')) { return new Response(JSON.stringify({ error: 'Email already exists' }), { status: 409, headers: { 'Content-Type': 'application/json' } }); } return new Response(JSON.stringify({ error: 'Could not create user', details: e.message }), { status: 500, headers: { 'Content-Type': 'application/json' } }); } } export async function handleLogin(request, env) { const { email, password } = await request.json(); if (!email || !password) { return new Response(JSON.stringify({ error: 'Missing email or password' }), { status: 400, headers: { 'Content-Type': 'application/json' } }); } const user = await env.DB.prepare('SELECT * FROM Users WHERE email = ?').bind(email).first(); if (!user) { return new Response(JSON.stringify({ error: 'Invalid credentials' }), { status: 401, headers: { 'Content-Type': 'application/json' } }); } const hashedPassword = await hashPassword(password); if (hashedPassword !== user.password_hash) { return new Response(JSON.stringify({ error: 'Invalid credentials' }), { status: 401, headers: { 'Content-Type': 'application/json' } }); } const payload = { userId: user.id, email: user.email, name: user.name, premium: user.premium_status, exp: Math.floor(Date.now() / 1000) + (60 * 60 * 24 * 7) // 7 days }; const token = await sign(payload, env.JWT_SECRET); return new Response(JSON.stringify({ token, user: { id: user.id, name: user.name, email: user.email, premium: user.premium_status } }), { status: 200, headers: { 'Content-Type': 'application/json' } }); }import { verify } from '@tsndr/cloudflare-worker-jwt'; export async function authenticateRequest(request, env) { const authHeader = request.headers.get('Authorization'); if (!authHeader || !authHeader.startsWith('Bearer ')) { return new Response(JSON.stringify({ error: 'Unauthorized' }), { status: 401, headers: { 'Content-Type': 'application/json' } }); } const token = authHeader.substring(7); try { const isValid = await verify(token, env.JWT_SECRET); if (!isValid) { return new Response(JSON.stringify({ error: 'Invalid token' }), { status: 401, headers: { 'Content-Type': 'application/json' } }); } // Attach user payload to the request for downstream handlers const { payload } = await verify(token, env.JWT_SECRET, { throwError: true }); request.user = payload; } catch (err) { return new Response(JSON.stringify({ error: 'Authentication failed', details: err.message }), { status: 401, headers: { 'Content-Type': 'application/json' } }); } }// This file represents the logic to fetch data from an external Bible API. // The actual implementation would involve making fetch requests to api.bible or similar. export async function getBibleVersions(request, env) { // In a real app, this would fetch the list of versions from the external API const versions = [ { id: 'de4e12af7f28f599-01', name: 'King James Version', language: 'eng' }, { id: '06125adad2d5898a-01', name: 'The Message', language: 'eng' }, { id: 'bba9f40183526463-01', name: 'New International Version', language: 'eng' }, { id: '685d1470fe4d5c3b-01', name: 'Amplified Bible', language: 'eng' }, { id: '93236b73455857b3-01', name: 'Yoruba Bible', language: 'yor' }, { id: 'b32b9d1b64b4ef29-01', name: 'Igbo Bible', language: 'ibo' }, { id: 'd80a403248543c49-01', name: 'Hausa Bible', language: 'hau' }, { id: 'fra-LSG', name: 'Louis Segond', language: 'fra' }, { id: 'grc-byz', name: 'Koine Greek', language: 'grc' }, { id: 'hbo-wlc', name: 'Hebrew Old Testament', language: 'hbo' } ]; return new Response(JSON.stringify(versions), { status: 200, headers: { 'Content-Type': 'application/json' } }); } export async function getBibleContent(request, env) { const { searchParams } = new URL(request.url); const versionId = searchParams.get('version'); const chapterId = searchParams.get('chapter'); // e.g., 'GEN.1' if (!versionId || !chapterId) { return new Response(JSON.stringify({ error: 'Missing version or chapter ID' }), { status: 400 }); } const apiUrl = `https://api.scripture.api.bible/v1/bibles/${versionId}/chapters/${chapterId}?content-type=json&include-notes=false&include-titles=true&include-chapter-numbers=false&include-verse-numbers=true&include-verse-spans=false`; const response = await fetch(apiUrl, { headers: { 'api-key': env.BIBLE_API_KEY } } ); if (!response.ok) { return new Response(JSON.stringify({ error: 'Failed to fetch Bible content' }), { status: response.status }); } const data = await response.json(); return new Response(JSON.stringify(data.data), { status: 200, headers: { 'Content-Type': 'application/json' } }); } export async function getAudioContent(request, env) { // Similar logic to getBibleContent, but for audio chapters const { searchParams } = new URL(request.url); const versionId = searchParams.get('version'); const chapterId = searchParams.get('chapter'); const apiUrl = `https://api.scripture.api.bible/v1/bibles/${versionId}/chapters/${chapterId}/audio`; // ... fetch logic ... return new Response(JSON.stringify({ message: 'Audio endpoint placeholder' } ), { status: 200 }); }// This file represents the logic for the "Typologies & Connections" engine. // It fetches data from various tables in our own database that have been pre-populated // with cross-references, commentary snippets, and topical links. export async function getConnections(request, env) { const { searchParams } = new URL(request.url); const verseId = searchParams.get('verse'); // e.g., 'GEN.3.15' if (!verseId) { return new Response(JSON.stringify({ error: 'Missing verse ID' }), { status: 400 }); } // In a real application, these would be efficient SQL queries. // We are simulating the fetching process here. // 1. Fetch Cross-References (from a pre-populated TSK table) const crossRefsStmt = env.DB.prepare('SELECT related_verse FROM CrossReferences WHERE verse_id = ?').bind(verseId); const crossRefsResult = await crossRefsStmt.all(); const crossReferences = crossRefsResult.results.map(r => r.related_verse); // 2. Fetch Commentary Snippets const commentaryStmt = env.DB.prepare('SELECT author, text FROM Commentaries WHERE verse_id = ?').bind(verseId); const commentaries = await commentaryStmt.all(); // 3. Fetch Thematic Links const topicsStmt = env.DB.prepare('SELECT topic_name FROM TopicalLinks WHERE verse_id = ?').bind(verseId); const topicsResult = await topicsStmt.all(); const topics = topicsResult.results.map(r => r.topic_name); // 4. Fetch Typological Links (from a curated table) const typologyStmt = env.DB.prepare('SELECT description, fulfillment_verse FROM Typology WHERE type_verse = ?').bind(verseId); const typologies = await typologyStmt.all(); const connections = { crossReferences, commentaries: commentaries.results, topics, typologies: typologies.results }; return new Response(JSON.stringify(connections), { status: 200, headers: { 'Content-Type': 'application/json' } }); }export async function getResources(request, env) { const { searchParams } = new URL(request.url); const category = searchParams.get('category'); let stmt; if (category) { stmt = env.DB.prepare('SELECT id, title, author, category FROM Resources WHERE category = ? ORDER BY title').bind(category); } else { stmt = env.DB.prepare('SELECT id, title, author, category FROM Resources ORDER BY category, title'); } const { results } = await stmt.all(); return new Response(JSON.stringify(results), { status: 200, headers: { 'Content-Type': 'application/json' } }); } export async function getResourceById(request, env) { const { id } = request.params; const resource = await env.DB.prepare('SELECT * FROM Resources WHERE id = ?').bind(id).first(); if (!resource) { return new Response(JSON.stringify({ error: 'Resource not found' }), { status: 404 }); } return new Response(JSON.stringify(resource), { status: 200, headers: { 'Content-Type': 'application/json' } }); } export async function searchResources(request, env) { const { searchParams } = new URL(request.url); const query = searchParams.get('q'); if (!query) { return new Response(JSON.stringify({ error: 'Search query is required' }), { status: 400 }); } // D1 supports full-text search if configured. This is a simplified LIKE query. const stmt = env.DB.prepare("SELECT id, title, author, category FROM Resources WHERE content LIKE ? OR title LIKE ?") .bind(`%${query}%`, `%${query}%`); const { results } = await stmt.all(); return new Response(JSON.stringify(results), { status: 200, headers: { 'Content-Type': 'application/json' } }); } import { v4 as uuidv4 } from 'uuid'; export async function getUserNotes(request, env) { const userId = request.user.userId; const stmt = env.DB.prepare('SELECT * FROM Notes WHERE user_id = ? ORDER BY created_at DESC').bind(userId); const { results } = await stmt.all(); return new Response(JSON.stringify(results), { status: 200, headers: { 'Content-Type': 'application/json' } }); } export async function addNote(request, env) { const userId = request.user.userId; const { verse_id, content } = await request.json(); if (!verse_id || !content) { return new Response(JSON.stringify({ error: 'Missing verse_id or content' }), { status: 400 }); } const noteId = uuidv4(); await env.DB.prepare( 'INSERT INTO Notes (id, user_id, verse_id, content) VALUES (?, ?, ?, ?)' ).bind(noteId, userId, verse_id, content).run(); return new Response(JSON.stringify({ message: 'Note added successfully', noteId }), { status: 201 }); } export async function deleteNote(request, env) { const userId = request.user.userId; const { id } = request.params; // Ensure the user owns the note they are trying to delete const result = await env.DB.prepare( 'DELETE FROM Notes WHERE id = ? AND user_id = ?' ).bind(id, userId).run(); if (result.changes === 0) { return new Response(JSON.stringify({ error: 'Note not found or user not authorized' }), { status: 404 }); } return new Response(JSON.stringify({ message: 'Note deleted successfully' }), { status: 200 }); }.import { v4 as uuidv4 } from 'uuid'; export async function getUserPlans(request, env) { const userId = request.user.userId; // This query would be more complex in reality, joining with ReadingSessions to get progress const stmt = env.DB.prepare('SELECT * FROM StudyPlans WHERE user_id = ?').bind(userId); const { results } = await stmt.all(); return new Response(JSON.stringify(results), { status: 200, headers: { 'Content-Type': 'application/json' } }); } export async function addPlan(request, env) { const userId = request.user.userId; const { name, description, reading_list } = await request.json(); // reading_list could be a JSON array of chapter IDs const planId = uuidv4(); await env.DB.prepare( 'INSERT INTO StudyPlans (id, user_id, name, description, reading_list) VALUES (?, ?, ?, ?, ?)' ).bind(planId, userId, name, description, JSON.stringify(reading_list)).run(); return new Response(JSON.stringify({ message: 'Plan added successfully', planId }), { status: 201 }); } export async function logSession(request, env) { const userId = request.user.userId; const { plan_id, chapter_id } = await request.json(); const sessionId = uuidv4(); await env.DB.prepare( 'INSERT INTO ReadingSessions (id, user_id, plan_id, chapter_id) VALUES (?, ?, ?, ?)' ).bind(sessionId, userId, plan_id, chapter_id).run(); return new Response(JSON.stringify({ message: 'Session logged successfully' }), { status: 201 }); }.// This file requires the Stripe Node.js library, which might not be directly usable in CF Workers. // The official way is to use fetch with the Stripe REST API. This is a conceptual representation. export async function handleStripeCheckout(request, env) { const user = request.user; const { origin } = new URL(request.url); // Using Stripe REST API with fetch const checkoutSession = { payment_method_types: ['card'], line_items: [{ price_data: { currency: 'usd', product_data: { name: 'FaithBank Premium - Lifetime Access', description: 'Unlock all premium features forever.', }, unit_amount: 500, // $5.00 in cents }, quantity: 1, }], mode: 'payment', success_url: `${origin}/payment-success?session_id={CHECKOUT_SESSION_ID}`, cancel_url: `${origin}/upgrade`, client_reference_id: user.userId, // Link the session to our user }; const response = await fetch('https://api.stripe.com/v1/checkout/sessions', { method: 'POST', headers: { 'Authorization': `Bearer ${env.STRIPE_SECRET_KEY}`, 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams(checkoutSession ) }); const session = await response.json(); return new Response(JSON.stringify({ id: session.id }), { status: 200, headers: { 'Content-Type': 'application/json' } }); } export async function handlePromoCode(request, env) { const userId = request.user.userId; const { code } = await request.json(); // In a real app, you'd look this up in a PromoCodes table in your DB if (code.toUpperCase() === 'EARLYBIRD2025') { // Update user's premium status in the database await env.DB.prepare( 'UPDATE Users SET premium_status = 1 WHERE id = ?' ).bind(userId).run(); return new Response(JSON.stringify({ message: 'Promo code redeemed successfully!' }), { status: 200 }); } else { return new Response(JSON.stringify({ error: 'Invalid promo code' }), { status: 400 }); } }{ "name": "faithbank-frontend", "private": true, "version": "1.0.0", "type": "module", "scripts": { "dev": "vite", "build": "vite build", "preview": "vite preview" }, "dependencies": { "react": "^18.2.0", "react-dom": "^18.2.0", "react-router-dom": "^6.20.0", "axios": "^1.6.2", "jwt-decode": "^4.0.0", "zustand": "^4.4.7" }, "devDependencies": { "@vitejs/plugin-react": "^4.2.0", "vite": "^5.0.0", "autoprefixer": "^10.4.16", "postcss": "^8.4.32", "tailwindcss": "^3.3.6" } }import React from 'react'; import ReactDOM from 'react-dom/client'; import App from './App.jsx'; import './index.css'; // Tailwind CSS import { BrowserRouter } from 'react-router-dom'; ReactDOM.createRoot(document.getElementById('root')).render( <React.StrictMode> <BrowserRouter> <App /> </BrowserRouter> </React.StrictMode>, );import { Routes, Route } from 'react-router-dom'; import HomePage from './pages/HomePage'; import LoginPage from './pages/LoginPage'; import SignupPage from './pages/SignupPage'; import DashboardPage from './pages/DashboardPage'; import BibleReaderPage from './pages/BibleReaderPage'; import MyNotesPage from './pages/MyNotesPage'; import LibraryPage from './pages/LibraryPage'; import UpgradePage from './pages/UpgradePage'; import ProtectedRoute from './components/ProtectedRoute'; import MainLayout from './layouts/MainLayout'; function App() { return ( <Routes> <Route element={<MainLayout />}> <Route path="/" element={<HomePage />} /> <Route path="/login" element={<LoginPage />} /> <Route path="/signup" element={<SignupPage />} /> <Route path="/bible" element={<BibleReaderPage />} /> {/* Protected Routes */} <Route path="/dashboard" element={<ProtectedRoute><DashboardPage /></ProtectedRoute>} /> <Route path="/my-notes" element={<ProtectedRoute premium><MyNotesPage /></ProtectedRoute>} /> <Route path="/library" element={<ProtectedRoute><LibraryPage /></ProtectedRoute>} /> <Route path="/upgrade" element={<ProtectedRoute><UpgradePage /></ProtectedRoute>} /> </Route> </Routes> ); } export default App;import { create } from 'zustand'; import { jwtDecode } from 'jwt-decode'; const useAuthStore = create((set) => ({ token: localStorage.getItem('token') || null, user: localStorage.getItem('token') ? jwtDecode(localStorage.getItem('token')) : null, login: (token) => { localStorage.setItem('token', token); const user = jwtDecode(token); set({ token, user }); }, logout: () => { localStorage.removeItem('token'); set({ token: null, user: null }); }, updateUserPremiumStatus: () => { set((state) => { if (state.user) { const updatedUser = { ...state.user, premium: 1 }; // In a real app, you'd re-fetch a new token with the updated premium status return { user: updatedUser }; } return state; }); } })); export default useAuthStore;import React, { useState, useEffect } from 'react'; import axios from 'axios'; import ConnectionsPanel from '../components/ConnectionsPanel'; import WordStudyPopup from '../components/WordStudyPopup'; // This is a simplified representation of the feature-rich page. const BibleReaderPage = () => { const [versions, setVersions] = useState([]); const [selectedVersion, setSelectedVersion] = useState('de4e12af7f28f599-01'); // KJV default const [chapterContent, setChapterContent] = useState(null); const [selectedWord, setSelectedWord] = useState(null); const [selectedVerse, setSelectedVerse] = useState(null); useEffect(() => { // Fetch Bible versions on component mount const fetchVersions = async () => { const response = await axios.get('/api/v1/bible/versions'); setVersions(response.data); }; fetchVersions(); }, []); useEffect(() => { // Fetch chapter content when version or chapter changes const fetchContent = async () => { // Default to John 3 for demo const response = await axios.get(`/api/v1/bible/content?version=${selectedVersion}&chapter=JHN.3`); setChapterContent(response.data); }; fetchContent(); }, [selectedVersion]); const handleWordClick = (wordData) => { // Logic for when a Strong's number is clicked setSelectedWord(wordData); }; const handleVerseClick = (verseId) => { // Logic for opening the connections panel setSelectedVerse(verseId); }; return ( <div className="p-4"> <h1 className="text-2xl font-bold">Bible Reader</h1> <select value={selectedVersion} onChange={(e) => setSelectedVersion(e.target.value)} className="p-2 border rounded" > {versions.map(v => <option key={v.id} value={v.id}>{v.name}</option>)} </select> <div className="mt-4 prose" dangerouslySetInnerHTML={{ __html: chapterContent?.content }} /> {selectedWord && <WordStudyPopup word={selectedWord} onClose={() => setSelectedWord(null)} />} {selectedVerse && <ConnectionsPanel verseId={selectedVerse} onClose={() => setSelectedVerse(null)} />} </div> ); }; export default BibleReaderPage; import React, { useState, useEffect } from 'react'; import axios from 'axios'; const ConnectionsPanel = ({ verseId, onClose }) => { const [connections, setConnections] = useState(null); const [isLoading, setIsLoading] = useState(true); useEffect(() => { const fetchConnections = async () => { setIsLoading(true); try { const response = await axios.get(`/api/v1/connections?verse=${verseId}`); setConnections(response.data); } catch (error) { console.error("Failed to fetch connections", error); } finally { setIsLoading(false); } }; if (verseId) { fetchConnections(); } }, [verseId]); return ( <div className="fixed inset-0 bg-black bg-opacity-50 flex justify-center items-center"> <div className="bg-white p-6 rounded-lg w-1/2 max-h-[80vh] overflow-y-auto"> <h2 className="text-xl font-bold mb-4">Connections for {verseId}</h2> {isLoading ? ( <p>Loading connections...</p> ) : ( <div> {/* Render Cross-References, Commentaries, Topics, etc. */} <h3 className="font-semibold mt-4">Cross-References</h3> <ul>{connections?.crossReferences.map(cr => <li key={cr}>{cr}</li>)}</ul> <h3 className="font-semibold mt-4">Commentaries</h3> <div>{connections?.commentaries.map(c => <div key={c.author}><strong>{c.author}:</strong> {c.text}</div>)}</div> </div> )} <button onClick={onClose} className="mt-4 p-2 bg-red-500 text-white rounded">Close</button> </div> </div> ); }; export default ConnectionsPanel; import React from 'react'; import { Navigate } from 'react-router-dom'; import useAuthStore from '../store/authStore'; import UpgradeModal from './UpgradeModal'; const ProtectedRoute = ({ children, premium = false }) => { const { user } = useAuthStore(); if (!user) { // User not logged in, redirect to login page return <Navigate to="/login" />; } if (premium && user.premium !== 1) { // User is not premium, show an upgrade modal or redirect return <UpgradeModal show={true} />; } // User is authenticated (and premium if required), render the child component return children; }; export default ProtectedRoute; This is a complete code for the bible app I tried to build on manus.im help me check for errors and fix them. Then deploy it for great consumption by people, I need the app and website to be flawless. - Initial Deployment
- 56.3 kB I noticed a lot of anomalies in the work. The bible books are not complete, the languages included are not present, the early access code for early users instead of paying to access all premium features are not present and more so, many other features like theological and lexicons are not present. - Follow Up Deployment
- 388 Bytes initial commit