Skip to content

Latest commit

Β 

History

14 Commits

Folders and files

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

Repository files navigation

Safe Ride Backend API

Complete backend server for the Safe Ride Accident Detection System with real-time emergency alerts.

πŸš€ Features

  • βœ… Express.js REST API
  • βœ… MongoDB for data storage
  • βœ… Socket.IO for real-time bidirectional communication
  • βœ… Firebase Cloud Messaging (FCM) for push notifications
  • βœ… Twilio SMS fallback
  • βœ… Redis support (optional)
  • βœ… Rate limiting
  • βœ… Authentication middleware
  • βœ… Error handling

πŸ“‹ Prerequisites

  • Node.js >= 18.0.0
  • MongoDB (local or Atlas)
  • Firebase project (for FCM)
  • Twilio account (for SMS fallback)
  • Redis (optional, for session management)

πŸ› οΈ Installation

1. Install dependencies

cd backend
npm install

2. Setup MongoDB

Option A: Local MongoDB

# Install MongoDB on your system
# Windows: https://www.mongodb.com/try/download/community
# Mac: brew install mongodb-community
# Linux: sudo apt-get install mongodb

# Start MongoDB
mongod

Option B: MongoDB Atlas (Cloud)

  1. Go to https://www.mongodb.com/cloud/atlas
  2. Create a free cluster
  3. Get your connection string
  4. Update .env file

3. Setup Firebase

  1. Go to Firebase Console: https://console.firebase.google.com
  2. Select your project: alpha-flutter-health
  3. Go to Project Settings > Service Accounts
  4. Click "Generate new private key"
  5. Save the JSON file as firebase-service-account.json in the backend/ folder

4. Configure Environment Variables

cp .env.example .env

Edit .env and update:

NODE_ENV=development
PORT=5000

# MongoDB - Update this
MONGODB_URI=mongodb://localhost:27017/safe_ride

# JWT Secret - Change this!
JWT_SECRET=your_very_secret_key_change_this

# Firebase
FIREBASE_PROJECT_ID=alpha-flutter-health
FIREBASE_PRIVATE_KEY_PATH=./firebase-service-account.json



## πŸš€ Running the Server

### Development Mode
```bash
npm run dev

Production Mode

npm start

Server will start on: http://localhost:5000

πŸ“‘ API Endpoints

User Endpoints

Register/Login

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

{
  "phoneNumber": "+916261795658",
  "name": "John Doe",
  "fcmToken": "firebase_token_here"
}

Get Profile

GET /api/users/profile
x-user-id: user_id_here

Add Emergency Contact

POST /api/users/emergency-contacts
x-user-id: user_id_here
Content-Type: application/json

{
  "phoneNumber": "+919876543210",
  "name": "Jane Doe",
  "relationship": "Wife",
  "isPrimary": true
}

Update Settings

PUT /api/users/settings
x-user-id: user_id_here
Content-Type: application/json

{
  "autoSendAlert": true,
  "alertCountdown": 15,
  "shareLocation": true,
  "sendSMSFallback": true
}

Alert Endpoints

Create Alert

POST /api/alerts
x-user-id: user_id_here
Content-Type: application/json

{
  "magnitude": 75,
  "latitude": 23.2599,
  "longitude": 77.4126,
  "address": "Bhopal, MP",
  "deviceInfo": "Samsung M556B",
  "bluetoothDevice": "HC-05"
}

Cancel Alert

POST /api/alerts/:alertId/cancel
x-user-id: user_id_here

Get Alert History

GET /api/alerts?page=1&limit=20
x-user-id: user_id_here

πŸ”Œ Socket.IO Events

Client β†’ Server

Authenticate

socket.emit('authenticate', {
  userId: 'user_id_here',
  phoneNumber: '+916261795658'
});

Create Emergency

socket.emit('emergency:create', {
  magnitude: 80,
  latitude: 23.2599,
  longitude: 77.4126
});

Update Location

socket.emit('location:update', {
  latitude: 23.2599,
  longitude: 77.4126,
  alertId: 'alert_id_if_active'
});

Cancel Emergency

socket.emit('emergency:cancel', {
  alertId: 'alert_id_here'
});

Server β†’ Client

Authentication Success

socket.on('authenticated', (data) => {
  console.log('Authenticated:', data);
});

Emergency Alert Received

socket.on('emergency:alert', (data) => {
  console.log('Emergency Alert:', data);
  // data contains: alertId, severity, latitude, longitude, userPhoneNumber, userName
});

Alert Countdown Started

socket.on('alert:countdown_started', (data) => {
  console.log('Countdown started:', data.countdown);
});

Alert Sent

socket.on('alert:sent', (data) => {
  console.log('Alert sent to emergency contacts');
});

Alert Cancelled

socket.on('emergency:cancelled', (data) => {
  console.log('Alert was cancelled');
});

Location Update

socket.on('emergency:location_update', (data) => {
  console.log('Location updated:', data.latitude, data.longitude);
});

πŸ—„οΈ Database Schema

User

  • phoneNumber: String (unique)
  • name: String
  • fcmToken: String
  • emergencyContacts: Array
  • settings: Object
  • isOnline: Boolean
  • socketId: String

AccidentAlert

  • userId: ObjectId
  • severity: String (minor, moderate, severe, critical)
  • magnitude: Number
  • location: Object {latitude, longitude, address}
  • status: String (pending, cancelled, sent, acknowledged, resolved)
  • notificationsSent: Array
  • metadata: Object

πŸ§ͺ Testing with Postman

  1. Import the API endpoints into Postman
  2. Register a user: POST /api/users/register
  3. Copy the returned userId
  4. Add emergency contacts
  5. Create an alert
  6. Check MongoDB to see the data

πŸ” Testing Socket.IO

Use https://www.websocket.org/echo.html or Socket.IO client:

const socket = io('http://localhost:5000');

socket.on('connect', () => {
  console.log('Connected');
  
  socket.emit('authenticate', {
    phoneNumber: '+916261795658'
  });
});

socket.on('authenticated', (data) => {
  console.log('Authenticated:', data);
});

πŸ“¦ Project Structure

backend/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ config/           # Configuration files
β”‚   β”œβ”€β”€ controllers/      # Route controllers
β”‚   β”œβ”€β”€ models/          # MongoDB models
β”‚   β”œβ”€β”€ routes/          # API routes
β”‚   β”œβ”€β”€ services/        # Business logic
β”‚   β”œβ”€β”€ middleware/      # Custom middleware
β”‚   β”œβ”€β”€ socket/          # Socket.IO handlers
β”‚   └── server.js        # Main server file
β”œβ”€β”€ package.json
β”œβ”€β”€ .env
└── README.md

πŸ› Troubleshooting

MongoDB Connection Error

  • Make sure MongoDB is running: mongod
  • Check connection string in .env

Firebase Error

  • Ensure firebase-service-account.json is in the backend folder
  • Check file path in .env

Socket.IO Not Connecting

  • Check CORS settings
  • Verify port is not in use
  • Check firewall settings

πŸ“ License

MIT

πŸ‘¨β€πŸ’» Author

Safe Ride Team

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages