const { validationResult } = require('express-validator'); const jwt = require('jsonwebtoken'); const bcrypt = require('bcryptjs'); const User = require('../models/User'); const ugaService = require('../services/ugaService'); const logger = require('../utils/logger'); const { redisUtils } = require('../utils/redis'); class AuthController { async register(req, res) { try { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ success: false, errors: errors.array() }); } const { email, firstName, lastName, password, college, major, classification } = req.body; // Validate email format if (!email || !email.includes('@')) { return res.status(400).json({ success: false, error: 'Valid email address is required' }); } // Check if user already exists const existingUser = await User.findOne({ email: email.toLowerCase() }); if (existingUser) { return res.status(409).json({ success: false, error: 'User already exists with this email' }); } // Validate required fields if (!firstName || !lastName) { return res.status(400).json({ success: false, error: 'First name and last name are required' }); } // Create new user const userData = { email: email.toLowerCase(), firstName: firstName.trim(), lastName: lastName.trim(), role: 'student', // Default role college: college ? college.trim() : 'Not specified', major: major ? major.trim() : 'Not specified', classification: classification ? classification.trim() : 'Not specified', authProvider: 'local' }; if (password) { userData.passwordHash = password; // Will be hashed by the model pre-save hook } const user = new User(userData); // Generate email verification token for local accounts if (userData.authProvider === 'local') { const verificationToken = user.generateEmailVerificationToken(); // In a production environment, you would send an email here // For now, we'll log the verification URL for development/testing const verificationUrl = `${req.protocol}://${req.get('host')}/verify-email?token=${verificationToken}`; logger.info('Email verification URL (DEV)', { email: user.email, verificationUrl, verificationToken: verificationToken.substring(0, 8) + '...' }); // TODO: Implement actual email sending service integration // Example: await emailService.sendVerificationEmail(user.email, verificationUrl); } await user.save(); // Generate JWT token const token = jwt.sign( { id: user._id, email: user.email, role: user.role }, process.env.JWT_SECRET, { expiresIn: process.env.JWT_EXPIRES_IN || '24h' } ); // Cache user await redisUtils.setex(`user:${user._id}`, 300, user); logger.info('User registered', { userId: user._id, email: user.email, role: user.role }); res.status(201).json({ success: true, data: { user: { id: user._id, ugaId: user.ugaId, email: user.email, firstName: user.firstName, lastName: user.lastName, role: user.role, college: user.college, major: user.major, classification: user.classification }, token }, message: 'User registered successfully' }); } catch (error) { logger.error('Registration error:', error); res.status(500).json({ success: false, error: 'Failed to register user' }); } } async login(req, res) { try { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ success: false, errors: errors.array() }); } const { username, password } = req.body; // Development mode - allow test users without database if (process.env.NODE_ENV === 'development' && process.env.ALLOW_TEST_USERS === 'true') { const testUsers = { 'test@uga.edu': { id: 'test-student-id', ugaId: '811000001', email: 'test@uga.edu', firstName: 'Test', lastName: 'Student', role: 'student', college: 'Franklin College of Arts & Sciences', major: 'Computer Science', classification: 'junior' }, 'faculty@uga.edu': { id: 'test-faculty-id', ugaId: '900000001', email: 'faculty@uga.edu', firstName: 'Test', lastName: 'Professor', role: 'faculty', college: 'Franklin College of Arts & Sciences', department: 'Computer Science' }, 'admin@uga.edu': { id: 'test-admin-id', ugaId: '700000001', email: 'admin@uga.edu', firstName: 'Test', lastName: 'Admin', role: 'admin' } }; if (testUsers[username] && password === process.env.TEST_USER_PASSWORD) { const testUser = testUsers[username]; const token = jwt.sign( { id: testUser.id, email: testUser.email, role: testUser.role }, process.env.JWT_SECRET, { expiresIn: process.env.JWT_EXPIRES_IN || '1h' } ); logger.info('Development login successful', { userId: testUser.id, username }); return res.json({ success: true, data: { token, user: testUser } }); } } // Validate username format if (!username || username.length < 3) { return res.status(400).json({ success: false, error: 'Valid username is required' }); } // Find user by username (could be ugaId, myId, or email) const user = await User.findOne({ $or: [ { ugaId: username }, { myId: username }, { email: username.toLowerCase() } ] }); if (!user) { return res.status(401).json({ success: false, error: 'Invalid credentials' }); } // Check if account is active if (!user.isActive) { return res.status(401).json({ success: false, error: 'Account has been deactivated' }); } // Verify password const isValidPassword = await user.comparePassword(password); if (!isValidPassword) { return res.status(401).json({ success: false, error: 'Invalid credentials' }); } // Update last login (with error handling) try { if (user && typeof user.updateActivity === 'function') { await user.updateActivity(); } } catch (activityError) { logger.warn('Failed to update user activity', { userId: user._id, error: activityError.message }); } // Generate JWT token const token = jwt.sign( { id: user._id, email: user.email, role: user.role }, process.env.JWT_SECRET, { expiresIn: process.env.JWT_EXPIRES_IN || '24h' } ); // Cache user await redisUtils.setex(`user:${user._id}`, 300, user); logger.info('User logged in', { userId: user._id, email: user.email }); res.json({ success: true, data: { user: { id: user._id, ugaId: user.ugaId, email: user.email, firstName: user.firstName, lastName: user.lastName, role: user.role, college: user.college, major: user.major, classification: user.classification }, token }, message: 'Login successful' }); } catch (error) { logger.error('Login error:', error); res.status(500).json({ success: false, error: 'Failed to login' }); } } async loginWithMyID(req, res) { try { const { username, password } = req.body; if (!username || !password) { return res.status(400).json({ success: false, error: 'Username and password are required' }); } // Authenticate with MyID system const myIdAuth = await ugaService.authenticateWithMyID({ username, password }); if (!myIdAuth.success) { return res.status(401).json({ success: false, error: myIdAuth.error || 'MyID authentication failed' }); } // Find or create user based on MyID response let user = await User.findOne({ myId: username }); if (!user) { // Create new user from MyID data const userData = { ugaId: myIdAuth.user.ugaId || username, myId: username, email: myIdAuth.user.email, firstName: myIdAuth.user.firstName, lastName: myIdAuth.user.lastName, role: myIdAuth.user.role || 'student', college: myIdAuth.user.college, major: myIdAuth.user.major, classification: myIdAuth.user.classification, authProvider: 'myid', isVerified: true }; user = new User(userData); await user.save(); logger.info('User created via MyID', { userId: user._id, myId: username }); } else { // Update existing user activity (with error handling) try { if (user && typeof user.updateActivity === 'function') { await user.updateActivity(); } } catch (activityError) { logger.warn('Failed to update user activity', { userId: user._id, error: activityError.message }); } logger.info('User logged in via MyID', { userId: user._id, myId: username }); } // Generate JWT token const token = jwt.sign( { id: user._id, email: user.email, role: user.role }, process.env.JWT_SECRET, { expiresIn: process.env.JWT_EXPIRES_IN || '24h' } ); // Cache user await redisUtils.setex(`user:${user._id}`, 300, user); res.json({ success: true, data: { user: { id: user._id, ugaId: user.ugaId, email: user.email, firstName: user.firstName, lastName: user.lastName, role: user.role, college: user.college, major: user.major, classification: user.classification }, token }, message: 'MyID login successful' }); } catch (error) { logger.error('MyID login error:', error); res.status(500).json({ success: false, error: 'Failed to authenticate with MyID' }); } } async logout(req, res) { try { const token = req.token; // Add token to blacklist const tokenPayload = jwt.decode(token); const expiresIn = tokenPayload.exp - Math.floor(Date.now() / 1000); if (expiresIn > 0) { await redisUtils.setex(`blacklist:${token}`, expiresIn, 'true'); } // Remove user from cache await redisUtils.del(`user:${req.user.id}`); logger.info('User logged out', { userId: req.user.id }); res.json({ success: true, message: 'Logout successful' }); } catch (error) { logger.error('Logout error:', error); res.status(500).json({ success: false, error: 'Failed to logout' }); } } async refreshToken(req, res) { try { const { refreshToken } = req.body; if (!refreshToken) { return res.status(400).json({ success: false, error: 'Refresh token is required' }); } try { const decoded = jwt.verify(refreshToken, process.env.JWT_REFRESH_SECRET); const user = await User.findById(decoded.id).select('-passwordHash'); if (!user || !user.isActive) { return res.status(401).json({ success: false, error: 'Invalid refresh token' }); } // Generate new access token const newToken = jwt.sign( { id: user._id, email: user.email, role: user.role }, process.env.JWT_SECRET, { expiresIn: process.env.JWT_EXPIRES_IN || '24h' } ); res.json({ success: true, data: { token: newToken }, message: 'Token refreshed successfully' }); } catch (tokenError) { return res.status(401).json({ success: false, error: 'Invalid refresh token' }); } } catch (error) { logger.error('Token refresh error:', error); res.status(500).json({ success: false, error: 'Failed to refresh token' }); } } async getProfile(req, res) { try { const user = req.user; res.json({ success: true, data: { id: user._id, ugaId: user.ugaId, email: user.email, firstName: user.firstName, lastName: user.lastName, displayName: user.displayName, role: user.role, college: user.college, department: user.department, major: user.major, classification: user.classification, preferences: user.preferences, stats: user.stats, lastLogin: user.lastLogin, createdAt: user.createdAt } }); } catch (error) { logger.error('Get profile error:', error); res.status(500).json({ success: false, error: 'Failed to fetch profile' }); } } async updateProfile(req, res) { try { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ success: false, errors: errors.array() }); } const allowedUpdates = ['firstName', 'lastName', 'displayName', 'preferences']; const updates = {}; allowedUpdates.forEach(field => { if (req.body[field] !== undefined) { updates[field] = req.body[field]; } }); const user = await User.findByIdAndUpdate( req.user.id, updates, { new: true, runValidators: true } ).select('-passwordHash'); // Update cache await redisUtils.setex(`user:${user._id}`, 300, user); logger.info('Profile updated', { userId: req.user.id }); res.json({ success: true, data: user, message: 'Profile updated successfully' }); } catch (error) { logger.error('Update profile error:', error); res.status(500).json({ success: false, error: 'Failed to update profile' }); } } async changePassword(req, res) { try { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ success: false, errors: errors.array() }); } const { currentPassword, newPassword } = req.body; const user = await User.findById(req.user.id); // Verify current password const isValidPassword = await user.comparePassword(currentPassword); if (!isValidPassword) { return res.status(400).json({ success: false, error: 'Current password is incorrect' }); } // Update password user.passwordHash = newPassword; // Will be hashed by pre-save hook await user.save(); logger.info('Password changed', { userId: req.user.id }); res.json({ success: true, message: 'Password changed successfully' }); } catch (error) { logger.error('Change password error:', error); res.status(500).json({ success: false, error: 'Failed to change password' }); } } async forgotPassword(req, res) { try { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ success: false, errors: errors.array() }); } const { email } = req.body; const user = await User.findOne({ email }); // Always return success to prevent email enumeration res.json({ success: true, message: 'If an account with that email exists, a password reset link has been sent.' }); // If user exists, generate reset token and store it if (user) { const resetToken = user.generatePasswordResetToken(); await user.save(); logger.info('Password reset requested', { userId: user._id, email, resetToken: resetToken.substring(0, 8) + '...' // Log only partial token for security }); // In a production environment, you would send an email here // For now, we'll log the reset URL for development/testing const resetUrl = `${req.protocol}://${req.get('host')}/reset-password?token=${resetToken}`; logger.info('Password reset URL (DEV)', { resetUrl }); // TODO: Implement actual email sending service integration // Example: await emailService.sendPasswordResetEmail(user.email, resetUrl); } } catch (error) { logger.error('Forgot password error:', error); res.status(500).json({ success: false, error: 'Failed to process password reset request' }); } } async resetPassword(req, res) { try { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ success: false, errors: errors.array() }); } const { token, password } = req.body; // Validate token format if (!token || typeof token !== 'string' || token.length !== 64) { return res.status(400).json({ success: false, error: 'Invalid reset token' }); } // Find user by token const user = await User.findByPasswordResetToken(token); if (!user) { return res.status(400).json({ success: false, error: 'Invalid or expired reset token' }); } // Update password and clear reset token user.passwordHash = password; // Will be hashed by pre-save middleware user.passwordResetToken = null; user.passwordResetExpires = null; await user.save(); // Remove from cache await redisUtils.del(`user:${user._id}`); logger.info('Password reset completed', { userId: user._id, email: user.email }); res.json({ success: true, message: 'Password has been reset successfully' }); } catch (error) { logger.error('Reset password error:', error); res.status(500).json({ success: false, error: 'Failed to reset password' }); } } async verifyEmail(req, res) { try { const { token } = req.query; // Validate token format if (!token || typeof token !== 'string' || token.length !== 64) { return res.status(400).json({ success: false, error: 'Invalid verification token' }); } // Find user by verification token const user = await User.findByEmailVerificationToken(token); if (!user) { return res.status(400).json({ success: false, error: 'Invalid or expired verification token' }); } // Mark email as verified and clear verification token user.isVerified = true; user.emailVerificationToken = null; user.emailVerificationExpires = null; await user.save(); // Remove from cache await redisUtils.del(`user:${user._id}`); logger.info('Email verified', { userId: user._id, email: user.email }); res.json({ success: true, message: 'Email verified successfully', user: { id: user._id, email: user.email, isVerified: true } }); } catch (error) { logger.error('Verify email error:', error); res.status(500).json({ success: false, error: 'Failed to verify email' }); } } async resendVerification(req, res) { try { const { email } = req.body; if (!email) { return res.status(400).json({ success: false, error: 'Email is required' }); } const user = await User.findOne({ email }); // Always return success to prevent email enumeration res.json({ success: true, message: 'If an account with that email exists and is unverified, a verification email has been sent.' }); // If user exists and is not verified, send verification email if (user && !user.isVerified) { const verificationToken = user.generateEmailVerificationToken(); await user.save(); logger.info('Email verification resent', { userId: user._id, email, verificationToken: verificationToken.substring(0, 8) + '...' // Log only partial token for security }); // In a production environment, you would send an email here // For now, we'll log the verification URL for development/testing const verificationUrl = `${req.protocol}://${req.get('host')}/verify-email?token=${verificationToken}`; logger.info('Email verification URL (DEV)', { verificationUrl }); // TODO: Implement actual email sending service integration // Example: await emailService.sendVerificationEmail(user.email, verificationUrl); } } catch (error) { logger.error('Resend verification error:', error); res.status(500).json({ success: false, error: 'Failed to resend verification' }); } } async deleteAccount(req, res) { try { const user = await User.findById(req.user.id); // Soft delete - mark as inactive user.isActive = false; await user.save(); // Remove from cache await redisUtils.del(`user:${req.user.id}`); logger.info('Account deleted', { userId: req.user.id }); res.json({ success: true, message: 'Account deleted successfully' }); } catch (error) { logger.error('Delete account error:', error); res.status(500).json({ success: false, error: 'Failed to delete account' }); } } // Helper methods generateToken(user) { return jwt.sign( { id: user._id, email: user.email, role: user.role }, process.env.JWT_SECRET, { expiresIn: process.env.JWT_EXPIRES_IN || '24h' } ); } generateRefreshToken(user) { return jwt.sign( { id: user._id, type: 'refresh' }, process.env.JWT_REFRESH_SECRET, { expiresIn: process.env.JWT_REFRESH_EXPIRES_IN || '7d' } ); } } module.exports = new AuthController();