redirectToDashboard(); } $errors = []; $form_data = []; $resend_success = ''; $show_resend = false; $resend_email = ''; // Handle resend verification request if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'resend_verification') { $resend_email = isset($_POST['email']) ? sanitize($_POST['email']) : ''; $form_data['email'] = $resend_email; if (empty($resend_email) || !validateEmail($resend_email)) { $errors[] = 'Please provide a valid email address.'; } else { try { $db = new Database(); $pdo = $db->getConnection(); $clientIP = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0'; // Rate limit: max 3 resend attempts per IP per hour try { $stmt = $pdo->prepare("SELECT COUNT(*) as cnt FROM registration_attempts WHERE ip_address = ? AND attempt_type = 'resend_verification' AND created_at > DATE_SUB(NOW(), INTERVAL 1 HOUR)"); $stmt->execute([$clientIP]); $attempts = $stmt->fetch(); if ($attempts && $attempts['cnt'] >= 3) { $errors[] = 'Too many resend attempts. Please try again later or contact support.'; } } catch (Exception $e) {} if (empty($errors)) { // Find the user $stmt = $pdo->prepare("SELECT id, email, email_verified, status FROM users WHERE email = ?"); $stmt->execute([$resend_email]); $user = $stmt->fetch(); if (!$user) { // Don't reveal if email exists - show generic success $resend_success = 'If an account with that email exists and is unverified, a new verification link has been sent. Please check your inbox and spam folder.'; } elseif ($user['email_verified']) { $resend_success = 'This email is already verified. You can log in directly.'; } else { // Delete old verification tokens $pdo->prepare("DELETE FROM email_verifications WHERE user_id = ?")->execute([$user['id']]); // Generate new token $verificationToken = generateSecureToken(); $expiresAt = date('Y-m-d H:i:s', strtotime('+' . TOKEN_EXPIRY_HOURS . ' hours')); $stmt = $pdo->prepare("INSERT INTO email_verifications (user_id, token, expires_at, created_at) VALUES (?, ?, ?, NOW())"); $stmt->execute([$user['id'], $verificationToken, $expiresAt]); // Send verification email require_once 'email.php'; $emailHandler = new EmailHandler(); $emailSent = $emailHandler->sendVerificationEmail($resend_email, $verificationToken); if ($emailSent) { logError('Verification email resent', ['user_id' => $user['id'], 'email' => $resend_email]); $resend_success = 'A new verification link has been sent to your email. Please check your inbox and spam folder. The link expires in ' . TOKEN_EXPIRY_HOURS . ' hours.'; } else { logError('Failed to resend verification email', ['user_id' => $user['id'], 'email' => $resend_email]); $errors[] = 'Failed to send verification email. Please try again or contact support@relevantreflex.com.'; } } // Log the attempt try { $pdo->prepare("INSERT INTO registration_attempts (ip_address, email, attempt_type, success, user_agent) VALUES (?, ?, 'resend_verification', ?, ?)") ->execute([$clientIP, $resend_email, empty($errors) ? 1 : 0, $_SERVER['HTTP_USER_AGENT'] ?? '']); } catch (Exception $e) {} } } catch (Exception $e) { logError('Error in resend verification: ' . $e->getMessage()); $errors[] = 'System error. Please try again later.'; } } } // Handle login form submission if ($_SERVER['REQUEST_METHOD'] === 'POST' && !isset($_POST['action'])) { // Initialize database try { $db = new Database(); $pdo = $db->getConnection(); } catch (Exception $e) { logError('Database connection failed in login.php: ' . $e->getMessage()); $errors[] = 'System error. Please try again later.'; } if (empty($errors)) { // Get and sanitize form data $email = isset($_POST['email']) ? sanitize($_POST['email']) : ''; $password = isset($_POST['password']) ? $_POST['password'] : ''; $rememberMe = isset($_POST['remember_me']) ? true : false; // Store email for form repopulation $form_data['email'] = $email; // Validation if (empty($email) || empty($password)) { $errors[] = 'Please provide both email and password.'; } elseif (!validateEmail($email)) { $errors[] = 'Please provide a valid email address.'; } else { try { // Find user by email $stmt = $pdo->prepare(" SELECT id, email, password, email_verified, status, last_login FROM users WHERE email = ? "); $stmt->execute([$email]); $user = $stmt->fetch(); if (!$user) { // Log failed login attempt logError('Login attempt with non-existent email', ['email' => $email]); $errors[] = 'Invalid email or password.'; } elseif (!verifyPassword($password, $user['password'])) { logError('Login attempt with incorrect password', ['email' => $email]); $errors[] = 'Invalid email or password.'; } elseif (!$user['email_verified']) { $errors[] = 'Your email is not yet verified.'; $show_resend = true; $resend_email = $email; } elseif ($user['status'] !== 'active') { $message = 'Your account is currently ' . $user['status'] . '.'; if ($user['status'] === 'suspended') { $message .= ' Please contact support for assistance.'; } $errors[] = $message; } else { // Login successful - create session session_start(); $_SESSION['user_id'] = $user['id']; $_SESSION['user_email'] = $user['email']; $_SESSION['logged_in'] = true; $_SESSION['login_time'] = time(); // Update last login time $stmt = $pdo->prepare("UPDATE users SET last_login = NOW() WHERE id = ?"); $stmt->execute([$user['id']]); // Set remember me cookie if requested (30 days) if ($rememberMe) { $sessionToken = generateSecureToken(); $expiresAt = date('Y-m-d H:i:s', strtotime('+30 days')); // Store session token in database $stmt = $pdo->prepare(" INSERT INTO user_sessions (user_id, session_token, expires_at) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE session_token = VALUES(session_token), expires_at = VALUES(expires_at) "); $stmt->execute([$user['id'], $sessionToken, $expiresAt]); // Set cookie setcookie('remember_token', $sessionToken, time() + (30 * 24 * 60 * 60), '/', '', true, true); } // Clean up expired sessions $pdo->prepare("DELETE FROM user_sessions WHERE expires_at < NOW()")->execute(); // Log successful login logError('User login successful', [ 'user_id' => $user['id'], 'email' => $user['email'], 'remember_me' => $rememberMe ]); // Redirect to dashboard header('Location: dashboard.php'); exit; } } catch (PDOException $e) { logError('Database error during login', [ 'error' => $e->getMessage(), 'email' => $email ]); $errors[] = 'Login failed due to a system error. Please try again later.'; } catch (Exception $e) { logError('General error during login', [ 'error' => $e->getMessage(), 'email' => $email ]); $errors[] = 'An unexpected error occurred. Please try again later.'; } } } } ?>
You can take Online paid Surveys, Redeem your reward points and update profile - all in one place.
Didn't receive the verification email? We can send a new one.