Dragon-Knight/public/login.php

47 lines
1.3 KiB
PHP

<?php
// login.php :: Handles logins and cookies.
if (!file_exists('../.installed')) redirect('install.php');
require_once '../src/lib.php';
match ($_GET['do'] ?? 'login') {
'login' => login(),
'logout' => logout()
};
function login()
{
if (checkcookies() !== false) redirect('index.php');
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$u = trim($_POST['username'] ?? '');
$query = db()->query('SELECT id, username, password FROM users WHERE username = ? LIMIT 1;', [$u]);
if ($query === false) die("Invalid username or password. Please go back and try again.");
$row = $query->fetchArray(SQLITE3_ASSOC);
if (!password_verify($_POST['password'] ?? '', $row['password'])) die("Invalid username or password. Please go back and try again.");
$expiretime = isset($_POST["rememberme"]) ? time() + 31536000 : 0;
$rememberme = isset($_POST["rememberme"]) ? 1 : 0;
$cookie = implode(' ', [$row['id'], $row['username'], $row['password'], $rememberme]);
set_cookie("dkgame", $cookie, $expiretime);
header("Location: index.php");
exit;
}
$page = gettemplate("login");
$title = "Log In";
display($page, $title, false, false, false, false);
}
function logout()
{
set_cookie("dkgame", "", -3600);
header("Location: login.php?do=login");
die();
}