Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 | 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x | const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const bcrypt = require('bcryptjs');
const crypto = require('crypto');
const pool = require('../config/database');
const { authenticate, authorize } = require('../middleware/auth');
const { sendVerificationEmail } = require('../services/emailService');
const router = express.Router();
// Configure multer for avatar uploads
const avatarStorage = multer.diskStorage({
destination: (req, file, cb) => {
const uploadDir = process.env.UPLOAD_DIR || './uploads';
const avatarsDir = path.join(uploadDir, 'avatars');
if (!fs.existsSync(avatarsDir)) {
fs.mkdirSync(avatarsDir, { recursive: true });
}
cb(null, avatarsDir);
},
filename: (req, file, cb) => {
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
cb(null, `avatar-${req.user.id}-${uniqueSuffix}${path.extname(file.originalname)}`);
}
});
const avatarUpload = multer({
storage: avatarStorage,
limits: {
fileSize: 5 * 1024 * 1024 // 5MB max for avatars
},
fileFilter: (req, file, cb) => {
const allowedTypes = /jpg|jpeg|png|gif|webp/;
const extname = allowedTypes.test(path.extname(file.originalname).toLowerCase());
const mimetype = /image\/(jpeg|jpg|png|gif|webp)/.test(file.mimetype);
if (extname && mimetype) {
return cb(null, true);
} else {
cb(new Error('Invalid file type. Only JPG, PNG, GIF, and WEBP images are allowed.'));
}
}
});
// Get all users (admin only)
router.get('/', authenticate, authorize('administrator'), async (req, res) => {
try {
const { role, status, search } = req.query;
let query = `
SELECT u.id, u.email, u.name, u.role, u.phone, u.avatar, u.status, u.created_at
FROM users u
WHERE 1=1
`;
const params = [];
if (role) {
query += ' AND u.role = ?';
params.push(role);
}
if (status) {
query += ' AND u.status = ?';
params.push(status);
}
if (search) {
query += ' AND (u.name LIKE ? OR u.email LIKE ?)';
const searchTerm = `%${search}%`;
params.push(searchTerm, searchTerm);
}
query += ' ORDER BY u.created_at DESC';
const [users] = await pool.query(query, params);
res.json({ users });
} catch (error) {
console.error('Get users error:', error);
res.status(500).json({ error: 'Failed to fetch users' });
}
});
// Get user by ID
router.get('/:id', authenticate, async (req, res) => {
try {
const userId = parseInt(req.params.id);
const currentUser = req.user;
// Users can only view their own profile unless they're admin
if (currentUser.role !== 'administrator' && currentUser.id !== userId) {
return res.status(403).json({ error: 'Access denied' });
}
const [users] = await pool.query(
'SELECT id, email, name, role, phone, avatar, status, created_at FROM users WHERE id = ?',
[userId]
);
if (users.length === 0) {
return res.status(404).json({ error: 'User not found' });
}
res.json({ user: users[0] });
} catch (error) {
console.error('Get user error:', error);
res.status(500).json({ error: 'Failed to fetch user' });
}
});
// Update user
router.put('/:id', authenticate, async (req, res) => {
try {
const userId = parseInt(req.params.id);
const currentUser = req.user;
const { name, phone, avatar, email } = req.body;
// Users can only update their own profile unless they're admin
if (currentUser.role !== 'administrator' && currentUser.id !== userId) {
return res.status(403).json({ error: 'Access denied' });
}
const updates = [];
const params = [];
if (name) {
updates.push('name = ?');
params.push(name);
}
if (phone !== undefined) {
updates.push('phone = ?');
params.push(phone);
}
if (avatar !== undefined) {
updates.push('avatar = ?');
params.push(avatar);
}
if (email) {
// Check if email is already taken by another user
const [existing] = await pool.query(
'SELECT id FROM users WHERE email = ? AND id != ?',
[email, userId]
);
if (existing.length > 0) {
return res.status(400).json({ error: 'Email is already in use' });
}
updates.push('email = ?');
params.push(email);
}
if (updates.length === 0) {
return res.status(400).json({ error: 'No fields to update' });
}
params.push(userId);
await pool.query(
`UPDATE users SET ${updates.join(', ')} WHERE id = ?`,
params
);
res.json({ message: 'User updated successfully' });
} catch (error) {
console.error('Update user error:', error);
res.status(500).json({ error: 'Failed to update user' });
}
});
// Update user status (admin only)
router.put('/:id/status', authenticate, authorize('administrator'), async (req, res) => {
try {
const userId = parseInt(req.params.id);
const { status } = req.body;
if (!['active', 'inactive', 'suspended'].includes(status)) {
return res.status(400).json({ error: 'Invalid status' });
}
await pool.query(
'UPDATE users SET status = ? WHERE id = ?',
[status, userId]
);
res.json({ message: 'User status updated successfully' });
} catch (error) {
console.error('Update status error:', error);
res.status(500).json({ error: 'Failed to update user status' });
}
});
// Delete user (admin only)
router.delete('/:id', authenticate, authorize('administrator'), async (req, res) => {
try {
const userId = parseInt(req.params.id);
if (userId === req.user.id) {
return res.status(400).json({ error: 'Cannot delete your own account' });
}
await pool.query('DELETE FROM users WHERE id = ?', [userId]);
res.json({ message: 'User deleted successfully' });
} catch (error) {
console.error('Delete user error:', error);
res.status(500).json({ error: 'Failed to delete user' });
}
});
// Admin: Add student (check if user exists in database)
router.post('/admin/add-student', authenticate, authorize('administrator'), async (req, res) => {
try {
const { email, phone } = req.body;
if (!email && !phone) {
return res.status(400).json({ error: 'Email or phone number is required' });
}
// Find user by email or phone
let userQuery = `
SELECT u.id, u.name, u.email, u.phone, u.role, u.status
FROM users u
WHERE u.status = 'active'
`;
const userParams = [];
if (email) {
userQuery += ' AND u.email = ?';
userParams.push(email);
} else if (phone) {
userQuery += ' AND u.phone = ?';
userParams.push(phone);
}
const [users] = await pool.query(userQuery, userParams);
if (users.length === 0) {
return res.status(404).json({
error: 'User not found. The user is not registered in the system.'
});
}
const user = users[0];
// Check if user is already a student
if (user.role !== 'student') {
return res.status(400).json({
error: `This user is registered as a ${user.role}, not a student.`
});
}
// Check if student record already exists
const [existingStudent] = await pool.query(
'SELECT id FROM students WHERE user_id = ?',
[user.id]
);
if (existingStudent.length > 0) {
return res.status(400).json({
error: 'This user is already registered as a student.'
});
}
// Create student record (with default values)
const [result] = await pool.query(
'INSERT INTO students (user_id, program, progress) VALUES (?, ?, ?)',
[user.id, 'PhD Computer Science', 0]
);
res.json({
message: 'Student added successfully',
student: {
id: result.insertId,
user_id: user.id,
name: user.name,
email: user.email,
phone: user.phone
}
});
} catch (error) {
console.error('Admin add student error:', error);
// Handle duplicate entry error
if (error.code === 'ER_DUP_ENTRY') {
return res.status(400).json({
error: 'This user is already registered as a student.'
});
}
res.status(500).json({ error: 'Failed to add student' });
}
});
// Admin: Add supervisor (check if user exists in database)
router.post('/admin/add-supervisor', authenticate, authorize('administrator'), async (req, res) => {
try {
const { email, phone } = req.body;
if (!email && !phone) {
return res.status(400).json({ error: 'Email or phone number is required' });
}
// Find user by email or phone
let userQuery = `
SELECT u.id, u.name, u.email, u.phone, u.role, u.status
FROM users u
WHERE u.status = 'active'
`;
const userParams = [];
if (email) {
userQuery += ' AND u.email = ?';
userParams.push(email);
} else if (phone) {
userQuery += ' AND u.phone = ?';
userParams.push(phone);
}
const [users] = await pool.query(userQuery, userParams);
if (users.length === 0) {
return res.status(404).json({
error: 'User not found. The user is not registered in the system.'
});
}
const user = users[0];
// Check if user is already a supervisor
if (user.role !== 'supervisor') {
return res.status(400).json({
error: `This user is registered as a ${user.role}, not a supervisor.`
});
}
// Check if supervisor record already exists
const [existingSupervisor] = await pool.query(
'SELECT id FROM supervisors WHERE user_id = ?',
[user.id]
);
if (existingSupervisor.length > 0) {
return res.status(400).json({
error: 'This user is already registered as a supervisor.'
});
}
// Create supervisor record (with default values)
const [result] = await pool.query(
'INSERT INTO supervisors (user_id, department, capacity, current_students) VALUES (?, ?, ?, ?)',
[user.id, 'Computer Science', 10, 0]
);
res.json({
message: 'Supervisor added successfully',
supervisor: {
id: result.insertId,
user_id: user.id,
name: user.name,
email: user.email,
phone: user.phone
}
});
} catch (error) {
console.error('Admin add supervisor error:', error);
// Handle duplicate entry error
if (error.code === 'ER_DUP_ENTRY') {
return res.status(400).json({
error: 'This user is already registered as a supervisor.'
});
}
res.status(500).json({ error: 'Failed to add supervisor' });
}
});
// Admin: Create new user account (student, supervisor, or administrator)
router.post('/admin/create-user', authenticate, authorize('administrator'), async (req, res) => {
try {
const { email, password, name, role, phone, program, department, supervisor_id } = req.body;
// Validation
if (!email || !password || !name || !role) {
return res.status(400).json({ error: 'Email, password, name, and role are required' });
}
if (password.length < 6) {
return res.status(400).json({ error: 'Password must be at least 6 characters long' });
}
if (!['student', 'supervisor', 'administrator'].includes(role)) {
return res.status(400).json({ error: 'Invalid role. Must be student, supervisor, or administrator.' });
}
// Check if user already exists
const [existingUsers] = await pool.query(
'SELECT id FROM users WHERE email = ?',
[email]
);
if (existingUsers.length > 0) {
return res.status(400).json({ error: 'User with this email already exists' });
}
// Hash password
const hashedPassword = await bcrypt.hash(password, 10);
// Generate verification token
const verificationToken = crypto.randomBytes(32).toString('hex');
const expiresAt = new Date();
expiresAt.setHours(expiresAt.getHours() + 24); // Token expires in 24 hours
// Start transaction
const connection = await pool.getConnection();
await connection.beginTransaction();
try {
// Insert user with email_verified = false and status = 'inactive' (requires email verification)
const [userResult] = await connection.query(
'INSERT INTO users (email, password, name, role, phone, status, email_verified) VALUES (?, ?, ?, ?, ?, ?, ?)',
[email, hashedPassword, name, role, phone || null, 'inactive', false]
);
const userId = userResult.insertId;
// Insert role-specific data
if (role === 'student') {
// Get the student ID after insertion
const [studentResult] = await connection.query(
'INSERT INTO students (user_id, program, enrollment_date) VALUES (?, ?, CURDATE())',
[userId, program || null]
);
const studentId = studentResult.insertId;
// If supervisor_id is provided, create the relationship
if (supervisor_id) {
// Verify supervisor exists
const [supervisorCheck] = await connection.query(
'SELECT id, capacity, current_students FROM supervisors WHERE id = ?',
[supervisor_id]
);
if (supervisorCheck.length > 0) {
const supervisor = supervisorCheck[0];
// Check capacity
if (supervisor.current_students >= supervisor.capacity) {
await connection.rollback();
connection.release();
return res.status(400).json({
error: 'Supervisor has reached maximum capacity. Please select another supervisor or increase capacity.'
});
}
// Create relationship in supervisor_student table
await connection.query(
'INSERT INTO supervisor_student (supervisor_id, student_id) VALUES (?, ?)',
[supervisor_id, studentId]
);
// Update supervisor's current_students count
await connection.query(
'UPDATE supervisors SET current_students = current_students + 1 WHERE id = ?',
[supervisor_id]
);
}
}
} else if (role === 'supervisor') {
await connection.query(
'INSERT INTO supervisors (user_id, department, capacity, current_students) VALUES (?, ?, ?, ?)',
[userId, department || null, 10, 0]
);
} else if (role === 'administrator') {
await connection.query(
'INSERT INTO administrators (user_id, department) VALUES (?, ?)',
[userId, department || null]
);
}
// Insert verification token
await connection.query(
'INSERT INTO email_verification_tokens (user_id, email, token, expires_at) VALUES (?, ?, ?, ?)',
[userId, email, verificationToken, expiresAt]
);
await connection.commit();
connection.release();
// Send verification email
try {
await sendVerificationEmail(email, name, verificationToken);
} catch (emailError) {
console.error('Failed to send verification email:', emailError);
// Don't fail account creation if email fails, but log it
}
res.json({
message: `${role.charAt(0).toUpperCase() + role.slice(1)} account created successfully! A verification email has been sent.`,
emailSent: true,
user: {
id: userId,
name,
email,
phone: phone || null,
role
}
});
} catch (error) {
await connection.rollback();
connection.release();
throw error;
}
} catch (error) {
console.error('Admin create user error:', error);
// Handle duplicate entry error
if (error.code === 'ER_DUP_ENTRY') {
return res.status(400).json({
error: 'User with this email already exists'
});
}
res.status(500).json({ error: 'Failed to create user' });
}
});
// Admin: Remove user from role (delete from role table but keep in users table)
router.delete('/:id/role', authenticate, authorize('administrator'), async (req, res) => {
try {
const userId = parseInt(req.params.id);
const { role } = req.body;
if (!role || !['student', 'supervisor'].includes(role)) {
return res.status(400).json({ error: 'Invalid role. Must be student or supervisor.' });
}
if (userId === req.user.id) {
return res.status(400).json({ error: 'Cannot remove your own role' });
}
// Get user to verify they exist
const [users] = await pool.query('SELECT id, role FROM users WHERE id = ?', [userId]);
if (users.length === 0) {
return res.status(404).json({ error: 'User not found' });
}
const user = users[0];
if (user.role !== role) {
return res.status(400).json({ error: `User is not a ${role}` });
}
if (role === 'student') {
// Get student ID
const [students] = await pool.query('SELECT id FROM students WHERE user_id = ?', [userId]);
if (students.length === 0) {
return res.status(404).json({ error: 'Student record not found' });
}
const studentId = students[0].id;
// Get supervisors who have this student before deleting relationships
const [supervisorRelations] = await pool.query(
'SELECT supervisor_id FROM supervisor_student WHERE student_id = ?',
[studentId]
);
// Remove from supervisor_student relationships
await pool.query('DELETE FROM supervisor_student WHERE student_id = ?', [studentId]);
// Update supervisor current_students count for any supervisors who had this student
for (const rel of supervisorRelations) {
await pool.query(
'UPDATE supervisors SET current_students = GREATEST(0, current_students - 1) WHERE id = ?',
[rel.supervisor_id]
);
}
// Delete student record
await pool.query('DELETE FROM students WHERE id = ?', [studentId]);
} else if (role === 'supervisor') {
// Get supervisor ID
const [supervisors] = await pool.query('SELECT id FROM supervisors WHERE user_id = ?', [userId]);
if (supervisors.length === 0) {
return res.status(404).json({ error: 'Supervisor record not found' });
}
const supervisorId = supervisors[0].id;
// Remove from supervisor_student relationships
await pool.query('DELETE FROM supervisor_student WHERE supervisor_id = ?', [supervisorId]);
// Update students to remove supervisor_id
await pool.query('UPDATE students SET supervisor_id = NULL WHERE supervisor_id = ?', [supervisorId]);
// Delete supervisor record
await pool.query('DELETE FROM supervisors WHERE id = ?', [supervisorId]);
}
// Update user role to null or a default role (keeping them in users table)
// We'll keep the role in users table but they won't have a role-specific record
// Optionally, you could set role to 'inactive' or keep it as is
res.json({ message: `User removed from ${role} role successfully` });
} catch (error) {
console.error('Remove role error:', error);
res.status(500).json({ error: 'Failed to remove user from role' });
}
});
// Upload avatar
router.post('/avatar', authenticate, avatarUpload.single('avatar'), async (req, res) => {
try {
if (!req.file) {
return res.status(400).json({ error: 'No file uploaded' });
}
const userId = req.user.id;
const avatarPath = `/uploads/avatars/${req.file.filename}`;
// Get the old avatar to delete it
const [users] = await pool.query('SELECT avatar FROM users WHERE id = ?', [userId]);
if (users.length > 0 && users[0].avatar) {
const oldAvatarPath = users[0].avatar;
// Only delete if it's a local file (starts with /uploads)
if (oldAvatarPath.startsWith('/uploads/avatars/')) {
const fullPath = path.join(process.env.UPLOAD_DIR || './uploads', 'avatars', path.basename(oldAvatarPath));
if (fs.existsSync(fullPath)) {
fs.unlinkSync(fullPath);
}
}
}
// Update user's avatar in database
await pool.query('UPDATE users SET avatar = ? WHERE id = ?', [avatarPath, userId]);
res.json({
message: 'Avatar uploaded successfully',
avatar: avatarPath
});
} catch (error) {
console.error('Avatar upload error:', error);
// Delete uploaded file if database update fails
if (req.file) {
fs.unlinkSync(req.file.path);
}
res.status(500).json({ error: 'Failed to upload avatar' });
}
});
module.exports = router;
|