diff options
author | Evgeny Zinoviev <me@ch1p.io> | 2022-05-26 21:18:29 +0300 |
---|---|---|
committer | Evgeny Zinoviev <me@ch1p.io> | 2022-05-27 01:04:47 +0300 |
commit | cf0b9f036b3e3eb218610e7eeececda1320d9f50 (patch) | |
tree | 39e6d1853aecb3fb77036a941a4c6df12a0ce793 /localwebsite/classes/auth.php | |
parent | c3ed2483ea508141431be74f29f7c209271897cd (diff) |
auth
Diffstat (limited to 'localwebsite/classes/auth.php')
-rw-r--r-- | localwebsite/classes/auth.php | 66 |
1 files changed, 66 insertions, 0 deletions
diff --git a/localwebsite/classes/auth.php b/localwebsite/classes/auth.php new file mode 100644 index 0000000..2cdee72 --- /dev/null +++ b/localwebsite/classes/auth.php @@ -0,0 +1,66 @@ +<?php + +class auth { + + public static ?User $authorizedUser = null; + + const SESSION_TIMEOUT = 86400 * 365; + const COOKIE_NAME = 'auth'; + + public static function getToken(): ?string { + return $_COOKIE[self::COOKIE_NAME] ?? null; + } + + public static function setToken(string $token) { + setcookie(self::COOKIE_NAME, + $token, + time() + self::SESSION_TIMEOUT, + '/', + config::get('auth_cookie_host'), + true); + } + + public static function resetToken() { + if (!headers_sent()) + setcookie(self::COOKIE_NAME, null, -1, '/', config::get('auth_cookie_host')); + } + + public static function id(bool $do_check = true): int { + if ($do_check) + self::check(); + + if (!self::$authorizedUser) + return 0; + + return self::$authorizedUser->id; + } + + public static function check(?string $pwhash = null): bool { + if (self::$authorizedUser !== null) + return true; + + // get auth token + if (!$pwhash) + $pwhash = self::getToken(); + + if (!is_string($pwhash)) + return false; + + // find session by given token + $user = users::getUserByPwhash($pwhash); + if (is_null($user)) { + self::resetToken(); + return false; + } + + self::$authorizedUser = $user; + + return true; + } + + public static function logout() { + self::resetToken(); + self::$authorizedUser = null; + } + +}
\ No newline at end of file |