aboutsummaryrefslogtreecommitdiffhomepage
path: root/Digitigrade/Model/UserAccount.php
blob: 3d0e2a4d07bad934c5e937173024b68976ff7280 (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
<?php
namespace Digitigrade\Model;

use Digitigrade\Model;

class UserAccount extends Model {
    public ?int $id;
    public string $email;
    public string $passwordHash;
    public ?Actor $actor;
    public bool $banned = false;

    public static function create(string $email, #[\SensitiveParameter] string $password): self {
        $user = new self();
        $user->email = $email;
        $user->passwordHash = defaults_password_hash($password);
        $user->actor = null;
        $user->save();
        return $user;
    }

    public function createLinkedActor(string $handle) {
        $this->actor = Actor::create($handle);
        $this->save();
    }

    protected function getUpdateWhereClause(\PDO $db): ?string {
        if (isset($this->id) && self::find($this->{'id'}) != null) {
            return 'id = ' . $this->{'id'};
        }
        if (self::findByEmail($this->email) != null) {
            return 'email = ' . $db->quote($this->email);
        }
        return null;
    }

    public static function findByEmail(string $email): ?self {
        return self::findWhere('email = ?', [$email]);
    }

    public static function findByCurrentSession(): ?self {
        if (!isset($_COOKIE['digitigrade-session'])) {
            return null;
        }
        $token = $_COOKIE['digitigrade-session'];
        return Session::findByToken($token)?->userAccount;
    }

    public function verifyPassword(#[\SensitiveParameter] $attemptedPassword): bool {
        return password_verify($attemptedPassword, $this->passwordHash);
    }
}