login.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. */
  21. function action(){
  22. if (!isset($_POST['uname'], $_POST['password'])){
  23. header("Location: " . URL::BASE);
  24. exit();
  25. }
  26. $uname = SQLite3::escapeString($_POST['uname']);
  27. if (strlen($uname) == 0){
  28. header("Location: " . URL::BASE);
  29. exit();
  30. }
  31. $password = SQLite3::escapeString($_POST['password']);
  32. if (strlen($password) == 0){
  33. header("Location: " . URL::BASE);
  34. exit();
  35. }
  36. $password = hash('sha256', $password);
  37. $statement = get_context()->get_db()->prepare("
  38. SELECT
  39. id,
  40. name
  41. FROM user
  42. WHERE
  43. (
  44. upper(name) = upper(:name) OR
  45. upper(mail) = upper(:mail)
  46. ) AND
  47. password = :password;
  48. ");
  49. $statement->bindValue(":name", $uname, SQLITE3_TEXT);
  50. $statement->bindValue(":mail", $uname, SQLITE3_TEXT);
  51. $statement->bindValue(":password", $password, SQLITE3_TEXT);
  52. $statement->execute();
  53. $r = $statement->execute()->fetchArray(SQLITE3_ASSOC);
  54. if (!$r){
  55. header("Location: " . URL::BASE);
  56. exit();
  57. die();
  58. return 401;
  59. }
  60. $user = $r["id"];
  61. // Generate token
  62. //$_COOKIE["user_token"]) && isset($COOKIE["user_id"])
  63. $token = bin2hex(random_bytes(32));
  64. $expiry = time() + 5 * 24 * 60 * 60; // 5 days
  65. $statement = get_context()->get_db()->prepare("
  66. INSERT INTO token (user, token, expiry) VALUES
  67. (:user, :token, :expiry);
  68. ");
  69. $statement->bindValue(":user", $user, SQLITE3_INTEGER);
  70. $statement->bindValue(":token", hash('sha256', $token), SQLITE3_TEXT);
  71. $statement->bindValue(":expiry", $expiry, SQLITE3_INTEGER);
  72. $statement->execute();
  73. setcookie("user_id", $user, $expiry, "/");
  74. setcookie("user_token", $token, $expiry, "/");
  75. session_regenerate_id();
  76. $_SESSION['session'] = true;
  77. $_SESSION['user_id'] = $user;
  78. //header("Location: " . URL::BASE . "/$user/");
  79. // TODO: Get player ID here?
  80. header("Location: " . URL::BASE);
  81. exit();
  82. die();
  83. return 0;
  84. }
  85. ?>