Untitled

mail@pastecode.io avatar
unknown
plain_text
19 days ago
1.8 kB
3
Indexable
Never
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const app = express();
app.use(cors());
app.use(express.json());

// MongoDB connection
mongoose.connect('mongodb://localhost:27017/sacco', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

// User schema
const UserSchema = new mongoose.Schema({
  name: String,
  email: String,
  password: String,
  role: { type: String, enum: ['member', 'admin'], default: 'member' },
  approved: { type: Boolean, default: false },
  payments: [{ amount: Number, date: Date }],
});

const User = mongoose.model('User', UserSchema);

// API Endpoints

// User Registration
app.post('/register', async (req, res) => {
  const { name, email, password } = req.body;
  const user = new User({ name, email, password });
  await user.save();
  res.status(201).send('User registered');
});

// User Login
app.post('/login', async (req, res) => {
  const { email, password } = req.body;
  const user = await User.findOne({ email, password });
  if (user && user.approved) {
    // Generate JWT token
    res.status(200).send('Login successful');
  } else {
    res.status(403).send('Login failed or account not approved');
  }
});

// Admin Approval
app.post('/approve/:userId', async (req, res) => {
  const user = await User.findById(req.params.userId);
  user.approved = true;
  await user.save();
  res.status(200).send('User approved');
});

// Track Payment Progress
app.get('/payments/:userId', async (req, res) => {
  const user = await User.findById(req.params.userId);
  res.status(200).json(user.payments);
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});
Leave a Comment