const express = require('express'); const bodyParser = require('body-parser'); const bcrypt = require('bcryptjs'); const jwt = require('jsonwebtoken'); const admin = require('firebase-admin'); const cors = require('cors'); // Import the cors package require('dotenv').config(); // Load environment variables from .env const app = express(); app.use(bodyParser.json()); // Enable CORS for all origins app.use(cors()); // Firebase Admin SDK setup const serviceAccount = { type: process.env.FIREBASE_TYPE, project_id: process.env.FIREBASE_PROJECT_ID, private_key_id: process.env.FIREBASE_PRIVATE_KEY_ID, private_key: process.env.FIREBASE_PRIVATE_KEY.replace(/\\n/g, '\n'), client_email: process.env.FIREBASE_CLIENT_EMAIL, client_id: process.env.FIREBASE_CLIENT_ID, auth_uri: process.env.FIREBASE_AUTH_URI, token_uri: process.env.FIREBASE_TOKEN_URI, auth_provider_x509_cert_url: process.env.FIREBASE_AUTH_PROVIDER_X509_CERT_URL, client_x509_cert_url: process.env.FIREBASE_CLIENT_X509_CERT_URL }; admin.initializeApp({ credential: admin.credential.cert(serviceAccount) }); const db = admin.firestore(); // Secret key for JWT const JWT_SECRET = 'your_jwt_secret_key'; // Replace with your actual JWT secret key // Register route app.post('/register', async (req, res) => { const { username, password } = req.body; if (!username || !password) { return res.status(400).send('Username and password are required'); } const hashedPassword = await bcrypt.hash(password, 10); // Save user to Firebase Firestore try { await db.collection('users').doc(username).set({ username, password: hashedPassword }); res.status(201).send('User registered'); } catch (error) { console.error('Error registering user:', error); res.status(500).send('Error registering user'); } }); // Login route app.post('/login', async (req, res) => { const { username, password } = req.body; try { const userDoc = await db.collection('users').doc(username).get(); if (!userDoc.exists) { return res.status(400).send('Invalid username or password'); } const user = userDoc.data(); const isPasswordValid = await bcrypt.compare(password, user.password); if (!isPasswordValid) { return res.status(400).send('Invalid username or password'); } const token = jwt.sign({ username: user.username }, JWT_SECRET, { expiresIn: '1h' }); res.json({ token }); } catch (error) { console.error('Error during login:', error); res.status(500).send('Error during login'); } }); // Fetch ads route app.get('/ads', async (req, res) => { try { const adsSnapshot = await db.collection('ads').get(); const ads = adsSnapshot.docs.map(doc => ({ id: doc.id, ...doc.data() })); res.json(ads); } catch (error) { console.error('Error fetching ads:', error); res.status(500).send('Error fetching ads'); } }); const PORT = 5000; app.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT}`); });