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 | 6x 6x 6x 6x 6x | const pool = require('../config/db'); const bcrypt = require('bcryptjs'); const validator = require('validator'); const crypto = require('crypto'); class User { static async create({ username, password, email, full_name, role = 'auditor' }) { try { // Validate all required fields if (!username || !password || !email || !full_name) { throw new Error('All fields are required: username, password, email, full_name'); } // Validate field lengths match database schema if (username.length > 50) throw new Error('Username must be 50 characters or less'); if (email.length > 100) throw new Error('Email must be 100 characters or less'); if (full_name.length > 100) throw new Error('Full name must be 100 characters or less'); // Validate email format if (!validator.isEmail(email)) { throw new Error('Invalid email format'); } // Validate password strength if (password.length < 8) { throw new Error('Password must be at least 8 characters'); } if (!/[A-Z]/.test(password)) { throw new Error('Password must contain at least one uppercase letter'); } if (!/[0-9]/.test(password)) { throw new Error('Password must contain at least one number'); } // Validate role matches enum const validRoles = ['auditor', 'manager', 'admin']; if (role && !validRoles.includes(role)) { throw new Error('Invalid user role'); } // Check for existing user const existingUser = await this.findByUsernameOrEmail(username, email); if (existingUser) { throw new Error('Username or email already exists'); } // Hash password with salt rounds const password_hash = await bcrypt.hash(password, 12); // Create user in database const [result] = await pool.query( `INSERT INTO users (username, password_hash, email, full_name, role, created_at) VALUES (?, ?, ?, ?, ?, NOW())`, [username, password_hash, email, full_name, role] ); // Return the new user's ID return result.insertId; } catch (error) { console.error('User creation error:', error); throw error; } } static async findByUsername(username) { if (!username || username.length > 50) return null; const [rows] = await pool.query( 'SELECT * FROM users WHERE username = ? LIMIT 1', [username] ); if (!rows || rows.length === 0) { return null; } return rows[0]; } static async findByEmail(email) { if (!email || email.length > 100) return null; const [rows] = await pool.query( 'SELECT * FROM users WHERE email = ? LIMIT 1', [email] ); return rows[0]; } static async findByUsernameOrEmail(username, email) { if ((!username || username.length > 50) && (!email || email.length > 100)) return null; const [rows] = await pool.query( 'SELECT * FROM users WHERE username = ? OR email = ? LIMIT 1', [username, email] ); return rows[0]; } static async findById(id) { if (!id || isNaN(id)) return null; const [rows] = await pool.query( `SELECT id, username, email, full_name, role, is_active, last_login, failed_login_attempts, created_at, updated_at FROM users WHERE id = ? LIMIT 1`, [id] ); return rows[0]; } static async updateLastLogin(id) { if (!id || isNaN(id)) return false; await pool.query( 'UPDATE users SET last_login = NOW() WHERE id = ?', [id] ); return true; } static async incrementFailedAttempts(id) { if (!id || isNaN(id)) return false; await pool.query( 'UPDATE users SET failed_login_attempts = failed_login_attempts + 1 WHERE id = ?', [id] ); return true; } static async resetFailedAttempts(id) { if (!id || isNaN(id)) return false; await pool.query( 'UPDATE users SET failed_login_attempts = 0 WHERE id = ?', [id] ); return true; } static async updatePassword(id, newPassword) { if (!id || isNaN(id) || !newPassword) return false; if (newPassword.length < 8) { throw new Error('Password must be at least 8 characters'); } const password_hash = await bcrypt.hash(newPassword, 12); await pool.query( 'UPDATE users SET password_hash = ?, password_reset_token = NULL, password_reset_expires = NULL WHERE id = ?', [password_hash, id] ); return true; } static async deactivateUser(id) { if (!id || isNaN(id)) return false; await pool.query( 'UPDATE users SET is_active = FALSE, updated_at = NOW() WHERE id = ?', [id] ); return true; } static async activateUser(id) { if (!id || isNaN(id)) return false; await pool.query( 'UPDATE users SET is_active = TRUE, updated_at = NOW() WHERE id = ?', [id] ); return true; } static async getAllUsers(options = {}) { const { page = 1, limit = 10, activeOnly = true, role = null } = options; const offset = (page - 1) * limit; let query = `SELECT id, username, email, full_name, role, is_active, last_login, created_at FROM users`; const params = []; const conditions = []; if (activeOnly) { conditions.push('is_active = TRUE'); } if (role) { conditions.push('role = ?'); params.push(role); } if (conditions.length) { query += ' WHERE ' + conditions.join(' AND '); } query += ' ORDER BY created_at DESC LIMIT ? OFFSET ?'; params.push(limit, offset); const [rows] = await pool.query(query, params); return rows; } static async comparePassword(password, hash) { if (!password || !hash) return false; return await bcrypt.compare(password, hash); } static async generateResetToken() { return crypto.randomBytes(32).toString('hex'); } static async setResetToken(email, token, expires) { if (!email || !token || !expires) return false; await pool.query( `UPDATE users SET password_reset_token = ?, password_reset_expires = ? WHERE email = ?`, [token, expires, email] ); return true; } static async findByResetToken(token) { if (!token) return null; const [rows] = await pool.query( `SELECT * FROM users WHERE password_reset_token = ? AND password_reset_expires > NOW() LIMIT 1`, [token] ); return rows[0]; } static async clearResetToken(id) { if (!id || isNaN(id)) return false; await pool.query( `UPDATE users SET password_reset_token = NULL, password_reset_expires = NULL WHERE id = ?`, [id] ); return true; } static async countUsers(activeOnly = true) { const [rows] = await pool.query( `SELECT COUNT(*) AS count FROM users ${activeOnly ? 'WHERE is_active = TRUE' : ''}` ); return rows[0].count; } static async updateProfile(id, updates) { if (!id || isNaN(id) || !updates || typeof updates !== 'object') { return false; } const allowedFields = ['full_name', 'email']; const fieldsToUpdate = {}; // Filter only allowed fields for (const field in updates) { if (allowedFields.includes(field)) { fieldsToUpdate[field] = updates[field]; } } if (Object.keys(fieldsToUpdate).length === 0) { return false; } // Validate email if being updated if (fieldsToUpdate.email) { if (fieldsToUpdate.email.length > 100) { throw new Error('Email must be 100 characters or less'); } if (!validator.isEmail(fieldsToUpdate.email)) { throw new Error('Invalid email format'); } // Check if email already exists const existingUser = await this.findByEmail(fieldsToUpdate.email); if (existingUser && existingUser.id !== id) { throw new Error('Email already in use by another account'); } } // Validate full_name if being updated if (fieldsToUpdate.full_name && fieldsToUpdate.full_name.length > 100) { throw new Error('Full name must be 100 characters or less'); } const setClause = Object.keys(fieldsToUpdate) .map(field => `${field} = ?`) .join(', '); const values = Object.values(fieldsToUpdate); values.push(id); await pool.query( `UPDATE users SET ${setClause}, updated_at = NOW() WHERE id = ?`, values ); return true; } static async changeRole(id, newRole) { if (!id || isNaN(id) || !newRole) return false; const validRoles = ['auditor', 'manager', 'admin']; if (!validRoles.includes(newRole)) { throw new Error('Invalid user role'); } await pool.query( 'UPDATE users SET role = ?, updated_at = NOW() WHERE id = ?', [newRole, id] ); return true; } } module.exports = User; |