-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
126 lines (111 loc) · 3.71 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
require('dotenv').config();
const express = require('express');
const mongoose = require('mongoose');
const multer = require('multer');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const cors = require('cors');
const path = require('path');
// Initialize app
const app = express();
app.use(cors());
app.use(express.json());
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));
// Health Check Route (Required for Deployment Platforms)
app.get('/', (req, res) => {
res.send('Server is running!');
});
// MongoDB Connection
mongoose
.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log('Connected to MongoDB Atlas'))
.catch((error) => console.error('MongoDB connection error:', error));
// Schemas
const reportSchema = new mongoose.Schema({
reporterName: String,
category: String,
description: String,
location: String,
date: String,
time: String,
image: String,
video: String,
});
const adminSchema = new mongoose.Schema({
username: String,
password: String,
});
const Report = mongoose.model('Report', reportSchema);
const Admin = mongoose.model('Admin', adminSchema);
// Setup multer for file uploads
const storage = multer.diskStorage({
destination: (req, file, cb) => cb(null, 'uploads/'),
filename: (req, file, cb) => cb(null, `${Date.now()}-${file.originalname}`),
});
const upload = multer({ storage });
// Seed admin account (for testing)
(async () => {
try {
const adminExists = await Admin.findOne({ username: 'admin' });
if (!adminExists) {
const hashedPassword = await bcrypt.hash('password', 10);
await Admin.create({ username: 'admin', password: hashedPassword });
console.log('Admin account created: username="admin", password="password"');
}
} catch (error) {
console.error('Error seeding admin account:', error);
}
})();
// Routes
// 1. Submit a crime report
app.post('/submit-report', upload.fields([{ name: 'image' }, { name: 'video' }]), async (req, res) => {
try {
const report = new Report({
reporterName: req.body.reporterName,
category: req.body.crimeCategory,
description: req.body.crimeDescription,
location: req.body.location,
date: req.body.date,
time: req.body.time,
image: req.files?.image?.[0]?.filename || null,
video: req.files?.video?.[0]?.filename || null,
});
await report.save();
res.status(201).json({ message: 'Report submitted successfully' });
} catch (error) {
res.status(500).json({ message: 'Error submitting report', error });
}
});
// 2. Admin login
app.post('/admin-login', async (req, res) => {
try {
const { username, password } = req.body;
const admin = await Admin.findOne({ username });
if (admin && (await bcrypt.compare(password, admin.password))) {
const token = jwt.sign({ username }, process.env.JWT_SECRET, { expiresIn: '1h' });
res.json({ token, message: 'Login successful' });
} else {
res.status(401).json({ message: 'Invalid credentials' });
}
} catch (error) {
res.status(500).json({ message: 'Error logging in', error });
}
});
// 3. Fetch all reports (protected route)
app.get('/get-reports', async (req, res) => {
const token = req.headers.authorization?.split(' ')[1];
if (!token) return res.status(401).json({ message: 'Unauthorized' });
try {
jwt.verify(token, process.env.JWT_SECRET);
const reports = await Report.find();
res.json(reports);
} catch (error) {
res.status(401).json({ message: 'Invalid token', error });
}
});
// Start server
const PORT = process.env.PORT || 5000; // Use Render's assigned port
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));