auth.php 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. <?php
  2. /**
  3. * lib/auth.php
  4. *
  5. * Authentication and authorisation functions.
  6. * Requires config/database.php to be included before use.
  7. */
  8. if (session_status() === PHP_SESSION_NONE) {
  9. session_start();
  10. }
  11. // ---------------------------------------------------------------------------
  12. // Session helpers
  13. // ---------------------------------------------------------------------------
  14. function isLoggedIn(): bool
  15. {
  16. return isset($_SESSION['user_id']) && !empty($_SESSION['user_id']);
  17. }
  18. function getCurrentUserId(): ?int
  19. {
  20. return isset($_SESSION['user_id']) ? (int) $_SESSION['user_id'] : null;
  21. }
  22. function getCurrentUser(): ?array
  23. {
  24. if (!isLoggedIn()) {
  25. return null;
  26. }
  27. return [
  28. 'id' => (int) $_SESSION['user_id'],
  29. 'fullname' => $_SESSION['user_name'] ?? '',
  30. 'email' => $_SESSION['user_email'] ?? '',
  31. ];
  32. }
  33. function requireLogin(): void
  34. {
  35. if (!isLoggedIn()) {
  36. $current = $_SERVER['REQUEST_URI'] ?? '';
  37. $redirect = $current !== '' ? '?redirect=' . urlencode($current) : '';
  38. header('Location: /login/login.php' . $redirect);
  39. exit;
  40. }
  41. }
  42. function hasPermission(string $permission): bool
  43. {
  44. // Stub — extend with role checks when roles are introduced
  45. return isLoggedIn();
  46. }
  47. // ---------------------------------------------------------------------------
  48. // Login / Logout
  49. // ---------------------------------------------------------------------------
  50. /**
  51. * Attempt login with email + plain-text password.
  52. * Returns user row array on success, null on failure.
  53. */
  54. function loginUser(string $email, string $password): ?array
  55. {
  56. $pdo = getDBConnection();
  57. $stmt = $pdo->prepare(
  58. 'SELECT id, fullname, email, password FROM users WHERE email = ? AND active = 1 LIMIT 1'
  59. );
  60. $stmt->execute([strtolower(trim($email))]);
  61. $user = $stmt->fetch();
  62. if (!$user || !password_verify($password, $user['password'])) {
  63. return null;
  64. }
  65. // Rehash on cost/algorithm upgrade
  66. if (password_needs_rehash($user['password'], PASSWORD_DEFAULT)) {
  67. $pdo->prepare('UPDATE users SET password = ? WHERE id = ?')
  68. ->execute([password_hash($password, PASSWORD_DEFAULT), $user['id']]);
  69. }
  70. session_regenerate_id(true);
  71. $_SESSION['user_id'] = $user['id'];
  72. $_SESSION['user_name'] = $user['fullname'];
  73. $_SESSION['user_email'] = $user['email'];
  74. return $user;
  75. }
  76. /**
  77. * Destroy session completely and clear the session cookie.
  78. */
  79. function logoutUser(): void
  80. {
  81. $_SESSION = [];
  82. if (ini_get('session.use_cookies')) {
  83. $p = session_get_cookie_params();
  84. setcookie(
  85. session_name(), '', time() - 42000,
  86. $p['path'], $p['domain'], $p['secure'], $p['httponly']
  87. );
  88. }
  89. session_destroy();
  90. }
  91. // ---------------------------------------------------------------------------
  92. // Registration
  93. // ---------------------------------------------------------------------------
  94. /**
  95. * Register a new user.
  96. * Returns ['success' => true, 'user_id' => int]
  97. * or ['success' => false, 'error' => string]
  98. */
  99. function registerUser(array $data): array
  100. {
  101. $pdo = getDBConnection();
  102. $email = strtolower(trim($data['email'] ?? ''));
  103. // Duplicate email check
  104. $stmt = $pdo->prepare('SELECT id FROM users WHERE email = ? LIMIT 1');
  105. $stmt->execute([$email]);
  106. if ($stmt->fetch()) {
  107. return ['success' => false, 'error' => 'An account with that email already exists.'];
  108. }
  109. $stmt = $pdo->prepare('
  110. INSERT INTO users
  111. (fullname, email, password, company, mobilephone, industry, role, city, state, postcode, country, active, created_at)
  112. VALUES
  113. (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, NOW())
  114. ');
  115. $stmt->execute([
  116. trim($data['fullname'] ?? ''),
  117. $email,
  118. password_hash($data['password'], PASSWORD_DEFAULT),
  119. trim($data['company'] ?? ''),
  120. trim($data['mobilephone'] ?? ''),
  121. $data['industry'] ?? '',
  122. $data['role'] ?? '',
  123. trim($data['city'] ?? ''),
  124. $data['state'] ?? '',
  125. trim($data['postcode'] ?? ''),
  126. $data['country'] ?? 'Australia',
  127. ]);
  128. return ['success' => true, 'user_id' => (int) $pdo->lastInsertId()];
  129. }
  130. // ---------------------------------------------------------------------------
  131. // Password reset
  132. // ---------------------------------------------------------------------------
  133. /**
  134. * Create a password-reset token for $email (1-hour expiry).
  135. * Returns the raw token string, or null if the email doesn't exist.
  136. */
  137. function createPasswordResetToken(string $email): ?string
  138. {
  139. $pdo = getDBConnection();
  140. $email = strtolower(trim($email));
  141. $stmt = $pdo->prepare('SELECT id FROM users WHERE email = ? AND active = 1 LIMIT 1');
  142. $stmt->execute([$email]);
  143. if (!$stmt->fetch()) {
  144. return null;
  145. }
  146. // Remove any previous tokens for this email
  147. $pdo->prepare('DELETE FROM password_resets WHERE email = ?')->execute([$email]);
  148. $token = bin2hex(random_bytes(32));
  149. $pdo->prepare(
  150. 'INSERT INTO password_resets (email, token, created_at, expires_at)
  151. VALUES (?, ?, NOW(), DATE_ADD(NOW(), INTERVAL 1 HOUR))'
  152. )->execute([$email, $token]);
  153. return $token;
  154. }
  155. /**
  156. * Validate a reset token. Returns the associated email on success, null if invalid/expired.
  157. */
  158. function validatePasswordResetToken(string $token): ?string
  159. {
  160. $pdo = getDBConnection();
  161. $stmt = $pdo->prepare(
  162. 'SELECT email FROM password_resets WHERE token = ? AND expires_at > NOW() LIMIT 1'
  163. );
  164. $stmt->execute([$token]);
  165. $row = $stmt->fetch();
  166. return $row ? $row['email'] : null;
  167. }
  168. /**
  169. * Update the user's password and delete the reset token.
  170. */
  171. function resetPassword(string $token, string $newPassword): bool
  172. {
  173. $pdo = getDBConnection();
  174. $email = validatePasswordResetToken($token);
  175. if (!$email) {
  176. return false;
  177. }
  178. $pdo->prepare('UPDATE users SET password = ? WHERE email = ?')
  179. ->execute([password_hash($newPassword, PASSWORD_DEFAULT), $email]);
  180. $pdo->prepare('DELETE FROM password_resets WHERE email = ?')->execute([$email]);
  181. return true;
  182. }
  183. /**
  184. * Change password for currently logged-in user after verifying old password.
  185. * Returns true on success, false if old password is wrong.
  186. */
  187. function changePassword(int $userId, string $oldPassword, string $newPassword): bool
  188. {
  189. $pdo = getDBConnection();
  190. $stmt = $pdo->prepare('SELECT password FROM users WHERE id = ? LIMIT 1');
  191. $stmt->execute([$userId]);
  192. $user = $stmt->fetch();
  193. if (!$user || !password_verify($oldPassword, $user['password'])) {
  194. return false;
  195. }
  196. $pdo->prepare('UPDATE users SET password = ? WHERE id = ?')
  197. ->execute([password_hash($newPassword, PASSWORD_DEFAULT), $userId]);
  198. return true;
  199. }