| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394 |
- <?php
- /**
- * File for the login action.
- *
- * Implements an action function to be called from the {@see Controller}.
- *
- * @author Iñigo Valentin <i@inigovalentin.com>
- * @license https://www.gnu.org/licenses/gpl-3.0.en.html GNU General Public License V3
- * @package SWDB
- */
- /**
- * Logs the user in.
- *
- * Reads the POST parameters looking for the following KEYS:
- * uname: username or email.
- * password: password.
- * If there is a match, it generates a token and sets cookies and session variablesand
- * redirects to the user homepage.
- *
- * @return int 201 on success, HTTP error codes on failure.
- * @category Action
- */
- function action(){
- if (!isset($_POST['uname'], $_POST['password'])){
- header("Location: " . URL::BASE);
- //exit();
- return 400;
- }
- $uname = SQLite3::escapeString($_POST['uname']);
- if (strlen($uname) == 0){
- header("Location: " . URL::BASE);
- //exit();
- return 400;
- }
- $password = SQLite3::escapeString($_POST['password']);
- if (strlen($password) == 0){
- header("Location: " . URL::BASE);
- return 400;
- //exit();
- }
- $password = hash('sha256', $password);
- $statement = get_context()->get_db()->prepare("
- SELECT
- id,
- name
- FROM user
- WHERE
- (
- upper(name) = upper(:name) OR
- upper(mail) = upper(:mail)
- ) AND
- password = :password;
- ");
- $statement->bindValue(":name", $uname, SQLITE3_TEXT);
- $statement->bindValue(":mail", $uname, SQLITE3_TEXT);
- $statement->bindValue(":password", $password, SQLITE3_TEXT);
- $statement->execute();
- $r = $statement->execute()->fetchArray(SQLITE3_ASSOC);
- if (!$r){
- header("Location: " . URL::BASE);
- //exit();
- //die();
- return 400;
- }
- $user = $r["id"];
- // Generate token
- //$_COOKIE["user_token"]) && isset($COOKIE["user_id"])
- $token = bin2hex(random_bytes(32));
- $expiry = time() + 5 * 24 * 60 * 60; // 5 days
- $statement = get_context()->get_db()->prepare("
- INSERT INTO token (user, token, expiry) VALUES
- (:user, :token, :expiry);
- ");
- $statement->bindValue(":user", $user, SQLITE3_INTEGER);
- $statement->bindValue(":token", hash('sha256', $token), SQLITE3_TEXT);
- $statement->bindValue(":expiry", $expiry, SQLITE3_INTEGER);
- $statement->execute();
- setcookie("user_id", $user, $expiry, "/");
- setcookie("user_token", $token, $expiry, "/");
- session_regenerate_id();
- $_SESSION['session'] = true;
- $_SESSION['user_id'] = $user;
- //header("Location: " . URL::BASE . "/$user/");
- // TODO: Get player ID here?
- header("Location: " . URL::BASE);
- exit();
- die();
- return 201;
- }
- ?>
|