login.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. /**
  3. * File for the login action.
  4. *
  5. * Implements an action function to be called from the {@see Controller}.
  6. *
  7. * @category Action
  8. */
  9. /**
  10. * Logs the user in.
  11. *
  12. * Reads the POST parameters looking for the following KEYS:
  13. * uname
  14. * password
  15. * If there is a match, it sets cookies and session variables, and
  16. * redirects to the user homepage.
  17. *
  18. * @return int 0 on success, negative values on error.
  19. * @category Action
  20. * @global resource Database connection.
  21. */
  22. function action(){
  23. global $db;
  24. if (!isset($_POST['uname'], $_POST['password'])){
  25. header("Location: " . URL::BASE);
  26. exit();
  27. }
  28. $uname = SQLite3::escapeString($_POST['uname']);
  29. if (strlen($uname) == 0){
  30. header("Location: " . URL::BASE);
  31. exit();
  32. }
  33. $password = SQLite3::escapeString($_POST['password']);
  34. if (strlen($password) == 0){
  35. header("Location: " . URL::BASE);
  36. exit();
  37. }
  38. $password = hash('sha256', $password);
  39. $statement = $db->prepare("
  40. SELECT
  41. id,
  42. name
  43. FROM user
  44. WHERE
  45. (
  46. upper(name) = upper(:name) OR
  47. upper(mail) = upper(:mail)
  48. ) AND
  49. password = :password;
  50. ");
  51. $statement->bindValue(":name", $uname, SQLITE3_TEXT);
  52. $statement->bindValue(":mail", $uname, SQLITE3_TEXT);
  53. $statement->bindValue(":password", $password, SQLITE3_TEXT);
  54. $statement->execute();
  55. $r = $statement->execute()->fetchArray(SQLITE3_ASSOC);
  56. if (!$r){
  57. header("Location: " . URL::BASE);
  58. exit();
  59. die();
  60. return 401;
  61. }
  62. $user = $r["id"];
  63. // Generate token
  64. //$_COOKIE["user_token"]) && isset($COOKIE["user_id"])
  65. $token = bin2hex(random_bytes(32));
  66. $expiry = time() + 5 * 24 * 60 * 60; // 5 days
  67. $statement = $db->prepare("
  68. INSERT INTO token (user, token, expiry) VALUES
  69. (:user, :token, :expiry);
  70. ");
  71. $statement->bindValue(":user", $user, SQLITE3_INTEGER);
  72. $statement->bindValue(":token", hash('sha256', $token), SQLITE3_TEXT);
  73. $statement->bindValue(":expiry", $expiry, SQLITE3_INTEGER);
  74. $statement->execute();
  75. setcookie("user_id", $user, $expiry, "/");
  76. setcookie("user_token", $token, $expiry, "/");
  77. session_regenerate_id();
  78. $_SESSION['session'] = true;
  79. $_SESSION['user_id'] = $user;
  80. //header("Location: " . URL::BASE . "/$user/");
  81. // TODO: Get player ID here?
  82. header("Location: " . URL::BASE);
  83. exit();
  84. die();
  85. return 0;
  86. }
  87. ?>