PlainSQLiteBlog/lib/UserAuth.php

114 lines
3.6 KiB
PHP

<?php
class UserAuth
{
public static function getUser()
{
global $c;
try
{
$strToken = Cookie::get("token");
if ($strToken == null)
{
// Attempt to read token from X-Token header first:
$strToken = Request::getHeader("X-Token");
// Then try reading it directly from the POST:
if (Request::posts("token"))
$strToken = Request::getPosted("token");
}
if ($strToken !== null)
if (strlen($strToken) > 0)
{
$varSessions = $c->query(
"SELECT *
from sessions as s
join users as u on u.username = s.username
where
s.token = ?
and (
s.expires is null
or s.expires > current_timestamp
)",
$strToken);
if (count($varSessions) == 1)
return $varSessions[0];
}
}
catch (Exception $x) {}
return null;
}
public static function has($strColumnName)
{
global $c;
$varUser = UserAuth::getUser();
if ($varUser == null)
return false;
if (array_key_exists($strColumnName, $varUser))
if (intval($varUser[$strColumnName]) > 0)
return true;
return false;
}
public static function require($strColumnName)
{
if (!UserAuth::has($strColumnName))
{
PageRender::message("You do not have permission to do that, please sign into an account that does.", "warning");
Respond::redirect("/user/signin");
}
}
public static function visible($strVisibility)
{
global $c;
if (UserAuth::has("is_admin"))
return true;
$varUser = UserAuth::getUser();
$strUsername = "";
if ($varUser !== null)
if (array_key_exists("username", $varUser))
$strUsername = $varUser["username"] ?? "";
// Support arrays with username and visibility keys:
if (is_array($strVisibility))
{
if (array_key_exists("username", $strVisibility))
if ($strVisibility["username"] == $strUsername)
return true;
if (!array_key_exists("visibility", $strVisibility))
return false;
$strVisibility = $strVisibility["visibility"];
}
if ($strVisibility == null)
$strVisibility = "";
// Handle hiding the post from non-admins:
if (preg_match("/^(admin|hid(e|den)|invisible|no(ne|body)|private)$/i", $strVisibility))
return false;
if (strlen($strUsername) > 0)
if (preg_match("/{$strUsername}/i", $strVisibility))
return true;
// Handle showing the post to everyone:
if (preg_match("/^(|(every|any)(body|one)|all|public)$/i", $strVisibility))
return true;
return false;
}
}
?>