All files / src/controllers authController.js

88.09% Statements 74/84
75.55% Branches 34/45
100% Functions 6/6
88.09% Lines 74/84

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 2681x 1x 1x         27x 27x     27x 27x 1x             26x 26x     26x             26x             26x   26x                       16x 16x     16x 16x 2x             14x 14x   1x 1x             13x     13x   13x 10x 10x   10x 7x         3x               3x             3x   3x                       8x 8x     8x 8x   1x           7x           7x                       3x 3x     3x 3x 1x             2x 2x     2x   2x             2x                   1x 1x 1x   1x               1x   1x                   3x 3x 3x     3x 3x 3x 1x             2x               2x 2x 2x 1x               1x   1x               1x   1x                   1x
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const User = require('../models/User');
 
class AuthController {
  // Register a new user
  async register(req, res, next) {
    try {
      const { email, password, name } = req.body;
 
      // Check if user already exists
      const existingUser = await User.findByEmail(email);
      if (existingUser) {
        return res.status(409).json({
          error: 'User already exists',
          message: 'A user with this email address already exists'
        });
      }
 
      // Hash password
      const saltRounds = parseInt(process.env.BCRYPT_ROUNDS) || 12;
      const hashedPassword = await bcrypt.hash(password, saltRounds);
 
      // Create user
      const user = await User.create({
        email,
        password: hashedPassword,
        name
      });
 
      // Generate JWT token
      const token = jwt.sign(
        { userId: user.id, email: user.email },
        process.env.JWT_SECRET,
        { expiresIn: process.env.JWT_EXPIRES_IN || '24h' }
      );
 
      // Return user data (without password) and token
      const { password: _, ...userWithoutPassword } = user;
      
      res.status(201).json({
        message: 'User registered successfully',
        user: userWithoutPassword,
        token
      });
    } catch (error) {
      next(error);
    }
  }
 
  // Login user
  async login(req, res, next) {
    try {
      const { email, password } = req.body;
 
      // Check if account is locked
      const isLocked = await User.isAccountLocked(email);
      if (isLocked) {
        return res.status(423).json({
          error: 'Account locked',
          message: 'Your account has been locked due to multiple failed login attempts. Please wait 15 minutes or reset your password.'
        });
      }
 
      // Find user by email
      const user = await User.findByEmail(email);
      if (!user) {
        // Track failed attempt even for non-existent users
        await User.trackLoginAttempt(email, false);
        return res.status(401).json({
          error: 'Authentication failed',
          message: 'Invalid email or password'
        });
      }
 
      // Verify password
      const isPasswordValid = user.password ? await bcrypt.compare(password, user.password) : false;
      
      // Track login attempt
      await User.trackLoginAttempt(email, isPasswordValid);
      
      if (!isPasswordValid) {
        const updatedUser = await User.findByEmail(email);
        const remainingAttempts = 3 - updatedUser.loginAttempts;
        
        if (remainingAttempts > 0) {
          return res.status(401).json({
            error: 'Authentication failed',
            message: `Invalid email or password. ${remainingAttempts} attempts remaining.`
          });
        } else {
          return res.status(423).json({
            error: 'Account locked',
            message: 'Your account has been locked due to multiple failed login attempts. Please wait 15 minutes or reset your password.'
          });
        }
      }
 
      // Generate JWT token
      const token = jwt.sign(
        { userId: user.id, email: user.email },
        process.env.JWT_SECRET,
        { expiresIn: process.env.JWT_EXPIRES_IN || '24h' }
      );
 
      // Return user data (without password) and token
      const { password: _, ...userWithoutPassword } = user;
      
      res.status(200).json({
        message: 'Login successful',
        user: userWithoutPassword,
        token
      });
    } catch (error) {
      next(error);
    }
  }
 
  // Request password reset
  async requestPasswordReset(req, res, next) {
    try {
      const { email } = req.body;
 
      // Check if user exists
      const user = await User.findByEmail(email);
      if (!user) {
        // Don't reveal if user exists or not for security
        return res.status(200).json({
          message: 'If an account with this email exists, a password reset link has been sent.'
        });
      }
 
      // Generate password reset token
      const userWithToken = await User.generatePasswordResetToken(email);
      
      // In a real application, you would send an email here
      // For demonstration, we'll return the token in the response
      // In production, this should be sent via email
      
      res.status(200).json({
        message: 'Password reset link sent to your email',
        resetToken: userWithToken.passwordResetToken, // Remove this in production
        expiresIn: '1 hour'
      });
    } catch (error) {
      next(error);
    }
  }
 
  // Reset password with token
  async resetPassword(req, res, next) {
    try {
      const { email, token, newPassword } = req.body;
 
      // Verify token
      const user = await User.verifyPasswordResetToken(email, token);
      if (!user) {
        return res.status(400).json({
          error: 'Invalid or expired token',
          message: 'The password reset token is invalid or has expired'
        });
      }
 
      // Hash new password
      const saltRounds = parseInt(process.env.BCRYPT_ROUNDS) || 12;
      const hashedPassword = await bcrypt.hash(newPassword, saltRounds);
 
      // Reset password
      const updatedUser = await User.resetPassword(email, token, hashedPassword);
      
      Iif (!updatedUser) {
        return res.status(400).json({
          error: 'Password reset failed',
          message: 'Unable to reset password. Please try again.'
        });
      }
 
      res.status(200).json({
        message: 'Password reset successfully. You can now login with your new password.'
      });
    } catch (error) {
      next(error);
    }
  }
 
  // Get user profile
  async getProfile(req, res, next) {
    try {
      const userId = req.user.userId;
      const user = await User.findById(userId);
      
      Iif (!user) {
        return res.status(404).json({
          error: 'User not found',
          message: 'User profile not found'
        });
      }
 
      // Return user data without password
      const { password, ...userWithoutPassword } = user;
      
      res.status(200).json({
        user: userWithoutPassword
      });
    } catch (error) {
      next(error);
    }
  }
 
  // Update user profile
  async updateProfile(req, res, next) {
    try {
      const userId = req.user.userId;
      const { name, email } = req.body;
 
      // Validate input
      Eif (email) {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(email)) {
          return res.status(400).json({
            error: 'Invalid email format',
            message: 'Please provide a valid email address'
          });
        }
      }
 
      Iif (name && (name.length < 2 || name.length > 50)) {
        return res.status(400).json({
          error: 'Invalid name length',
          message: 'Name must be between 2 and 50 characters'
        });
      }
 
      // Check if email is already taken by another user
      Eif (email) {
        const existingUser = await User.findByEmail(email);
        if (existingUser && existingUser.id !== userId) {
          return res.status(409).json({
            error: 'Email already exists',
            message: 'This email address is already in use'
          });
        }
      }
 
      // Update user
      const updatedUser = await User.update(userId, { name, email });
      
      Iif (!updatedUser) {
        return res.status(404).json({
          error: 'User not found',
          message: 'User profile not found'
        });
      }
 
      // Return updated user data without password
      const { password, ...userWithoutPassword } = updatedUser;
      
      res.status(200).json({
        message: 'Profile updated successfully',
        user: userWithoutPassword
      });
    } catch (error) {
      next(error);
    }
  }
}
 
module.exports = new AuthController();