Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 47 additions & 36 deletions server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,72 +12,83 @@ dotenv.config({ path: path.join(__dirname, '.env') });
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server, {
cors: {
origin: "*",
methods: ["GET", "POST"]
}
cors: {
origin: '*',
methods: ['GET', 'POST'],
},
});

// Initialize Simulation Service
const simulation = new SimulationService(io);
simulation.start();

io.on('connection', (socket) => {
console.log('Client connected for IoT stream:', socket.id);
console.log('Client connected for IoT stream:', socket.id);
});

// Middleware
app.use(cors());

// Stripe Webhook Endpoint (requires raw unparsed Buffer before global express.json)
app.use('/api/webhooks', express.raw({ type: 'application/json' }), require('./routes/webhooks'));

app.use(express.json());

// Hybrid Connection Logic
const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://localhost:27017/traffitech';
mongoose.connect(MONGODB_URI, { serverSelectionTimeoutMS: 4000 })
.then(() => console.log('✅ Connected to MongoDB Atlas (Production Cloud DB)'))
.catch((err) => {
console.warn('⚠️ MongoDB Atlas connection error details:', err?.message || err);
console.warn('⚠️ Using Local JSON DB fallback.');
if (process.env.NODE_ENV === 'production' || process.env.RENDER === 'true') {
console.warn('🚨 PRODUCTION PERSISTENCE WARNING: MONGODB_URI is not connected in production mode. Data written to JSON fallback DB will be ephemeral across server restarts on Render. Ensure MONGODB_URI is configured in Render environment variables for cloud persistence.');
} else {
console.log('✅ Zero-Dependency Fallback Mode Active');
}
});
mongoose
.connect(MONGODB_URI, { serverSelectionTimeoutMS: 4000 })
.then(() => console.log('✅ Connected to MongoDB Atlas (Production Cloud DB)'))
.catch((err) => {
console.warn('⚠️ MongoDB Atlas connection error details:', err?.message || err);
console.warn('⚠️ Using Local JSON DB fallback.');
if (process.env.NODE_ENV === 'production' || process.env.RENDER === 'true') {
console.warn(
'🚨 PRODUCTION PERSISTENCE WARNING: MONGODB_URI is not connected in production mode. Data written to JSON fallback DB will be ephemeral across server restarts on Render. Ensure MONGODB_URI is configured in Render environment variables for cloud persistence.'
);
} else {
console.log('✅ Zero-Dependency Fallback Mode Active');
}
});

// Routes
app.use('/api/auth', require('./routes/auth'));
app.use('/api/bookings', require('./routes/bookings'));
app.use('/api/payments', require('./routes/payments'));
app.use('/api/webhooks', require('./routes/webhooks'));
app.use('/api/rapids-analytics', require('./routes/rapidsAnalytics'));

// Basic Route
app.get('/', (req, res) => {
res.json({
message: 'TraffiTech API is running',
mode: mongoose.connection.readyState === 1 ? 'Production (Cloud DB)' : 'Development (Fallback JSON DB)'
});
res.json({
message: 'TraffiTech API is running',
mode:
mongoose.connection.readyState === 1
? 'Production (Cloud DB)'
: 'Development (Fallback JSON DB)',
});
});

// Port Configuration
const PORT = process.env.PORT || 5000;
server.listen(PORT, '0.0.0.0', () => {
console.log(`🚀 Server running on port ${PORT} (0.0.0.0 interface bound)`);
console.log(`🚀 Server running on port ${PORT} (0.0.0.0 interface bound)`);

// Environment Variables Audit Log on Boot
const isProdEnv = process.env.NODE_ENV === 'production' || process.env.RENDER === 'true';
if (isProdEnv) {
const missingKeys = [];
if (!process.env.JWT_SECRET) missingKeys.push('JWT_SECRET');
if (!process.env.ADMIN_SECRET_KEY) missingKeys.push('ADMIN_SECRET_KEY');
if (!process.env.STRIPE_SECRET_KEY) missingKeys.push('STRIPE_SECRET_KEY');
if (!process.env.STRIPE_WEBHOOK_SECRET) missingKeys.push('STRIPE_WEBHOOK_SECRET');
if (!process.env.MONGODB_URI) missingKeys.push('MONGODB_URI');
// Environment Variables Audit Log on Boot
const isProdEnv = process.env.NODE_ENV === 'production' || process.env.RENDER === 'true';
if (isProdEnv) {
const missingKeys = [];
if (!process.env.JWT_SECRET) missingKeys.push('JWT_SECRET');
if (!process.env.ADMIN_SECRET_KEY) missingKeys.push('ADMIN_SECRET_KEY');
if (!process.env.STRIPE_SECRET_KEY) missingKeys.push('STRIPE_SECRET_KEY');
if (!process.env.STRIPE_WEBHOOK_SECRET) missingKeys.push('STRIPE_WEBHOOK_SECRET');
if (!process.env.MONGODB_URI) missingKeys.push('MONGODB_URI');

if (missingKeys.length > 0) {
console.warn(`⚠️ PRODUCTION ENV CONFIG NOTICE: Missing Render environment variables: ${missingKeys.join(', ')}`);
} else {
console.log('✅ Production Environment Audit Passed: All production secrets configured.');
}
if (missingKeys.length > 0) {
console.warn(
`⚠️ PRODUCTION ENV CONFIG NOTICE: Missing Render environment variables: ${missingKeys.join(', ')}`
);
} else {
console.log('✅ Production Environment Audit Passed: All production secrets configured.');
}
}
});
96 changes: 53 additions & 43 deletions server/routes/payments.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,54 +5,64 @@ const Booking = require('../models/Booking');
const router = express.Router();

const toPlain = (doc) => {
if (!doc) return null;
if (doc.data) return doc.data;
if (typeof doc.toObject === 'function') return doc.toObject();
return doc;
if (!doc) return null;
if (doc.data) return doc.data;
if (typeof doc.toObject === 'function') return doc.toObject();
return doc;
};

// Create Payment Intent
router.post('/create-payment-intent', auth, async (req, res) => {
try {
const { bookingId, currency = 'inr' } = req.body;

if (!bookingId) {
return res.status(400).json({ message: 'Booking ID is required' });
}

// Fetch booking from database to get verified server-computed price
const booking = await Booking.findById(bookingId);
if (!booking) {
return res.status(404).json({ message: 'Booking not found' });
}

const plain = toPlain(booking);
// Ensure user owns the booking
const userId = String(plain.user || '');
if (userId !== String(req.user.id)) {
return res.status(403).json({ message: 'Unauthorized access to this booking' });
}

const totalPrice = plain.totalPrice || 50;

const paymentIntent = await stripe.paymentIntents.create({
amount: Math.round(Number(totalPrice) * 100), // Secure verified amount
currency,
automatic_payment_methods: {
enabled: true,
},
metadata: {
bookingId: String(plain._id || bookingId) // Inject metadata for Webhooks
}
});

res.json({
clientSecret: paymentIntent.client_secret,
});
} catch (err) {
console.error("Stripe Backend Error:", err);
res.status(500).json({ message: err.message || 'Failed to create Stripe PaymentIntent', error: err.stack });
try {
const { bookingId, currency = 'inr' } = req.body;

if (!bookingId) {
return res.status(400).json({ message: 'Booking ID is required' });
}

// Fetch booking from database to get verified server-computed price
const booking = await Booking.findById(bookingId);
if (!booking) {
return res.status(404).json({ message: 'Booking not found' });
}

const plain = toPlain(booking);
// Ensure user owns the booking
const userId = String(plain.user || '');
if (userId !== String(req.user.id)) {
return res.status(403).json({ message: 'Unauthorized access to this booking' });
}

// Prevent charging already paid bookings
if (plain.paymentStatus === 'paid' || plain.paymentStatus === 'completed') {
return res.status(400).json({ message: 'Booking is already paid' });
}

// Prevent charging cancelled or refunded bookings
if (plain.paymentStatus === 'cancelled' || plain.paymentStatus === 'refunded') {
return res.status(400).json({ message: 'Booking is cancelled' });
}

const totalPrice = plain.totalPrice || 50;

const paymentIntent = await stripe.paymentIntents.create({
amount: Math.round(Number(totalPrice) * 100), // Secure verified amount
currency,
automatic_payment_methods: {
enabled: true,
},
metadata: {
bookingId: String(plain._id || bookingId), // Inject metadata for Webhooks
},
});

res.json({
clientSecret: paymentIntent.client_secret,
});
} catch (err) {
console.error('Stripe Backend Error:', err);
res.status(500).json({ message: err.message || 'Failed to create Stripe PaymentIntent' });
}
});

module.exports = router;
Loading