aboutsummaryrefslogtreecommitdiffhomepage
path: root/Digitigrade/Model/Session.php
blob: 31fb8bb260398b3a050e0d9556eba5752294e74c (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
<?php
namespace Digitigrade\Model;

use Digitigrade\GlobalConfig;
use Digitigrade\Model;

class Session extends Model {
    public string $token;
    public UserAccount $userAccount;

    public static function create(UserAccount $user): self {
        $session = new self();
        $session->userAccount = $user;
        $session->token = random_printable_bytes();
        $session->save();
        return $session;
    }

    protected function getUpdateWhereClause(\PDO $db): ?string {
        if (self::findByToken($this->token) != null) {
            return 'token = ' . $db->quote($this->token);
        }
        return null;
    }

    public static function findByToken(#[\SensitiveParameter] string $token): ?self {
        return self::findWhere('token = ?', [$token]);
    }

    public static function findAllByAccount(UserAccount $userAccount): array {
        return self::findAllWhere('user_account = ?', [$userAccount->id]);
    }

    public function setCookie(bool $rememberSession) {
        setcookie('digitigrade-session', $this->token, [
            'expires' => $rememberSession ? (new \DateTimeImmutable('1 year'))->getTimestamp() : null,
            'httponly' => true,
            'samesite' => 'Lax',
            'path' => '/',
            'secure' => GlobalConfig::getInstance()->isHttps()
        ]);
    }
}