* @license https://www.gnu.org/licenses/gpl-3.0.en.html GNU General Public License V3 * @package SWDB */ require_once(PATH::ACTION . "Action.php"); /** * 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. * * @category Action */ class Login_Action extends Action{ /** * Executes the action. */ function execute(){ if (!isset($_POST['uname'], $_POST['password'])){ $this->code = 401; $this->message = "Invalid username / password."; http_response_code(401); header("Location: " . URL::BASE . "login/?status=401"); die(); // So the erorr is not handled by the controller. return 401; } $uname = SQLite3::escapeString($_POST['uname']); if (strlen($uname) == 0){ $this->code = 401; $this->message = "Invalid username / password."; http_response_code(401); header("Location: " . URL::BASE . "login/?status=401"); die(); // So the erorr is not handled by the controller. return 401; } $password = SQLite3::escapeString($_POST['password']); if (strlen($password) == 0){ $this->code = 401; $this->message = "Invalid username / password."; http_response_code(401); header("Location: " . URL::BASE . "login/?status=401"); die(); // So the erorr is not handled by the controller. return 401; } $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){ $this->code = 401; $this->message = "Invalid username / password."; header("Location: " . URL::BASE . "login/?status=401"); die(); // So the erorr is not handled by the controller. return 401; } $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? $this->code = 204; $this->message = "No content."; header("Location: " . URL::BASE); die(); return 204; } }