summaryrefslogtreecommitdiff
path: root/localwebsite/classes/auth.php
blob: 2cdee72547d89cc8dd4ac457caddbf3ac9bb9b82 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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;
    }

}