login.php 2.9 KB

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