All files / src/models User.js

80% Statements 92/115
65.38% Branches 34/52
79.16% Functions 19/24
87.23% Lines 82/94

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        27x 27x 27x 27x 27x 27x 27x 27x 27x 27x         1x 1x         26x             26x 26x         61x 61x         1x 1x         1x 1x   1x 1x 1x   1x                           17x     14x 1x             1x 1x 13x       14x 14x   14x   3x 3x 3x     11x 11x     11x 3x       14x 14x         20x 16x     15x 2x       13x 7x 7x   7x   7x                     13x         7x 7x   7x 7x 7x   7x 7x 7x   7x         3x 3x   3x 2x   2x         2x 2x   2x   2x 2x     2x 2x 2x 2x 2x   2x 2x                   29x 29x       1x
// Simple in-memory user storage for demonstration
// In a real application, this would be replaced with a database (MongoDB, PostgreSQL, etc.)
class User {
  constructor(id, email, password, name, createdAt) {
    this.id = id;
    this.email = email;
    this.password = password;
    this.name = name;
    this.createdAt = createdAt || new Date().toISOString();
    this.loginAttempts = 0;
    this.lastLoginAttempt = null;
    this.isLocked = false;
    this.passwordResetToken = null;
    this.passwordResetExpires = null;
  }
}
 
// In-memory storage
let users = [];
let nextId = 1;
 
class UserModel {
  // Create a new user
  static async create(userData) {
    const user = new User(
      nextId++,
      userData.email,
      userData.password,
      userData.name
    );
    
    users.push(user);
    return { ...user };
  }
 
  // Find user by email
  static async findByEmail(email) {
    const user = users.find(u => u.email === email);
    return user ? { ...user } : null;
  }
 
  // Find user by ID
  static async findById(id) {
    const user = users.find(u => u.id === parseInt(id));
    return user ? { ...user } : null;
  }
 
  // Update user
  static async update(id, updateData) {
    const userIndex = users.findIndex(u => u.id === parseInt(id));
    Iif (userIndex === -1) return null;
 
    const user = users[userIndex];
    const updatedUser = { ...user, ...updateData };
    users[userIndex] = updatedUser;
    
    return { ...updatedUser };
  }
 
  // Delete user
  static async delete(id) {
    const userIndex = users.findIndex(u => u.id === parseInt(id));
    if (userIndex === -1) return false;
 
    users.splice(userIndex, 1);
    return true;
  }
 
  // Track login attempt
  static async trackLoginAttempt(email, success) {
    let userIndex = users.findIndex(u => u.email === email);
    
    // If user doesn't exist and it's a failed attempt, create a temporary record
    if (userIndex === -1 && !success) {
      const tempUser = new User(
        nextId++,
        email,
        null, // No password for non-existent users
        null,  // No name for non-existent users
        new Date().toISOString()
      );
      users.push(tempUser);
      userIndex = users.length - 1;
    } else Iif (userIndex === -1) {
      return null; // User doesn't exist and it's a successful login (shouldn't happen)
    }
 
    const user = users[userIndex];
    const now = new Date();
 
    if (success) {
      // Reset login attempts on successful login
      user.loginAttempts = 0;
      user.isLocked = false;
      user.lastLoginAttempt = now;
    } else {
      // Increment failed attempts
      user.loginAttempts += 1;
      user.lastLoginAttempt = now;
      
      // Lock account after 3 failed attempts
      if (user.loginAttempts >= 3) {
        user.isLocked = true;
      }
    }
 
    users[userIndex] = user;
    return { ...user };
  }
 
  // Check if account is locked
  static async isAccountLocked(email) {
    const user = users.find(u => u.email === email);
    if (!user) return false;
    
    // Check if account is locked due to failed attempts
    if (user.isLocked) {
      return true;
    }
 
    // Auto-unlock after 2 seconds for testing (15 minutes in production)
    if (user.lastLoginAttempt) {
      const lockoutDuration = process.env.NODE_ENV === 'test' ? 2000 : 15 * 60 * 1000; // 2s for test, 15 min for production
      const timeSinceLastAttempt = new Date() - new Date(user.lastLoginAttempt);
      
      Iif (user.loginAttempts >= 3 && timeSinceLastAttempt < lockoutDuration) {
        return true;
      } else Iif (timeSinceLastAttempt >= lockoutDuration) {
        // Auto-unlock after timeout
        const userIndex = users.findIndex(u => u.email === email);
        if (userIndex !== -1) {
          users[userIndex].loginAttempts = 0;
          users[userIndex].isLocked = false;
        }
        return false;
      }
    }
 
    return false;
  }
 
  // Generate password reset token
  static async generatePasswordResetToken(email) {
    const userIndex = users.findIndex(u => u.email === email);
    Iif (userIndex === -1) return null;
 
    const user = users[userIndex];
    const resetToken = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
    const resetExpires = new Date(Date.now() + (process.env.NODE_ENV === 'test' ? 10000 : 60 * 60 * 1000)); // 10s for test, 1 hour for production
 
    user.passwordResetToken = resetToken;
    user.passwordResetExpires = resetExpires;
    users[userIndex] = user;
 
    return { ...user };
  }
 
  // Verify password reset token
  static async verifyPasswordResetToken(email, token) {
    const user = users.find(u => u.email === email);
    Iif (!user) return null;
 
    if (user.passwordResetToken !== token) return null;
    Iif (new Date() > new Date(user.passwordResetExpires)) return null;
 
    return { ...user };
  }
 
  // Reset password with token
  static async resetPassword(email, token, newPassword) {
    const userIndex = users.findIndex(u => u.email === email);
    Iif (userIndex === -1) return null;
 
    const user = users[userIndex];
    
    Iif (user.passwordResetToken !== token) return null;
    Iif (new Date() > new Date(user.passwordResetExpires)) return null;
 
    // Update password and clear reset token
    user.password = newPassword;
    user.passwordResetToken = null;
    user.passwordResetExpires = null;
    user.loginAttempts = 0;
    user.isLocked = false;
 
    users[userIndex] = user;
    return { ...user };
  }
 
  // Get all users (for testing purposes)
  static async findAll() {
    return users.map(user => ({ ...user }));
  }
 
  // Clear all users (for testing purposes)
  static async clear() {
    users = [];
    nextId = 1;
  }
}
 
module.exports = UserModel;