diff options
Diffstat (limited to 'Digitigrade/Model/Session.php')
| -rw-r--r-- | Digitigrade/Model/Session.php | 43 |
1 files changed, 43 insertions, 0 deletions
diff --git a/Digitigrade/Model/Session.php b/Digitigrade/Model/Session.php new file mode 100644 index 0000000..31fb8bb --- /dev/null +++ b/Digitigrade/Model/Session.php @@ -0,0 +1,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() + ]); + } +}
\ No newline at end of file |
