forked from harikrishna0315/uni_map
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
563 lines (478 loc) · 22.3 KB
/
Copy pathserver.js
File metadata and controls
563 lines (478 loc) · 22.3 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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
require('dotenv').config();
const express = require('express');
const mysql = require('mysql2');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const cors = require('cors');
const bodyParser = require('body-parser');
const https = require('https');
const app = express();
const PORT = process.env.PORT || 3000;
const JWT_SECRET = '123456789'; // Change this in production!
// Middleware
app.use(cors());
app.use(bodyParser.json());
app.use(express.static('public')); // Serve frontend files
// Database connection
const db = mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME
});
// Promisify database queries
const query = (sql, params) => {
return new Promise((resolve, reject) => {
db.query(sql, params, (err, results) => {
if (err) reject(err);
else resolve(results);
});
});
};
// Middleware to verify JWT token
const authenticateToken = (req, res, next) => {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if (!token) {
return res.status(401).json({ error: 'Access token required' });
}
jwt.verify(token, JWT_SECRET, (err, user) => {
if (err) return res.status(403).json({ error: 'Invalid token' });
req.user = user;
next();
});
};
// Middleware to check user role
const authorizeRole = (...roles) => {
return (req, res, next) => {
if (!roles.includes(req.user.role)) {
return res.status(403).json({ error: 'Insufficient permissions' });
}
next();
};
};
// Log activity
const logActivity = async (userId, actionType, tableName, recordId, details, ipAddress) => {
try {
await query(
'INSERT INTO activity_logs (user_id, action_type, table_name, record_id, action_details, ip_address) VALUES (?, ?, ?, ?, ?, ?)',
[userId, actionType, tableName, recordId, details, ipAddress]
);
} catch (err) {
console.error('Error logging activity:', err);
}
};
// ==================== AUTH ROUTES ====================
// Register new user
app.post('/api/auth/register', async (req, res) => {
try {
const { username, password, email, full_name, role = 'student' } = req.body;
// Validate input
if (!username || !password || !email || !full_name) {
return res.status(400).json({ error: 'All fields are required' });
}
// Hash password
const password_hash = await bcrypt.hash(password, 10);
// Insert user
const result = await query(
'INSERT INTO users (username, password_hash, email, full_name, role) VALUES (?, ?, ?, ?, ?)',
[username, password_hash, email, full_name, role]
);
res.status(201).json({ message: 'User registered successfully', user_id: result.insertId });
} catch (err) {
if (err.code === 'ER_DUP_ENTRY') {
res.status(409).json({ error: 'Username or email already exists' });
} else {
res.status(500).json({ error: 'Registration failed', details: err.message });
}
}
});
// Login
app.post('/api/auth/login', async (req, res) => {
try {
const { username, password } = req.body;
const users = await query('SELECT * FROM users WHERE username = ? AND is_active = TRUE', [username]);
if (users.length === 0) {
return res.status(401).json({ error: 'Invalid credentials' });
}
const user = users[0];
const validPassword = await bcrypt.compare(password, user.password_hash);
if (!validPassword) {
return res.status(401).json({ error: 'Invalid credentials' });
}
// Update last login
await query('UPDATE users SET last_login = NOW() WHERE user_id = ?', [user.user_id]);
// Create token
const token = jwt.sign(
{ user_id: user.user_id, username: user.username, role: user.role },
JWT_SECRET,
{ expiresIn: '24h' }
);
// Log activity
await logActivity(user.user_id, 'LOGIN', 'users', user.user_id, 'User logged in', req.ip);
res.json({
token,
user: {
user_id: user.user_id,
username: user.username,
email: user.email,
full_name: user.full_name,
role: user.role
}
});
} catch (err) {
res.status(500).json({ error: 'Login failed', details: err.message });
}
});
// ==================== BUILDING ROUTES ====================
// Get all buildings (accessible by all authenticated users)
app.get('/api/buildings', authenticateToken, async (req, res) => {
try {
const buildings = await query('SELECT * FROM buildings WHERE is_accessible = TRUE ORDER BY building_name');
res.json(buildings);
} catch (err) {
res.status(500).json({ error: 'Failed to fetch buildings', details: err.message });
}
});
// Get single building
app.get('/api/buildings/:id', authenticateToken, async (req, res) => {
try {
const buildings = await query('SELECT * FROM buildings WHERE building_id = ?', [req.params.id]);
if (buildings.length === 0) {
return res.status(404).json({ error: 'Building not found' });
}
res.json(buildings[0]);
} catch (err) {
res.status(500).json({ error: 'Failed to fetch building', details: err.message });
}
});
// Create building (admin/staff only)
app.post('/api/buildings', authenticateToken, authorizeRole('admin', 'staff'), async (req, res) => {
try {
const { building_code, building_name, building_type, latitude, longitude, floors, description, image_url, is_accessible } = req.body;
const result = await query(
'INSERT INTO buildings (building_code, building_name, building_type, latitude, longitude, floors, description, image_url, is_accessible, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
[building_code, building_name, building_type, latitude, longitude, floors, description, image_url, is_accessible, req.user.user_id]
);
await logActivity(req.user.user_id, 'CREATE', 'buildings', result.insertId, `Created building: ${building_name}`, req.ip);
res.status(201).json({ message: 'Building created successfully', building_id: result.insertId });
} catch (err) {
res.status(500).json({ error: 'Failed to create building', details: err.message });
}
});
// Update building (admin/staff only)
app.put('/api/buildings/:id', authenticateToken, authorizeRole('admin', 'staff'), async (req, res) => {
try {
const { building_code, building_name, building_type, latitude, longitude, floors, description, image_url, is_accessible } = req.body;
await query(
'UPDATE buildings SET building_code = ?, building_name = ?, building_type = ?, latitude = ?, longitude = ?, floors = ?, description = ?, image_url = ?, is_accessible = ? WHERE building_id = ?',
[building_code, building_name, building_type, latitude, longitude, floors, description, image_url, is_accessible, req.params.id]
);
await logActivity(req.user.user_id, 'UPDATE', 'buildings', req.params.id, `Updated building: ${building_name}`, req.ip);
res.json({ message: 'Building updated successfully' });
} catch (err) {
res.status(500).json({ error: 'Failed to update building', details: err.message });
}
});
// Delete building (admin only)
app.delete('/api/buildings/:id', authenticateToken, authorizeRole('admin'), async (req, res) => {
try {
await query('DELETE FROM buildings WHERE building_id = ?', [req.params.id]);
await logActivity(req.user.user_id, 'DELETE', 'buildings', req.params.id, 'Deleted building', req.ip);
res.json({ message: 'Building deleted successfully' });
} catch (err) {
res.status(500).json({ error: 'Failed to delete building', details: err.message });
}
});
// ==================== ROUTE FINDING API - OPENROUTESERVICE ====================
// Calculate distance between two points using Haversine formula
function calculateDistance(lat1, lon1, lat2, lon2) {
const R = 6371e3; // Earth's radius in meters
const φ1 = lat1 * Math.PI / 180;
const φ2 = lat2 * Math.PI / 180;
const Δφ = (lat2 - lat1) * Math.PI / 180;
const Δλ = (lon2 - lon1) * Math.PI / 180;
const a = Math.sin(Δφ / 2) * Math.sin(Δφ / 2) +
Math.cos(φ1) * Math.cos(φ2) *
Math.sin(Δλ / 2) * Math.sin(Δλ / 2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return R * c; // Distance in meters
}
// Helper function for enhanced fallback straight line route
function createStraightLineRoute(startBuilding, endBuilding) {
const distance = calculateDistance(
startBuilding.latitude,
startBuilding.longitude,
endBuilding.latitude,
endBuilding.longitude
);
const walkingSpeed = 1.4; // meters per second
const timeInMinutes = Math.ceil((distance / walkingSpeed) / 60);
// Calculate bearing for directional instruction
const lat1 = startBuilding.latitude * Math.PI / 180;
const lat2 = endBuilding.latitude * Math.PI / 180;
const lon1 = startBuilding.longitude * Math.PI / 180;
const lon2 = endBuilding.longitude * Math.PI / 180;
const y = Math.sin(lon2 - lon1) * Math.cos(lat2);
const x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1);
const bearing = Math.atan2(y, x) * 180 / Math.PI;
const directions = ['North', 'Northeast', 'East', 'Southeast', 'South', 'Southwest', 'West', 'Northwest'];
const index = Math.round(((bearing + 360) % 360) / 45) % 8;
const direction = directions[index];
return {
start: {
building_id: startBuilding.building_id,
building_name: startBuilding.building_name,
building_code: startBuilding.building_code,
latitude: startBuilding.latitude,
longitude: startBuilding.longitude
},
end: {
building_id: endBuilding.building_id,
building_name: endBuilding.building_name,
building_code: endBuilding.building_code,
latitude: endBuilding.latitude,
longitude: endBuilding.longitude
},
distance: Math.round(distance),
estimated_time: timeInMinutes,
path_coordinates: [
[startBuilding.latitude, startBuilding.longitude],
[endBuilding.latitude, endBuilding.longitude]
],
instructions: [
{
instruction: `Head ${direction} from ${startBuilding.building_name}`,
distance: Math.round(distance * 0.2),
duration: Math.ceil(timeInMinutes * 0.2) || 1
},
{
instruction: `Continue ${direction} towards ${endBuilding.building_name}`,
distance: Math.round(distance * 0.7),
duration: Math.ceil(timeInMinutes * 0.7) || 1
},
{
instruction: `Arrive at ${endBuilding.building_name}`,
distance: Math.round(distance * 0.1),
duration: Math.ceil(timeInMinutes * 0.1) || 1
}
],
fallback: true
};
}
// Find route between two buildings - OpenRouteService
app.post('/api/route/find', authenticateToken, async (req, res) => {
try {
const { start_building_id, end_building_id } = req.body;
if (!start_building_id || !end_building_id) {
return res.status(400).json({ error: 'Start and end building IDs are required' });
}
// Get building details
const [startBuilding] = await query('SELECT * FROM buildings WHERE building_id = ?', [start_building_id]);
const [endBuilding] = await query('SELECT * FROM buildings WHERE building_id = ?', [end_building_id]);
if (!startBuilding || !endBuilding) {
return res.status(404).json({ error: 'One or both buildings not found' });
}
// ========================================================================
// OPENROUTESERVICE API - 2000 FREE requests/day, NO CREDIT CARD REQUIRED
// ========================================================================
// Get your FREE API key:
// 1. Sign up at: https://openrouteservice.org/dev/#/signup
// 2. Verify your email
// 3. Login and click "REQUEST A TOKEN"
// 4. Copy your key and paste it below
const ORS_API_KEY = 'eyJvcmciOiI1YjNjZTM1OTc4NTExMTAwMDFjZjYyNDgiLCJpZCI6ImY2MjVmMWJkYjVmMDRjZDVhYzM2OTJkMTE1NDA0OWQzIiwiaCI6Im11cm11cjY0In0='; // ← PASTE YOUR NEW KEY HERE
// Try OpenRouteService API if key is provided
if (ORS_API_KEY && ORS_API_KEY !== 'YOUR_NEW_ORS_API_KEY_HERE') {
const orsUrl = `https://api.openrouteservice.org/v2/directions/foot-walking?api_key=${ORS_API_KEY}&start=${startBuilding.longitude},${startBuilding.latitude}&end=${endBuilding.longitude},${endBuilding.latitude}`;
try {
console.log('🔍 Requesting route from OpenRouteService...');
const routeData = await new Promise((resolve, reject) => {
https.get(orsUrl, (orsRes) => {
let data = '';
orsRes.on('data', (chunk) => {
data += chunk;
});
orsRes.on('end', () => {
try {
const parsed = JSON.parse(data);
// Check for API errors
if (parsed.error) {
console.log('❌ ORS API Error:', parsed.error.message);
reject(new Error(parsed.error.message));
} else {
resolve(parsed);
}
} catch (err) {
console.log('❌ JSON Parse Error:', err.message);
reject(err);
}
});
}).on('error', (err) => {
console.log('❌ HTTPS Request Error:', err.message);
reject(err);
});
});
if (routeData.features && routeData.features.length > 0) {
const route = routeData.features[0];
const geometry = route.geometry.coordinates;
const properties = route.properties.segments[0];
// Convert coordinates to [lat, lng] format for Leaflet
const pathCoordinates = geometry.map(coord => [coord[1], coord[0]]);
const routeInfo = {
start: {
building_id: startBuilding.building_id,
building_name: startBuilding.building_name,
building_code: startBuilding.building_code,
latitude: startBuilding.latitude,
longitude: startBuilding.longitude
},
end: {
building_id: endBuilding.building_id,
building_name: endBuilding.building_name,
building_code: endBuilding.building_code,
latitude: endBuilding.latitude,
longitude: endBuilding.longitude
},
distance: Math.round(properties.distance), // meters
estimated_time: Math.ceil(properties.duration / 60), // minutes
path_coordinates: pathCoordinates,
instructions: properties.steps.map(step => ({
instruction: step.instruction,
distance: Math.round(step.distance),
duration: Math.ceil(step.duration / 60)
})),
fallback: false
};
await logActivity(
req.user.user_id,
'ROUTE_SEARCH',
'buildings',
null,
`Route from ${startBuilding.building_name} to ${endBuilding.building_name}`,
req.ip
);
console.log('✅ Route found - Following actual roads!');
console.log(` Distance: ${routeInfo.distance}m, Time: ${routeInfo.estimated_time} min`);
return res.json(routeInfo);
} else {
console.log('⚠️ No route found in response, using fallback');
}
} catch (orsError) {
console.log('⚠️ OpenRouteService error:', orsError.message);
console.log(' Falling back to straight-line route');
}
} else {
console.log('⚠️ No API key provided');
console.log(' Get your FREE key at: https://openrouteservice.org/dev/#/signup');
console.log(' Using fallback route for now...');
}
// FALLBACK: Use enhanced straight-line route
console.log('📍 Using enhanced fallback route with directions');
const fallbackRoute = createStraightLineRoute(startBuilding, endBuilding);
await logActivity(
req.user.user_id,
'ROUTE_SEARCH',
'buildings',
null,
`Fallback route from ${startBuilding.building_name} to ${endBuilding.building_name}`,
req.ip
);
res.json(fallbackRoute);
} catch (err) {
console.error('❌ Route finding error:', err);
res.status(500).json({ error: 'Failed to find route', details: err.message });
}
});
// ==================== POI ROUTES ====================
// Get all POIs
app.get('/api/pois', authenticateToken, async (req, res) => {
try {
const pois = await query(`
SELECT p.*, b.building_name
FROM points_of_interest p
LEFT JOIN buildings b ON p.building_id = b.building_id
WHERE p.is_accessible = TRUE
ORDER BY p.poi_name
`);
res.json(pois);
} catch (err) {
res.status(500).json({ error: 'Failed to fetch POIs', details: err.message });
}
});
// Get POIs by building
app.get('/api/buildings/:id/pois', authenticateToken, async (req, res) => {
try {
const pois = await query('SELECT * FROM points_of_interest WHERE building_id = ? AND is_accessible = TRUE', [req.params.id]);
res.json(pois);
} catch (err) {
res.status(500).json({ error: 'Failed to fetch POIs', details: err.message });
}
});
// Create POI (admin/staff only)
app.post('/api/pois', authenticateToken, authorizeRole('admin', 'staff'), async (req, res) => {
try {
const { poi_name, poi_type, building_id, floor_number, latitude, longitude, description, opening_hours, is_accessible } = req.body;
const result = await query(
'INSERT INTO points_of_interest (poi_name, poi_type, building_id, floor_number, latitude, longitude, description, opening_hours, is_accessible) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',
[poi_name, poi_type, building_id, floor_number, latitude, longitude, description, opening_hours, is_accessible]
);
await logActivity(req.user.user_id, 'CREATE', 'points_of_interest', result.insertId, `Created POI: ${poi_name}`, req.ip);
res.status(201).json({ message: 'POI created successfully', poi_id: result.insertId });
} catch (err) {
res.status(500).json({ error: 'Failed to create POI', details: err.message });
}
});
// ==================== DEPARTMENT ROUTES ====================
// Get all departments
app.get('/api/departments', authenticateToken, async (req, res) => {
try {
const departments = await query(`
SELECT d.*, b.building_name
FROM departments d
LEFT JOIN buildings b ON d.building_id = b.building_id
ORDER BY d.dept_name
`);
res.json(departments);
} catch (err) {
res.status(500).json({ error: 'Failed to fetch departments', details: err.message });
}
});
// Create department (admin only)
app.post('/api/departments', authenticateToken, authorizeRole('admin'), async (req, res) => {
try {
const { dept_name, dept_code, building_id, floor_number, phone, email, head_of_dept } = req.body;
const result = await query(
'INSERT INTO departments (dept_name, dept_code, building_id, floor_number, phone, email, head_of_dept) VALUES (?, ?, ?, ?, ?, ?, ?)',
[dept_name, dept_code, building_id, floor_number, phone, email, head_of_dept]
);
res.status(201).json({ message: 'Department created successfully', dept_id: result.insertId });
} catch (err) {
res.status(500).json({ error: 'Failed to create department', details: err.message });
}
});
// ==================== USER ROUTES ====================
// Get all users (admin only)
app.get('/api/users', authenticateToken, authorizeRole('admin'), async (req, res) => {
try {
const users = await query('SELECT user_id, username, email, full_name, role, created_at, last_login, is_active FROM users ORDER BY created_at DESC');
res.json(users);
} catch (err) {
res.status(500).json({ error: 'Failed to fetch users', details: err.message });
}
});
// Update user role (admin only)
app.put('/api/users/:id/role', authenticateToken, authorizeRole('admin'), async (req, res) => {
try {
const { role } = req.body;
await query('UPDATE users SET role = ? WHERE user_id = ?', [role, req.params.id]);
await logActivity(req.user.user_id, 'UPDATE', 'users', req.params.id, `Changed user role to: ${role}`, req.ip);
res.json({ message: 'User role updated successfully' });
} catch (err) {
res.status(500).json({ error: 'Failed to update user role', details: err.message });
}
});
// Start server
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});