Set up backend API server with Express and Prisma
- Initialize Node.js/Express backend project structure - Configure TypeScript for backend development - Set up Prisma ORM with MySQL database schema - Implement authentication middleware with Clerk - Create photo upload endpoint with EXIF extraction - Build report CRUD endpoints (create, read, delete) - Add file upload handling with Multer - Configure CORS and security middleware (helmet) - Set up error handling and validation - Create development environment configuration Task 21 complete: Backend foundation ready for report submissions
This commit is contained in:
14
server/.env.example
Normal file
14
server/.env.example
Normal file
@@ -0,0 +1,14 @@
|
||||
# Database
|
||||
DATABASE_URL="mysql://beach_litter_user:BeachClean2024!@192.168.4.20:3306/beach_litter_mapping"
|
||||
|
||||
# Clerk Authentication
|
||||
CLERK_SECRET_KEY="sk_test_your_secret_key_here"
|
||||
CLERK_WEBHOOK_SECRET="whsec_your_webhook_secret_here"
|
||||
|
||||
# Server
|
||||
PORT=3000
|
||||
NODE_ENV=development
|
||||
|
||||
# File Upload
|
||||
UPLOAD_DIR=./uploads
|
||||
MAX_FILE_SIZE=5242880
|
||||
26
server/.gitignore
vendored
Normal file
26
server/.gitignore
vendored
Normal file
@@ -0,0 +1,26 @@
|
||||
# Dependencies
|
||||
node_modules/
|
||||
|
||||
# Environment variables
|
||||
.env
|
||||
.env.local
|
||||
|
||||
# Build output
|
||||
dist/
|
||||
|
||||
# Uploads
|
||||
uploads/
|
||||
|
||||
# Logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# IDE
|
||||
.vscode/
|
||||
.idea/
|
||||
*.swp
|
||||
*.swo
|
||||
56
server/README.md
Normal file
56
server/README.md
Normal file
@@ -0,0 +1,56 @@
|
||||
# Beach Litter Mapping API
|
||||
|
||||
Backend API server for the Beach Litter Mapping Platform.
|
||||
|
||||
## Setup
|
||||
|
||||
1. Install dependencies:
|
||||
```bash
|
||||
cd server
|
||||
npm install
|
||||
```
|
||||
|
||||
2. Configure environment variables:
|
||||
```bash
|
||||
cp .env.example .env
|
||||
# Edit .env with your configuration
|
||||
```
|
||||
|
||||
3. Set up the database:
|
||||
```bash
|
||||
npm run prisma:generate
|
||||
npm run prisma:migrate
|
||||
```
|
||||
|
||||
4. Start the development server:
|
||||
```bash
|
||||
npm run dev
|
||||
```
|
||||
|
||||
The API will be available at `http://localhost:3000`
|
||||
|
||||
## API Endpoints
|
||||
|
||||
### Reports
|
||||
|
||||
- `POST /api/reports/upload` - Upload a photo (requires auth)
|
||||
- `POST /api/reports` - Create a new report (requires auth)
|
||||
- `GET /api/reports` - Get all reports (with optional filters)
|
||||
- `GET /api/reports/:id` - Get a single report
|
||||
- `DELETE /api/reports/:id` - Delete a report (requires auth, owner only)
|
||||
|
||||
### Health Check
|
||||
|
||||
- `GET /health` - Server health status
|
||||
|
||||
## Environment Variables
|
||||
|
||||
See `.env.example` for required environment variables.
|
||||
|
||||
## Database
|
||||
|
||||
The API uses MySQL 8.0+ with Prisma ORM. Connection details are configured in the `.env` file.
|
||||
|
||||
## Authentication
|
||||
|
||||
Authentication is handled by Clerk. Protected endpoints require a Bearer token in the Authorization header.
|
||||
2220
server/package-lock.json
generated
Normal file
2220
server/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
38
server/package.json
Normal file
38
server/package.json
Normal file
@@ -0,0 +1,38 @@
|
||||
{
|
||||
"name": "beach-litter-api",
|
||||
"version": "1.0.0",
|
||||
"description": "Backend API for Beach Litter Mapping Platform",
|
||||
"main": "dist/index.js",
|
||||
"scripts": {
|
||||
"dev": "tsx watch src/index.ts",
|
||||
"build": "tsc",
|
||||
"start": "node dist/index.js",
|
||||
"prisma:generate": "prisma generate",
|
||||
"prisma:migrate": "prisma migrate dev",
|
||||
"prisma:studio": "prisma studio"
|
||||
},
|
||||
"keywords": ["beach", "litter", "environment", "api"],
|
||||
"author": "",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@clerk/clerk-sdk-node": "^5.0.0",
|
||||
"@prisma/client": "^5.22.0",
|
||||
"cors": "^2.8.5",
|
||||
"dotenv": "^16.4.5",
|
||||
"express": "^4.21.1",
|
||||
"express-validator": "^7.2.0",
|
||||
"exifr": "^7.1.3",
|
||||
"helmet": "^8.0.0",
|
||||
"multer": "^1.4.5-lts.1",
|
||||
"zod": "^3.23.8"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/cors": "^2.8.17",
|
||||
"@types/express": "^5.0.0",
|
||||
"@types/multer": "^1.4.12",
|
||||
"@types/node": "^22.9.0",
|
||||
"prisma": "^5.22.0",
|
||||
"tsx": "^4.19.2",
|
||||
"typescript": "^5.6.3"
|
||||
}
|
||||
}
|
||||
192
server/prisma/schema.prisma
Normal file
192
server/prisma/schema.prisma
Normal file
@@ -0,0 +1,192 @@
|
||||
generator client {
|
||||
provider = "prisma-client-js"
|
||||
}
|
||||
|
||||
datasource db {
|
||||
provider = "mysql"
|
||||
url = env("DATABASE_URL")
|
||||
}
|
||||
|
||||
model User {
|
||||
id String @id @default(dbgenerated("(uuid())")) @db.VarChar(36)
|
||||
email String @unique(map: "email") @db.VarChar(255)
|
||||
password_hash String @db.VarChar(255)
|
||||
username String @unique(map: "username") @db.VarChar(100)
|
||||
createdAt DateTime? @default(now()) @map("created_at") @db.Timestamp(0)
|
||||
updatedAt DateTime? @default(now()) @updatedAt @map("updated_at") @db.Timestamp(0)
|
||||
firstName String? @map("first_name") @db.VarChar(100)
|
||||
lastName String? @map("last_name") @db.VarChar(100)
|
||||
avatarUrl String? @map("avatar_url") @db.VarChar(500)
|
||||
impactScore Int? @default(0) @map("impact_score")
|
||||
notificationEmail Boolean? @default(true) @map("notification_email")
|
||||
notificationInApp Boolean? @default(true) @map("notification_in_app")
|
||||
areasOfInterest Json? @map("areas_of_interest")
|
||||
eventRegistrations EventRegistration[]
|
||||
organizedEvents Event[] @relation("EventOrganizer")
|
||||
reports Report[]
|
||||
verifications Verification[]
|
||||
|
||||
@@index([email], map: "idx_email")
|
||||
@@index([username], map: "idx_username")
|
||||
@@map("users")
|
||||
}
|
||||
|
||||
model Report {
|
||||
id String @id @default(dbgenerated("(uuid())")) @db.VarChar(36)
|
||||
userId String @map("user_id") @db.VarChar(36)
|
||||
location Unsupported("point")
|
||||
latitude Decimal @db.Decimal(10, 8)
|
||||
longitude Decimal @db.Decimal(11, 8)
|
||||
locationSource reports_location_source @map("location_source")
|
||||
photoUrls Json @map("photo_urls")
|
||||
photoTimestamp DateTime? @map("photo_timestamp") @db.Timestamp(0)
|
||||
litterType reports_litter_type @map("litter_type")
|
||||
quantity reports_quantity
|
||||
description String? @db.Text
|
||||
createdAt DateTime? @default(now()) @map("created_at") @db.Timestamp(0)
|
||||
updatedAt DateTime? @default(now()) @updatedAt @map("updated_at") @db.Timestamp(0)
|
||||
submittedAt DateTime? @default(now()) @map("submitted_at") @db.Timestamp(0)
|
||||
verificationStatus reports_verification_status? @default(pending) @map("verification_status")
|
||||
environmentalConcerns EnvironmentalConcern[]
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade, onUpdate: NoAction, map: "reports_ibfk_1")
|
||||
verifications Verification[]
|
||||
|
||||
@@index([createdAt], map: "idx_created_at")
|
||||
@@index([latitude, longitude], map: "idx_lat_lng")
|
||||
@@index([litterType], map: "idx_litter_type")
|
||||
@@index([location(length: 32)], map: "idx_location")
|
||||
@@index([userId], map: "user_id")
|
||||
@@map("reports")
|
||||
}
|
||||
|
||||
model Event {
|
||||
id String @id @default(dbgenerated("(uuid())")) @db.VarChar(36)
|
||||
organizerId String @map("organizer_id") @db.VarChar(36)
|
||||
title String @db.VarChar(255)
|
||||
description String @db.Text
|
||||
location Unsupported("point")
|
||||
latitude Decimal @db.Decimal(10, 8)
|
||||
longitude Decimal @db.Decimal(11, 8)
|
||||
locationName String @map("location_name") @db.VarChar(255)
|
||||
scheduledDate DateTime @map("scheduled_date") @db.Timestamp(0)
|
||||
duration Int
|
||||
status events_status? @default(upcoming)
|
||||
participantCount Int? @default(0) @map("participant_count")
|
||||
litterCollected Decimal? @map("litter_collected") @db.Decimal(10, 2)
|
||||
photos Json?
|
||||
createdAt DateTime? @default(now()) @map("created_at") @db.Timestamp(0)
|
||||
updatedAt DateTime? @default(now()) @updatedAt @map("updated_at") @db.Timestamp(0)
|
||||
registrations EventRegistration[]
|
||||
organizer User @relation("EventOrganizer", fields: [organizerId], references: [id], onDelete: Cascade, onUpdate: NoAction, map: "events_ibfk_1")
|
||||
|
||||
@@index([location(length: 32)], map: "idx_location")
|
||||
@@index([scheduledDate], map: "idx_scheduled_date")
|
||||
@@index([status], map: "idx_status")
|
||||
@@index([organizerId], map: "organizer_id")
|
||||
@@map("events")
|
||||
}
|
||||
|
||||
model EventRegistration {
|
||||
id String @id @default(dbgenerated("(uuid())")) @db.VarChar(36)
|
||||
userId String @map("user_id") @db.VarChar(36)
|
||||
eventId String @map("event_id") @db.VarChar(36)
|
||||
registeredAt DateTime? @default(now()) @map("registered_at") @db.Timestamp(0)
|
||||
attended Boolean? @default(false)
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade, onUpdate: NoAction, map: "event_registrations_ibfk_1")
|
||||
event Event @relation(fields: [eventId], references: [id], onDelete: Cascade, onUpdate: NoAction, map: "event_registrations_ibfk_2")
|
||||
|
||||
@@unique([userId, eventId], map: "unique_user_event")
|
||||
@@index([eventId], map: "event_id")
|
||||
@@map("event_registrations")
|
||||
}
|
||||
|
||||
model Verification {
|
||||
id String @id @default(dbgenerated("(uuid())")) @db.VarChar(36)
|
||||
reportId String @map("report_id") @db.VarChar(36)
|
||||
userId String @map("user_id") @db.VarChar(36)
|
||||
verificationType verifications_verification_type @map("verification_type")
|
||||
comment String? @db.Text
|
||||
createdAt DateTime? @default(now()) @map("created_at") @db.Timestamp(0)
|
||||
report Report @relation(fields: [reportId], references: [id], onDelete: Cascade, onUpdate: NoAction, map: "verifications_ibfk_1")
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade, onUpdate: NoAction, map: "verifications_ibfk_2")
|
||||
|
||||
@@unique([reportId, userId], map: "unique_report_user")
|
||||
@@index([userId], map: "user_id")
|
||||
@@map("verifications")
|
||||
}
|
||||
|
||||
model EnvironmentalConcern {
|
||||
id String @id @default(dbgenerated("(uuid())")) @db.VarChar(36)
|
||||
reportId String @map("report_id") @db.VarChar(36)
|
||||
concernType String @map("concern_type") @db.VarChar(100)
|
||||
severity environmental_concerns_severity
|
||||
description String @db.Text
|
||||
createdAt DateTime? @default(now()) @map("created_at") @db.Timestamp(0)
|
||||
report Report @relation(fields: [reportId], references: [id], onDelete: Cascade, onUpdate: NoAction, map: "environmental_concerns_ibfk_1")
|
||||
|
||||
@@index([concernType], map: "idx_concern_type")
|
||||
@@index([reportId], map: "report_id")
|
||||
@@map("environmental_concerns")
|
||||
}
|
||||
|
||||
model Hotspot {
|
||||
id String @id @default(dbgenerated("(uuid())")) @db.VarChar(36)
|
||||
location Unsupported("point")
|
||||
latitude Decimal @db.Decimal(10, 8)
|
||||
longitude Decimal @db.Decimal(11, 8)
|
||||
radius Decimal @db.Decimal(10, 2)
|
||||
reportCount Int @map("report_count")
|
||||
severityScore Decimal @map("severity_score") @db.Decimal(5, 2)
|
||||
lastReportDate DateTime @map("last_report_date") @db.Timestamp(0)
|
||||
calculatedAt DateTime? @default(now()) @map("calculated_at") @db.Timestamp(0)
|
||||
|
||||
@@index([location(length: 32)], map: "idx_location")
|
||||
@@index([severityScore], map: "idx_severity_score")
|
||||
@@map("hotspots")
|
||||
}
|
||||
|
||||
enum verifications_verification_type {
|
||||
verify
|
||||
dispute
|
||||
}
|
||||
|
||||
enum environmental_concerns_severity {
|
||||
low
|
||||
medium
|
||||
high
|
||||
critical
|
||||
}
|
||||
|
||||
enum reports_location_source {
|
||||
exif
|
||||
gps
|
||||
manual
|
||||
}
|
||||
|
||||
enum reports_litter_type {
|
||||
plastic
|
||||
metal
|
||||
glass
|
||||
organic
|
||||
hazardous
|
||||
other
|
||||
}
|
||||
|
||||
enum reports_quantity {
|
||||
minimal
|
||||
moderate
|
||||
significant
|
||||
severe
|
||||
}
|
||||
|
||||
enum events_status {
|
||||
upcoming
|
||||
completed
|
||||
cancelled
|
||||
}
|
||||
|
||||
enum reports_verification_status {
|
||||
pending
|
||||
verified
|
||||
disputed
|
||||
}
|
||||
7
server/src/config/database.ts
Normal file
7
server/src/config/database.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
|
||||
const prisma = new PrismaClient({
|
||||
log: process.env.NODE_ENV === 'development' ? ['query', 'error', 'warn'] : ['error'],
|
||||
});
|
||||
|
||||
export default prisma;
|
||||
240
server/src/controllers/reportController.ts
Normal file
240
server/src/controllers/reportController.ts
Normal file
@@ -0,0 +1,240 @@
|
||||
import { Response } from 'express';
|
||||
import { AuthRequest } from '../middleware/auth';
|
||||
import { reportService } from '../services/reportService';
|
||||
import { extractExifData } from '../utils/exif';
|
||||
import path from 'path';
|
||||
|
||||
export class ReportController {
|
||||
async uploadPhoto(req: AuthRequest, res: Response) {
|
||||
try {
|
||||
if (!req.file) {
|
||||
return res.status(400).json({
|
||||
error: {
|
||||
code: 'NO_FILE',
|
||||
message: 'No file uploaded',
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Extract EXIF data
|
||||
const exifData = await extractExifData(req.file.path);
|
||||
|
||||
// Generate URL for the uploaded file
|
||||
const fileUrl = `/uploads/${req.file.filename}`;
|
||||
|
||||
res.json({
|
||||
url: fileUrl,
|
||||
exifData: {
|
||||
latitude: exifData.latitude,
|
||||
longitude: exifData.longitude,
|
||||
timestamp: exifData.timestamp,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error uploading photo:', error);
|
||||
res.status(500).json({
|
||||
error: {
|
||||
code: 'UPLOAD_ERROR',
|
||||
message: 'Failed to upload photo',
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async createReport(req: AuthRequest, res: Response) {
|
||||
try {
|
||||
if (!req.userId) {
|
||||
return res.status(401).json({
|
||||
error: {
|
||||
code: 'UNAUTHORIZED',
|
||||
message: 'User not authenticated',
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const {
|
||||
latitude,
|
||||
longitude,
|
||||
locationSource,
|
||||
litterType,
|
||||
quantity,
|
||||
description,
|
||||
photoUrls,
|
||||
photoTimestamp,
|
||||
environmentalConcerns,
|
||||
} = req.body;
|
||||
|
||||
// Validation
|
||||
if (!latitude || !longitude) {
|
||||
return res.status(400).json({
|
||||
error: {
|
||||
code: 'VALIDATION_ERROR',
|
||||
message: 'Latitude and longitude are required',
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (!photoUrls || photoUrls.length === 0) {
|
||||
return res.status(400).json({
|
||||
error: {
|
||||
code: 'VALIDATION_ERROR',
|
||||
message: 'At least one photo is required',
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const report = await reportService.createReport({
|
||||
userId: req.userId,
|
||||
latitude: parseFloat(latitude),
|
||||
longitude: parseFloat(longitude),
|
||||
locationSource,
|
||||
photoUrls,
|
||||
photoTimestamp: photoTimestamp ? new Date(photoTimestamp) : undefined,
|
||||
litterType,
|
||||
quantity,
|
||||
description,
|
||||
environmentalConcerns,
|
||||
});
|
||||
|
||||
res.status(201).json(report);
|
||||
} catch (error) {
|
||||
console.error('Error creating report:', error);
|
||||
res.status(500).json({
|
||||
error: {
|
||||
code: 'INTERNAL_SERVER_ERROR',
|
||||
message: 'Failed to create report',
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async getReports(req: AuthRequest, res: Response) {
|
||||
try {
|
||||
const {
|
||||
startDate,
|
||||
endDate,
|
||||
litterTypes,
|
||||
quantities,
|
||||
verificationStatus,
|
||||
north,
|
||||
south,
|
||||
east,
|
||||
west,
|
||||
} = req.query;
|
||||
|
||||
const filters: any = {};
|
||||
|
||||
if (startDate) filters.startDate = new Date(startDate as string);
|
||||
if (endDate) filters.endDate = new Date(endDate as string);
|
||||
if (litterTypes) filters.litterTypes = (litterTypes as string).split(',');
|
||||
if (quantities) filters.quantities = (quantities as string).split(',');
|
||||
if (verificationStatus) filters.verificationStatus = (verificationStatus as string).split(',');
|
||||
|
||||
if (north && south && east && west) {
|
||||
filters.bounds = {
|
||||
north: parseFloat(north as string),
|
||||
south: parseFloat(south as string),
|
||||
east: parseFloat(east as string),
|
||||
west: parseFloat(west as string),
|
||||
};
|
||||
}
|
||||
|
||||
const reports = await reportService.getReports(filters);
|
||||
res.json(reports);
|
||||
} catch (error) {
|
||||
console.error('Error fetching reports:', error);
|
||||
res.status(500).json({
|
||||
error: {
|
||||
code: 'INTERNAL_SERVER_ERROR',
|
||||
message: 'Failed to fetch reports',
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async getReportById(req: AuthRequest, res: Response) {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const report = await reportService.getReportById(id);
|
||||
|
||||
if (!report) {
|
||||
return res.status(404).json({
|
||||
error: {
|
||||
code: 'RESOURCE_NOT_FOUND',
|
||||
message: 'Report not found',
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
res.json(report);
|
||||
} catch (error) {
|
||||
console.error('Error fetching report:', error);
|
||||
res.status(500).json({
|
||||
error: {
|
||||
code: 'INTERNAL_SERVER_ERROR',
|
||||
message: 'Failed to fetch report',
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async deleteReport(req: AuthRequest, res: Response) {
|
||||
try {
|
||||
if (!req.userId) {
|
||||
return res.status(401).json({
|
||||
error: {
|
||||
code: 'UNAUTHORIZED',
|
||||
message: 'User not authenticated',
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const { id } = req.params;
|
||||
await reportService.deleteReport(id, req.userId);
|
||||
|
||||
res.status(204).send();
|
||||
} catch (error: any) {
|
||||
console.error('Error deleting report:', error);
|
||||
|
||||
if (error.message === 'Report not found') {
|
||||
return res.status(404).json({
|
||||
error: {
|
||||
code: 'RESOURCE_NOT_FOUND',
|
||||
message: 'Report not found',
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (error.message === 'Unauthorized to delete this report') {
|
||||
return res.status(403).json({
|
||||
error: {
|
||||
code: 'FORBIDDEN',
|
||||
message: 'You are not authorized to delete this report',
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
res.status(500).json({
|
||||
error: {
|
||||
code: 'INTERNAL_SERVER_ERROR',
|
||||
message: 'Failed to delete report',
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const reportController = new ReportController();
|
||||
66
server/src/index.ts
Normal file
66
server/src/index.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
import express from 'express';
|
||||
import cors from 'cors';
|
||||
import helmet from 'helmet';
|
||||
import dotenv from 'dotenv';
|
||||
import path from 'path';
|
||||
import reportRoutes from './routes/reportRoutes';
|
||||
|
||||
// Load environment variables
|
||||
dotenv.config();
|
||||
|
||||
const app = express();
|
||||
const PORT = process.env.PORT || 3000;
|
||||
|
||||
// Middleware
|
||||
app.use(helmet());
|
||||
app.use(cors({
|
||||
origin: process.env.CORS_ORIGIN || 'http://localhost:5173',
|
||||
credentials: true,
|
||||
}));
|
||||
app.use(express.json());
|
||||
app.use(express.urlencoded({ extended: true }));
|
||||
|
||||
// Serve uploaded files
|
||||
app.use('/uploads', express.static(path.join(__dirname, '../uploads')));
|
||||
|
||||
// Health check
|
||||
app.get('/health', (req, res) => {
|
||||
res.json({ status: 'ok', timestamp: new Date().toISOString() });
|
||||
});
|
||||
|
||||
// API Routes
|
||||
app.use('/api/reports', reportRoutes);
|
||||
|
||||
// Error handling middleware
|
||||
app.use((err: any, req: express.Request, res: express.Response, next: express.NextFunction) => {
|
||||
console.error('Error:', err);
|
||||
|
||||
if (err.name === 'MulterError') {
|
||||
if (err.code === 'LIMIT_FILE_SIZE') {
|
||||
return res.status(400).json({
|
||||
error: {
|
||||
code: 'FILE_TOO_LARGE',
|
||||
message: 'File size exceeds the maximum limit of 5MB',
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
res.status(500).json({
|
||||
error: {
|
||||
code: 'INTERNAL_SERVER_ERROR',
|
||||
message: err.message || 'An unexpected error occurred',
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
// Start server
|
||||
app.listen(PORT, () => {
|
||||
console.log(`🚀 Server running on port ${PORT}`);
|
||||
console.log(`📍 Environment: ${process.env.NODE_ENV || 'development'}`);
|
||||
console.log(`🔗 API: http://localhost:${PORT}/api`);
|
||||
});
|
||||
|
||||
export default app;
|
||||
56
server/src/middleware/auth.ts
Normal file
56
server/src/middleware/auth.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
import { clerkClient } from '@clerk/clerk-sdk-node';
|
||||
|
||||
export interface AuthRequest extends Request {
|
||||
userId?: string;
|
||||
user?: any;
|
||||
}
|
||||
|
||||
export const requireAuth = async (
|
||||
req: AuthRequest,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
) => {
|
||||
try {
|
||||
const authHeader = req.headers.authorization;
|
||||
|
||||
if (!authHeader || !authHeader.startsWith('Bearer ')) {
|
||||
return res.status(401).json({
|
||||
error: {
|
||||
code: 'UNAUTHORIZED',
|
||||
message: 'No authorization token provided',
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const token = authHeader.substring(7);
|
||||
|
||||
// Verify the session token with Clerk
|
||||
const session = await clerkClient.sessions.verifySession(token, token);
|
||||
|
||||
if (!session) {
|
||||
return res.status(401).json({
|
||||
error: {
|
||||
code: 'INVALID_TOKEN',
|
||||
message: 'Invalid or expired token',
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Attach user ID to request
|
||||
req.userId = session.userId;
|
||||
|
||||
next();
|
||||
} catch (error) {
|
||||
console.error('Auth middleware error:', error);
|
||||
return res.status(401).json({
|
||||
error: {
|
||||
code: 'UNAUTHORIZED',
|
||||
message: 'Authentication failed',
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
||||
40
server/src/middleware/upload.ts
Normal file
40
server/src/middleware/upload.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
import multer from 'multer';
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
|
||||
// Ensure upload directory exists
|
||||
const uploadDir = process.env.UPLOAD_DIR || './uploads';
|
||||
if (!fs.existsSync(uploadDir)) {
|
||||
fs.mkdirSync(uploadDir, { recursive: true });
|
||||
}
|
||||
|
||||
// Configure storage
|
||||
const storage = multer.diskStorage({
|
||||
destination: (req, file, cb) => {
|
||||
cb(null, uploadDir);
|
||||
},
|
||||
filename: (req, file, cb) => {
|
||||
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
|
||||
cb(null, file.fieldname + '-' + uniqueSuffix + path.extname(file.originalname));
|
||||
},
|
||||
});
|
||||
|
||||
// File filter
|
||||
const fileFilter = (req: any, file: Express.Multer.File, cb: multer.FileFilterCallback) => {
|
||||
const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp'];
|
||||
|
||||
if (allowedTypes.includes(file.mimetype)) {
|
||||
cb(null, true);
|
||||
} else {
|
||||
cb(new Error('Invalid file type. Only JPEG, PNG, and WebP images are allowed.'));
|
||||
}
|
||||
};
|
||||
|
||||
// Configure multer
|
||||
export const upload = multer({
|
||||
storage,
|
||||
fileFilter,
|
||||
limits: {
|
||||
fileSize: parseInt(process.env.MAX_FILE_SIZE || '5242880'), // 5MB default
|
||||
},
|
||||
});
|
||||
17
server/src/routes/reportRoutes.ts
Normal file
17
server/src/routes/reportRoutes.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import { Router } from 'express';
|
||||
import { reportController } from '../controllers/reportController';
|
||||
import { requireAuth } from '../middleware/auth';
|
||||
import { upload } from '../middleware/upload';
|
||||
|
||||
const router = Router();
|
||||
|
||||
// Photo upload endpoint (protected)
|
||||
router.post('/upload', requireAuth, upload.single('photo'), reportController.uploadPhoto.bind(reportController));
|
||||
|
||||
// Report CRUD endpoints
|
||||
router.post('/', requireAuth, reportController.createReport.bind(reportController));
|
||||
router.get('/', reportController.getReports.bind(reportController));
|
||||
router.get('/:id', reportController.getReportById.bind(reportController));
|
||||
router.delete('/:id', requireAuth, reportController.deleteReport.bind(reportController));
|
||||
|
||||
export default router;
|
||||
168
server/src/services/reportService.ts
Normal file
168
server/src/services/reportService.ts
Normal file
@@ -0,0 +1,168 @@
|
||||
import prisma from '../config/database';
|
||||
import { Prisma } from '@prisma/client';
|
||||
|
||||
export interface CreateReportData {
|
||||
userId: string;
|
||||
latitude: number;
|
||||
longitude: number;
|
||||
locationSource: 'exif' | 'gps' | 'manual';
|
||||
photoUrls: string[];
|
||||
photoTimestamp?: Date;
|
||||
litterType: string;
|
||||
quantity: string;
|
||||
description?: string;
|
||||
environmentalConcerns?: Array<{
|
||||
type: string;
|
||||
severity: string;
|
||||
description: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
export class ReportService {
|
||||
async createReport(data: CreateReportData) {
|
||||
const report = await prisma.report.create({
|
||||
data: {
|
||||
userId: data.userId,
|
||||
latitude: new Prisma.Decimal(data.latitude),
|
||||
longitude: new Prisma.Decimal(data.longitude),
|
||||
locationSource: data.locationSource,
|
||||
photoUrls: data.photoUrls,
|
||||
photoTimestamp: data.photoTimestamp,
|
||||
litterType: data.litterType,
|
||||
quantity: data.quantity,
|
||||
description: data.description,
|
||||
environmentalConcerns: data.environmentalConcerns
|
||||
? {
|
||||
create: data.environmentalConcerns.map((concern) => ({
|
||||
concernType: concern.type,
|
||||
severity: concern.severity,
|
||||
description: concern.description,
|
||||
})),
|
||||
}
|
||||
: undefined,
|
||||
},
|
||||
include: {
|
||||
user: {
|
||||
select: {
|
||||
id: true,
|
||||
username: true,
|
||||
avatarUrl: true,
|
||||
},
|
||||
},
|
||||
environmentalConcerns: true,
|
||||
},
|
||||
});
|
||||
|
||||
return report;
|
||||
}
|
||||
|
||||
async getReports(filters?: {
|
||||
startDate?: Date;
|
||||
endDate?: Date;
|
||||
litterTypes?: string[];
|
||||
quantities?: string[];
|
||||
verificationStatus?: string[];
|
||||
bounds?: { north: number; south: number; east: number; west: number };
|
||||
}) {
|
||||
const where: any = {};
|
||||
|
||||
if (filters?.startDate || filters?.endDate) {
|
||||
where.createdAt = {};
|
||||
if (filters.startDate) where.createdAt.gte = filters.startDate;
|
||||
if (filters.endDate) where.createdAt.lte = filters.endDate;
|
||||
}
|
||||
|
||||
if (filters?.litterTypes?.length) {
|
||||
where.litterType = { in: filters.litterTypes };
|
||||
}
|
||||
|
||||
if (filters?.quantities?.length) {
|
||||
where.quantity = { in: filters.quantities };
|
||||
}
|
||||
|
||||
if (filters?.verificationStatus?.length) {
|
||||
where.verificationStatus = { in: filters.verificationStatus };
|
||||
}
|
||||
|
||||
if (filters?.bounds) {
|
||||
where.latitude = {
|
||||
gte: new Prisma.Decimal(filters.bounds.south),
|
||||
lte: new Prisma.Decimal(filters.bounds.north),
|
||||
};
|
||||
where.longitude = {
|
||||
gte: new Prisma.Decimal(filters.bounds.west),
|
||||
lte: new Prisma.Decimal(filters.bounds.east),
|
||||
};
|
||||
}
|
||||
|
||||
const reports = await prisma.report.findMany({
|
||||
where,
|
||||
include: {
|
||||
user: {
|
||||
select: {
|
||||
id: true,
|
||||
username: true,
|
||||
avatarUrl: true,
|
||||
},
|
||||
},
|
||||
environmentalConcerns: true,
|
||||
verifications: true,
|
||||
},
|
||||
orderBy: {
|
||||
createdAt: 'desc',
|
||||
},
|
||||
});
|
||||
|
||||
return reports;
|
||||
}
|
||||
|
||||
async getReportById(id: string) {
|
||||
const report = await prisma.report.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
user: {
|
||||
select: {
|
||||
id: true,
|
||||
username: true,
|
||||
avatarUrl: true,
|
||||
},
|
||||
},
|
||||
environmentalConcerns: true,
|
||||
verifications: {
|
||||
include: {
|
||||
user: {
|
||||
select: {
|
||||
id: true,
|
||||
username: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return report;
|
||||
}
|
||||
|
||||
async deleteReport(id: string, userId: string) {
|
||||
// Verify ownership
|
||||
const report = await prisma.report.findUnique({
|
||||
where: { id },
|
||||
select: { userId: true },
|
||||
});
|
||||
|
||||
if (!report) {
|
||||
throw new Error('Report not found');
|
||||
}
|
||||
|
||||
if (report.userId !== userId) {
|
||||
throw new Error('Unauthorized to delete this report');
|
||||
}
|
||||
|
||||
await prisma.report.delete({
|
||||
where: { id },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export const reportService = new ReportService();
|
||||
33
server/src/utils/exif.ts
Normal file
33
server/src/utils/exif.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import exifr from 'exifr';
|
||||
|
||||
export interface ExifData {
|
||||
latitude?: number;
|
||||
longitude?: number;
|
||||
timestamp?: Date;
|
||||
make?: string;
|
||||
model?: string;
|
||||
}
|
||||
|
||||
export async function extractExifData(filePath: string): Promise<ExifData> {
|
||||
try {
|
||||
const exif = await exifr.parse(filePath, {
|
||||
gps: true,
|
||||
pick: ['latitude', 'longitude', 'DateTimeOriginal', 'Make', 'Model'],
|
||||
});
|
||||
|
||||
if (!exif) {
|
||||
return {};
|
||||
}
|
||||
|
||||
return {
|
||||
latitude: exif.latitude,
|
||||
longitude: exif.longitude,
|
||||
timestamp: exif.DateTimeOriginal,
|
||||
make: exif.Make,
|
||||
model: exif.Model,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error extracting EXIF data:', error);
|
||||
return {};
|
||||
}
|
||||
}
|
||||
18
server/tsconfig.json
Normal file
18
server/tsconfig.json
Normal file
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "commonjs",
|
||||
"lib": ["ES2022"],
|
||||
"outDir": "./dist",
|
||||
"rootDir": "./src",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"resolveJsonModule": true,
|
||||
"moduleResolution": "node",
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"exclude": ["node_modules", "dist"]
|
||||
}
|
||||
Reference in New Issue
Block a user