| 119 | {{{#!sql |
| 120 | <?php |
| 121 | session_start(); |
| 122 | session_regenerate_id(true); |
| 123 | |
| 124 | // Rate limiting check |
| 125 | if (isset($_SESSION['login_attempts']) && $_SESSION['login_attempts'] > 5) { |
| 126 | $timeout = 300; // 5 minutes timeout |
| 127 | if (time() - $_SESSION['last_attempt'] < $timeout) { |
| 128 | header("Location: /Sign&Log.php?error=TOO_MANY_ATTEMPTS"); |
| 129 | exit(); |
| 130 | } else { |
| 131 | $_SESSION['login_attempts'] = 0; |
| 132 | } |
| 133 | } |
| 134 | |
| 135 | // Input validation |
| 136 | if (empty($_POST['username']) || empty($_POST['password'])) { |
| 137 | header("Location: /Sign&Log.php?error=INVALID_CREDENTIALS"); |
| 138 | exit(); |
| 139 | } |
| 140 | |
| 141 | require 'connect.php'; |
| 142 | |
| 143 | try { |
| 144 | $username = trim(htmlspecialchars($_POST['username'])); |
| 145 | |
| 146 | $sql = "SELECT * FROM Users WHERE username = :username"; |
| 147 | $stmt = $conn->prepare($sql); |
| 148 | $stmt->bindParam(':username', $username, PDO::PARAM_STR); |
| 149 | $stmt->execute(); |
| 150 | |
| 151 | if ($stmt->rowCount() <= 0) { |
| 152 | $_SESSION['login_attempts'] = isset($_SESSION['login_attempts']) ? $_SESSION['login_attempts'] + 1 : 1; |
| 153 | $_SESSION['last_attempt'] = time(); |
| 154 | header("Location: /Sign&Log.php?error=INVALID_CREDENTIALS"); |
| 155 | exit(); |
| 156 | } |
| 157 | |
| 158 | $res = $stmt->fetch(PDO::FETCH_ASSOC); |
| 159 | |
| 160 | if (!password_verify($_POST['password'], $res['password'])) { |
| 161 | $_SESSION['login_attempts'] = isset($_SESSION['login_attempts']) ? $_SESSION['login_attempts'] + 1 : 1; |
| 162 | $_SESSION['last_attempt'] = time(); |
| 163 | header("Location: /Sign&Log.php?error=INVALID_CREDENTIALS"); |
| 164 | exit(); |
| 165 | } |
| 166 | |
| 167 | $_SESSION['username'] = $username; |
| 168 | $_SESSION['userid'] = $res['userid']; |
| 169 | $_SESSION['role'] = $res['role']; |
| 170 | $_SESSION['last_activity'] = time(); |
| 171 | $_SESSION['ip_address'] = $_SERVER['REMOTE_ADDR']; |
| 172 | |
| 173 | $_SESSION['login_attempts'] = 0; |
| 174 | |
| 175 | // Redirect based on role |
| 176 | if ($res['role'] == 'Admin') { |
| 177 | header("Location: ./Admin.php"); |
| 178 | } else { |
| 179 | header("Location: ./HomePage.php"); |
| 180 | } |
| 181 | |
| 182 | } catch (PDOException $e) { |
| 183 | error_log("Login error: " . $e->getMessage()); |
| 184 | header("Location: /Sign&Log.php?error=SERVER_ERROR"); |
| 185 | exit(); |
| 186 | } |
| 187 | }}} |