Skip to content

Latest commit

Β 

History

4 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Rafeeq Logo

Rafeeq Backend - Educational Platform API

A robust Node.js/Express backend API for the Rafeeq educational platform, providing authentication, course management, resource handling, and integration with external services.

Node.js Express MongoDB JWT

πŸš€ Features

  • User Authentication: JWT-based authentication with secure password hashing
  • Course Management: Create, update, and manage educational courses
  • Classroom Operations: Virtual classroom management and student enrollment
  • Resource Management: Upload, share, and organize educational resources
  • MongoDB Integration: Efficient data storage with Mongoose ODM
  • RESTful API: Clean, documented endpoints following REST principles
  • Error Handling: Comprehensive error handling and validation
  • CORS Support: Configured for cross-origin requests
  • Docker Support: Containerized deployment with Docker Compose

πŸ›  Tech Stack

  • Runtime: Node.js (v18+)
  • Framework: Express.js
  • Database: MongoDB with Mongoose ODM
  • Authentication: JWT (jsonwebtoken) + bcryptjs
  • File Upload: Multer
  • Validation: Express-validator
  • Environment: dotenv
  • Containerization: Docker & Docker Compose

πŸ“‹ Prerequisites

  • Node.js (v18 or higher)
  • MongoDB (v6 or higher) or MongoDB Atlas account
  • npm or yarn
  • Docker & Docker Compose (optional)

πŸ”§ Installation

Standard Installation

  1. Clone the repository
git clone https://github.com/Rafeeq-dz/Rafeeq-Backend.git
cd Rafeeq-Backend/server
  1. Install dependencies
npm install
  1. Set up environment variables

Create a .env file in the server directory:

# Server Configuration
PORT=5000
NODE_ENV=development

# Database
MONGODB_URI=mongodb://localhost:27017/rafeeq
# Or use MongoDB Atlas:
# MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/rafeeq?retryWrites=true&w=majority

# JWT Configuration
JWT_SECRET=your_super_secret_jwt_key_here_change_in_production
JWT_EXPIRE=7d

# CORS Configuration
CLIENT_URL=http://localhost:5173

# File Upload Configuration
MAX_FILE_SIZE=52428800
UPLOAD_PATH=./uploads

# AI Service (if using external AI API)
AI_API_URL=https://your-ai-api-url.ngrok-free.dev
AI_API_KEY=your_ai_api_key_here
  1. Start MongoDB (if running locally)
# macOS with Homebrew
brew services start mongodb-community

# Linux with systemd
sudo systemctl start mongod

# Windows
net start MongoDB
  1. Start the development server
npm run dev

The API will be available at http://localhost:5000

Docker Installation

  1. Using Docker Compose (Recommended)
cd server
docker-compose up -d

This will start:

  • MongoDB container on port 27017
  • Node.js API container on port 5000
  1. Build and run manually
# Build the image
docker build -t rafeeq-backend .

# Run the container
docker run -p 5000:5000 --env-file .env rafeeq-backend

πŸ“ Project Structure

server/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ config/              # Configuration files
β”‚   β”‚   └── db.js           # MongoDB connection
β”‚   β”œβ”€β”€ controllers/         # Route controllers
β”‚   β”‚   β”œβ”€β”€ authController.js
β”‚   β”‚   β”œβ”€β”€ courseController.js
β”‚   β”‚   β”œβ”€β”€ classroomController.js
β”‚   β”‚   └── resourceController.js
β”‚   β”œβ”€β”€ middleware/          # Custom middleware
β”‚   β”‚   β”œβ”€β”€ authMiddleware.js    # JWT authentication
β”‚   β”‚   └── errorHandler.js      # Global error handling
β”‚   β”œβ”€β”€ models/              # Mongoose models
β”‚   β”‚   β”œβ”€β”€ User.js
β”‚   β”‚   β”œβ”€β”€ Course.js
β”‚   β”‚   β”œβ”€β”€ Classroom.js
β”‚   β”‚   └── Resource.js
β”‚   β”œβ”€β”€ routes/              # API routes
β”‚   β”‚   β”œβ”€β”€ authRoutes.js
β”‚   β”‚   β”œβ”€β”€ courseRoutes.js
β”‚   β”‚   β”œβ”€β”€ classroomRoutes.js
β”‚   β”‚   └── resourceRoutes.js
β”‚   β”œβ”€β”€ app.js               # Express app setup
β”‚   └── server.js            # Server entry point
β”œβ”€β”€ uploads/                 # File upload directory
β”œβ”€β”€ .env                     # Environment variables
β”œβ”€β”€ .gitignore
β”œβ”€β”€ docker-compose.yml       # Docker Compose configuration
β”œβ”€β”€ Dockerfile               # Docker container definition
β”œβ”€β”€ package.json             # Dependencies and scripts
└── README.md

🎯 Available Scripts

# Development
npm run dev              # Start with nodemon (auto-reload)
npm start               # Start production server

# Docker
docker-compose up -d    # Start with Docker Compose
docker-compose down     # Stop containers
docker-compose logs -f  # View logs

# Database
npm run db:seed         # Seed database (if script exists)
npm run db:reset        # Reset database (if script exists)

πŸ”‘ API Endpoints

Authentication Routes (/api/auth)

Register User

POST /api/auth/register
Content-Type: application/json

{
  "name": "Ahmed Benali",
  "email": "ahmed@example.com",
  "password": "SecurePass123!",
  "specialty": "Computer Science",
  "year": 2
}

Response: {
  "success": true,
  "token": "jwt_token_here",
  "user": {
    "id": "user_id",
    "name": "Ahmed Benali",
    "email": "ahmed@example.com"
  }
}

Login

POST /api/auth/login
Content-Type: application/json

{
  "email": "ahmed@example.com",
  "password": "SecurePass123!"
}

Response: {
  "success": true,
  "token": "jwt_token_here",
  "user": {...}
}

Get Current User

GET /api/auth/me
Authorization: Bearer jwt_token_here

Response: {
  "success": true,
  "user": {...}
}

Course Routes (/api/courses)

Get All Courses

GET /api/courses
Authorization: Bearer jwt_token_here

Response: {
  "success": true,
  "count": 10,
  "courses": [...]
}

Get Single Course

GET /api/courses/:id
Authorization: Bearer jwt_token_here

Response: {
  "success": true,
  "course": {...}
}

Create Course

POST /api/courses
Authorization: Bearer jwt_token_here
Content-Type: application/json

{
  "title": "Introduction to Algorithms",
  "description": "Learn fundamental algorithms and data structures",
  "instructor": "Dr. Karim",
  "duration": "12 weeks",
  "level": "Intermediate"
}

Response: {
  "success": true,
  "course": {...}
}

Enroll in Course

POST /api/courses/:id/enroll
Authorization: Bearer jwt_token_here

Response: {
  "success": true,
  "message": "Enrolled successfully"
}

Classroom Routes (/api/classrooms)

Get All Classrooms

GET /api/classrooms
Authorization: Bearer jwt_token_here

Response: {
  "success": true,
  "classrooms": [...]
}

Create Classroom

POST /api/classrooms
Authorization: Bearer jwt_token_here
Content-Type: application/json

{
  "name": "CS301 - Data Structures",
  "description": "Advanced data structures course",
  "capacity": 30
}

Response: {
  "success": true,
  "classroom": {...}
}

Join Classroom

POST /api/classrooms/:id/join
Authorization: Bearer jwt_token_here

Response: {
  "success": true,
  "message": "Joined classroom successfully"
}

Resource Routes (/api/resources)

Get All Resources

GET /api/resources
Authorization: Bearer jwt_token_here

Response: {
  "success": true,
  "resources": [...]
}

Upload Resource

POST /api/resources
Authorization: Bearer jwt_token_here
Content-Type: multipart/form-data

FormData:
- file: [file]
- title: "Linear Algebra Notes"
- subject: "Mathematics"
- type: "Course Materials"
- description: "Comprehensive notes on linear algebra"

Response: {
  "success": true,
  "resource": {...}
}

Share Resource

POST /api/resources/:id/share
Authorization: Bearer jwt_token_here
Content-Type: application/json

{
  "userIds": ["user_id_1", "user_id_2"]
}

Response: {
  "success": true,
  "message": "Resource shared successfully"
}

πŸ—„ Database Models

User Model

{
  name: String (required),
  email: String (required, unique),
  password: String (required, hashed),
  specialty: String,
  year: Number,
  role: String (default: 'student'),
  enrolledCourses: [CourseId],
  classrooms: [ClassroomId],
  createdAt: Date,
  updatedAt: Date
}

Course Model

{
  title: String (required),
  description: String,
  instructor: String,
  duration: String,
  level: String,
  enrolledStudents: [UserId],
  resources: [ResourceId],
  createdBy: UserId,
  createdAt: Date,
  updatedAt: Date
}

Classroom Model

{
  name: String (required),
  description: String,
  capacity: Number,
  students: [UserId],
  teacher: UserId,
  resources: [ResourceId],
  createdAt: Date,
  updatedAt: Date
}

Resource Model

{
  title: String (required),
  type: String (required),
  subject: String,
  description: String,
  fileUrl: String,
  externalUrl: String,
  uploadedBy: UserId,
  sharedWith: [UserId],
  tags: [String],
  downloads: Number,
  createdAt: Date,
  updatedAt: Date
}

πŸ” Authentication Middleware

The authMiddleware.js protects routes by verifying JWT tokens:

// Usage in routes
router.get('/protected', authMiddleware, controller)

How it works:

  1. Extracts token from Authorization: Bearer <token> header
  2. Verifies token with JWT_SECRET
  3. Attaches user object to req.user
  4. Returns 401 if token is invalid or missing

πŸ›‘ Error Handling

Global error handler in middleware/errorHandler.js:

{
  success: false,
  error: "Error message here",
  stack: "Stack trace (dev mode only)"
}

Error Types:

  • 400: Bad Request (validation errors)
  • 401: Unauthorized (authentication required)
  • 403: Forbidden (insufficient permissions)
  • 404: Not Found (resource doesn't exist)
  • 500: Internal Server Error

πŸ”§ Configuration

MongoDB Connection

Local MongoDB:

MONGODB_URI=mongodb://localhost:27017/rafeeq

MongoDB Atlas:

MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/rafeeq

Connection Options (in config/db.js):

{
  useNewUrlParser: true,
  useUnifiedTopology: true,
  serverSelectionTimeoutMS: 5000
}

CORS Configuration

Configure allowed origins in app.js:

cors({
  origin: process.env.CLIENT_URL || 'http://localhost:5173',
  credentials: true
})

File Upload Configuration

Configure in app.js:

multer({
  storage: diskStorage({
    destination: './uploads/',
    filename: (req, file, cb) => {
      cb(null, `${Date.now()}-${file.originalname}`)
    }
  }),
  limits: { fileSize: 52428800 }, // 50MB
  fileFilter: (req, file, cb) => {
    // Validate file types
  }
})

πŸš€ Deployment

Environment Setup

Production Environment Variables:

NODE_ENV=production
PORT=5000
MONGODB_URI=your_production_mongodb_uri
JWT_SECRET=strong_random_secret_here
CLIENT_URL=https://your-frontend-domain.com

Deployment Platforms

Heroku:

heroku login
heroku create rafeeq-backend
git push heroku main
heroku config:set MONGODB_URI=your_mongodb_uri
heroku config:set JWT_SECRET=your_jwt_secret

DigitalOcean:

  1. Create a Droplet (Ubuntu 22.04)
  2. Install Node.js and MongoDB
  3. Clone repository
  4. Set up environment variables
  5. Use PM2 for process management
npm install -g pm2
pm2 start src/server.js --name rafeeq-backend
pm2 startup
pm2 save

AWS EC2:

  1. Launch EC2 instance
  2. Configure security groups (port 5000, 27017)
  3. Install Node.js and MongoDB
  4. Deploy with PM2 or Docker

Docker Deployment:

docker-compose -f docker-compose.prod.yml up -d

πŸ§ͺ Testing

# Run tests (when implemented)
npm test

# Run tests with coverage
npm run test:coverage

# Integration tests
npm run test:integration

πŸ” Monitoring & Logging

Production Logging:

// Add logging middleware
const morgan = require('morgan');
app.use(morgan('combined'));

Error Tracking:

  • Integrate Sentry for error tracking
  • Set up application monitoring (PM2, New Relic)
  • Configure database monitoring

🀝 Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/NewEndpoint)
  3. Commit your changes (git commit -m 'Add new endpoint')
  4. Push to the branch (git push origin feature/NewEndpoint)
  5. Open a Pull Request

Code Standards:

  • Use ES6+ features
  • Follow REST conventions
  • Add JSDoc comments
  • Validate all inputs
  • Handle errors properly

πŸ› Known Issues

  • None at the moment

πŸ“ Environment Variables Reference

Variable Description Required Default
PORT Server port No 5000
MONGODB_URI MongoDB connection string Yes -
JWT_SECRET Secret key for JWT Yes -
JWT_EXPIRE JWT expiration time No 7d
NODE_ENV Environment mode No development
CLIENT_URL Frontend URL for CORS No http://localhost:5173
MAX_FILE_SIZE Max upload size in bytes No 52428800

πŸ”§ Troubleshooting

MongoDB Connection Error:

# Check if MongoDB is running
mongosh
# Or for MongoDB Atlas, verify connection string

Port Already in Use:

# Kill process on port 5000
lsof -ti:5000 | xargs kill -9

JWT Errors:

  • Verify JWT_SECRET is set
  • Check token expiration
  • Ensure correct token format: Bearer <token>

File Upload Errors:

  • Check upload directory permissions
  • Verify file size limits
  • Ensure correct file types

πŸ“ž Support

For support, email support@rafeeq.dz or open an issue on GitHub.

πŸ“„ License

This project is proprietary and confidential. Β© 2025 Rafeeq Platform. All rights reserved.

πŸ™ Acknowledgments

  • Express.js - Fast, unopinionated web framework
  • MongoDB - Flexible document database
  • Mongoose - Elegant MongoDB object modeling
  • JWT - Secure authentication standard
  • All Contributors - For testing and feedback

Built with ❀️ for Algerian Students

Last Updated: December 20, 2025

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages