TheEkopolitan's picture
Build the entire back end stack ready for easy integration from the services flow html
264efb5 verified
Raw History Blame Contribute Delete
10.7 kB
```javascript
// MediCash Backend API Server
const express = require('express');
const cors = require('cors');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const { v4: uuidv4 } = require('uuid');
const rateLimit = require('express-rate-limit');
const helmet = require('helmet');
const morgan = require('morgan');
const app = express();
const PORT = process.env.PORT || 3000;
const JWT_SECRET = process.env.JWT_SECRET || 'mediCash-secret-key-2025';
const SALT_ROUNDS = 12;
// Mock database (replace with real database in production)
let users = [];
let cards = [];
let transactions = [];
let otpCodes = new Map();
// Middleware
app.use(helmet());
app.use(cors());
app.use(express.json());
app.use(morgan('combined'));
// Rate limiting
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100 // limit each IP to 100 requests per windowMs
});
app.use(limiter);
// Mock exchange rates (in production, fetch from external API)
const exchangeRates = {
'USD': { 'NGN': 1500, 'KES': 150, 'GHS': 12, 'ZAR': 18 },
'EUR': { 'NGN': 1600, 'KES': 160, 'GHS': 13, 'ZAR': 19 },
'GBP': { 'NGN': 1900, 'KES': 190, 'GHS': 15, 'ZAR': 22 },
'NGN': { 'USD': 0.00067, 'EUR': 0.00063, 'KES': 0.0067, 'GHS': 0.083, 'ZAR': 0.12 },
'KES': { 'USD': 0.0067, 'NGN': 150, 'GHS': 0.08, 'ZAR': 0.12 },
'GHS': { 'USD': 0.083, 'NGN': 12, 'ZAR': 1.5 },
'ZAR': { 'USD': 0.056, 'NGN': 0.083, 'KES': 12.5, 'ZAR': 1 }
};
// Utility functions
const generateCardNumber = () => {
return '**** **** **** ' + Math.floor(Math.random() * 10000).toString().padStart(4, '0')
};
const generateOTP = () => {
return '123456'; // In production, generate random 6-digit code
};
// Authentication middleware
const authenticateToken = (req, res, next) => {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1]; // Bearer TOKEN
if (!token) {
return res.status(401).json({ error: 'Access token required' });
}
jwt.verify(token, JWT_SECRET, (err, user) => {
if (err) return res.status(403).json({ error: 'Invalid or expired token' });
}
req.user = user;
next();
};
// API Routes
// User Registration
app.post('/api/register', async (req, res) => {
try {
const { username, email, phone, password } = req.body;
// Validation
if (!username || !email || !phone || !password) {
return res.status(400).json({ error: 'All fields are required' });
}
// Check if user already exists
const existingUser = users.find(u => u.email === email || u.username === username);
if (existingUser) {
return res.status(409).json({ error: 'User already exists' });
}
// Hash password
const hashedPassword = await bcrypt.hash(password, SALT_ROUNDS);
// Create user
const user = {
id: uuidv4(),
username,
email,
phone,
password: hashedPassword,
creditScore: 300 + Math.floor(Math.random() * 500),
availableCredit: 0,
createdAt: new Date().toISOString()
};
users.push(user);
// Generate JWT token
const token = jwt.sign({ userId: user.id, username }, JWT_SECRET, { expiresIn: '24h' });
res.status(201).json({
message: 'User registered successfully',
token,
user: {
id: user.id,
username: user.username,
email: user.email,
},
creditScore: user.creditScore,
availableCredit: user.availableCredit
});
} catch (error) {
res.status(500).json({ error: 'Internal server error' });
}
});
// User Login
app.post('/api/login', async (req, res) => {
try {
const { email, password } = req.body;
if (!email || !password) {
return res.status(400).json({ error: 'Email and password required' });
});
// Send OTP
app.post('/api/send-otp', (req, res) => {
const { email } = req.body;
if (!email) {
return res.status(400).json({ error: 'Email is required' });
}
const user = users.find(u => u.email === email);
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
const otp = generateOTP();
otpCodes.set(email, { otp, expires: Date.now() + 10 * 60 * 1000 }); // 10 minutes
// In production, send OTP via email/SMS
console.log(`OTP for ${email}: ${otp}`);
res.json({
message: 'OTP sent successfully',
// For demo purposes, we return the OTP. In production, don't return it.
otp: otp
});
});
// Verify OTP
app.post('/api/verify-otp', (req, res) => {
const { email, otp } = req.body;
const storedOtp = otpCodes.get(email);
if (!storedOtp) {
return res.status(400).json({ error: 'No OTP requested for this email' });
}
if (Date.now() > storedOtp.expires) {
otpCodes.delete(email);
return res.status(400).json({ error: 'OTP expired' });
}
if (storedOtp.otp !== otp) {
return res.status(400).json({ error: 'Invalid OTP' });
}
// Clear OTP after successful verification
otpCodes.delete(email);
const user = users.find(u => u.email === email);
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
const token = jwt.sign({ userId: user.id, username: user.username }, JWT_SECRET, { expiresIn: '24h' });
res.json({
message: 'OTP verified successfully',
token,
user: {
id: user.id,
username: user.username,
email: user.email,
},
creditScore: user.creditScore,
availableCredit: user.availableCredit
});
});
// Create Card
app.post('/api/cards', authenticateToken, (req, res) => {
const { label, type, currency, limit } = req.body;
const newCard = {
id: uuidv4(),
userId: req.user.userId,
label,
type,
currency,
limit,
number: generateCardNumber(),
expiry: '12/' + (new Date().getFullYear() + 3).toString().slice(-2),
cvv: Math.floor(Math.random() * 1000).toString().padStart(3, '0'),
status: 'active',
createdAt: new Date().toISOString()
};
cards.push(newCard);
res.status(201).json({
message: 'Card created successfully',
card: newCard
});
});
// Get User Cards
app.get('/api/cards', authenticateToken, (req, res) => {
const userCards = cards.filter(card => card.userId === req.user.userId)
.map(card => ({ ...card, number: card.number }));
// Update Card Status
app.patch('/api/cards/:cardId', authenticateToken, (req, res) => {
const { cardId } = req.params;
const { status } = req.body;
const card = cards.find(c => c.id === cardId && c.userId === req.user.userId);
if (!card) {
return res.status(404).json({ error: 'Card not found' });
}
card.status = status;
res.json({
message: 'Card status updated successfully',
card
});
});
// Get Remittance Quote
app.post('/api/remittance/quote', (req, res) => {
const { amount, fromCurrency, toCurrency } = req.body;
if (!amount || !fromCurrency || !toCurrency) {
return res.status(400).json({ error: 'Amount, fromCurrency, and toCurrency are required' });
}
const rate = exchangeRates[fromCurrency]?.[toCurrency];
if (!rate) {
return res.status(400).json({ error: 'Currency conversion not available' });
}
const fee = Math.max(1, amount * 0.02); // 2% fee, minimum $1 equivalent
const receiveAmount = amount * rate - (fromCurrency === toCurrency ? 0 : fee);
const quote = {
sendAmount: amount,
sendCurrency: fromCurrency,
receiveCurrency: toCurrency,
exchangeRate: rate,
fee: fee,
receiveAmount: receiveAmount,
estimatedDelivery: 'Instant',
timestamp: new Date().toISOString()
};
res.json(quote);
});
// Process Remittance
app.post('/api/remittance/process', authenticateToken, (req, res) => {
const { amount, fromCurrency, toCurrency, recipientDetails } = req.body;
const transaction = {
id: uuidv4(),
userId: req.user.userId,
type: 'remittance',
amount,
fromCurrency,
toCurrency,
receiveAmount: amount * exchangeRates[fromCurrency]?.[toCurrency] || 1),
status: 'pending',
createdAt: new Date().toISOString(),
recipientDetails
};
transactions.push(transaction);
// Simulate processing delay
setTimeout(() => {
transaction.status = 'completed';
res.json({
message: 'Remittance processed successfully',
transactionId: transaction.id
}, 2000);
// For demo, return immediately
res.json({
message: 'Remittance initiated successfully',
transactionId: transaction.id
});
});
// Get User Profile
app.get('/api/profile', authenticateToken, (req, res) => {
const user = users.find(u => u.id === req.user.userId);
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
const userCards = cards.filter(card => card.userId === req.user.userId);
res.json({
user: {
id: user.id,
username: user.username,
email: user.email,
phone: user.phone
},
stats: {
creditScore: user.creditScore,
availableCredit: user.availableCredit,
activeCards: userCards.length,
totalTransactions: transactions.filter(t => t.userId === req.user.userId).length
}
});
});
// Update User Profile
app.put('/api/profile', authenticateToken, async (req, res) => {
try {
const userIndex = users.findIndex(u => u.id === req.user.userId);
if (userIndex === -1) {
return res.status(404).json({ error: 'User not found' });
}
const { username, phone, nextOfKin, biometricEnabled, locationEnabled } = req.body;
if (username) users[userIndex].username = username;
if (phone) users[userIndex].phone = phone;
res.json({
message: 'Profile updated successfully',
user: {
id: users[userIndex].id,
username: users[userIndex].username,
email: users[userIndex].email,
phone: users[userIndex].phone,
nextOfKin,
biometricEnabled,
locationEnabled
});
});
// Get Dashboard Data
app.get('/api/dashboard', authenticateToken, (req, res) => {
const userCards = cards.filter(card => card.userId === req.user.userId);
const userTransactions = transactions.filter(t => t.userId === req.user.userId);
res.json({
creditScore: users.find(u => u.id === req.user.userId).creditScore,
availableCredit: users.find(u => u.id === req.user.userId).availableCredit,
activeCards: userCards.length,
recentTransactions: userTransactions.slice(-5)
});
});
// Health check
app.get('/api/health', (req, res) => {
res.json({
status: 'OK',
message: 'MediCash API is running',
timestamp: new Date().toISOString()
});
});
// Error handling middleware
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ error: 'Something went wrong!' });
});
app.listen(PORT, () => {
console.log(`MediCash API server running on port ${PORT}`);
});
```