Advertisement
TechGeek

login.php

Sep 16th, 2020 (edited)
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 4.21 KB | None | 0 0
  1. <?php
  2.  
  3. declare(strict_types=1);
  4.  
  5. // Start session.
  6. session_start();
  7.  
  8. // Include helper functions.
  9. require_once 'helpers.php';
  10.  
  11. // Redirect user to homepage/dashboard if authenticated.
  12. if (check_auth()) {
  13.     redirect('index.php');
  14.     return;
  15. }
  16.  
  17. if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  18.     $pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8mb4', 'root', '', [
  19.         PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
  20.         PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
  21.         PDO::ATTR_EMULATE_PREPARES   => false,
  22.     ]);
  23.     $stmt = $pdo->prepare('SELECT * FROM accounts WHERE username = ?');
  24.     $stmt->execute([$_POST['username']]);
  25.     $user = $stmt->fetch();
  26.  
  27.     if (! ($user && password_verify($_POST['password'], $user->password))) {
  28.         echo json_encode([
  29.             'success' => false,
  30.             'message' => 'These credentials don\'t match our records.',
  31.         ]);
  32.         return;
  33.     }
  34.  
  35.     // Log user in if another is not authenticated.
  36.     if (filesize('current_user.txt') === 0) {
  37.         file_put_contents('current_user.txt', json_encode([
  38.             'user_id'    => $user->id,
  39.             'created_at' => (new DateTime('now'))->format('Y-m-d H:i:s'),
  40.         ]));
  41.  
  42.         $_SESSION['user_id'] = $user->id;
  43.  
  44.         echo json_encode([
  45.             'success' => true,
  46.         ]);
  47.  
  48.         return;
  49.     }
  50.  
  51.     $trace = json_decode(file_get_contents('current_user.txt'));
  52.  
  53.     // Log user in if the last authenticated user is himself/herself.
  54.     if ((int) $trace->user_id === $user->id) {
  55.         $trace->created_at = (new DateTime('now'))->format('Y-m-d H:i:s');
  56.  
  57.         file_put_contents('current_user.txt', json_encode($trace));
  58.  
  59.         $_SESSION['user_id'] = $user->id;
  60.  
  61.         echo json_encode([
  62.             'success' => true,
  63.         ]);
  64.  
  65.         return;
  66.     }
  67.  
  68.     // Ask user if he/she wants to take over.
  69.     echo json_encode([
  70.         'success'  => false,
  71.         'takeover' => true,
  72.         'message'  => 'Another user is logged in. Do you want to take over?',
  73.     ]);
  74.  
  75.     return;
  76. }
  77.  
  78. ?>
  79.  
  80. <!doctype html>
  81. <html lang="en">
  82. <head>
  83.     <meta charset="UTF-8">
  84.     <meta name="viewport"
  85.           content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  86.     <meta http-equiv="X-UA-Compatible" content="ie=edge">
  87.     <title>Login</title>
  88. </head>
  89. <body>
  90.     <form method="post" id="form">
  91.         <div>
  92.             <label for="email">Email:</label>
  93.             <input type="text" name="username" placeholder="Username" id="username" required>
  94.         </div>
  95.         <div>
  96.             <label for="password">Password:</label>
  97.             <input type="password" id="password" name="password" placeholder="Password">
  98.         </div>
  99.         <div>
  100.             <span id="message" style="color: red;"></span>
  101.         </div>
  102.         <button>Log in</button>
  103.     </form>
  104.     <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
  105.     <script>
  106.         $(function () {
  107.             $('#form').submit(function (e) {
  108.                 e.preventDefault();
  109.                 $('#message').text('');
  110.  
  111.                 $.post('login.php', $(this).serialize(), function (response) {
  112.                     const res = JSON.parse(response);
  113.  
  114.                     if (res.takeover) {
  115.                         // Ask user if he/she wants to take over. If user confirms, run `confirmed()` function.
  116.                         confirm(res.message) && confirmed();
  117.                         return;
  118.                     }
  119.  
  120.                     if (res.success) {
  121.                         // Login is successful. Reload or redirect user to another page.
  122.                         location.reload();
  123.                     } else {
  124.                         // Login failed. Incorrect email or password entered.
  125.                         $('#message').text(res.message || '');
  126.                     }
  127.                 });
  128.             });
  129.  
  130.             function confirmed() {
  131.                 $.post('confirmed.php', function (response) {
  132.                     const res = JSON.parse(response);
  133.                     console.log(res.data);
  134.                 });
  135.             }
  136.         });
  137.     </script>
  138. </body>
  139. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement