summaryrefslogtreecommitdiff
path: root/app/frontend/facades/UserFacade.php
blob: 1604a705a644c5d2b8af646e69fc378321324690 (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
67
68
69
70
71
72
73
74
75
76
77
78
<?php

Prado::using('Application.facades.Facade');
Prado::using('Application.user.DbUser');
Prado::using('Application.model.User');
Prado::using('Application.dto.TimezoneDTO');

class UserFacade extends Facade {

    public function findByLogin(string $login) {
        return User::finder()->findByLogin($login);
    }

    public function checkForUsername(string $login) {
        return !User::finder()->count('login = ?', $login);
    }

    public function registerUser(string $login, string $password, bool $admin) {
        $transaction = $this->beginTransaction();
        try {
            $newUser = new User();
            $newUser->Login = $login;
            $newUser->Password = $this->generatePassword($password);
            $newUser->IsAdmin = $admin;
            $newUser->save();
            $this->raiseEvent('UserRegistered', $newUser);
            $transaction->commit();
            return $newUser;
        } catch (Exception $e) {
            $transaction->rollback();
            throw $e;
        }
    }

    public function changePassword(DbUser $user, string $pass) {
        if (!$user->IsGuest) {
            $user->DbRecord->Password = $this->generatePassword($pass);
            $user->DbRecord->save();
        }
    }

    public function verifyUserPassword(string $password, DbUser $user) {
        $dbPassword = $user->IsGuest ? '' : $user->DbRecord->Password;
        return $this->verifyPassword($password, $dbPassword);
    }

    public function generatePassword(string $password) {
        return password_hash($password, PASSWORD_DEFAULT);
    }

    public function verifyPassword(string $password, string $dbPassword) {
        return password_verify($password, $dbPassword);
    }

    public function setTimezonePreference(DbUser $user, string $timezone) {
        if ($user->IsGuest) {
            throw new TInvalidDataException(
                Prado::localize(
                    'Timezone preference change impossible for guest user'
                )
            );
        }
        $user->DbRecord->Timezone = $timezone;
        $user->DbRecord->save();
    }

    public function getTimezonePreference(DbUser $user) {
        if (!$user->IsGuest) {
            try {
                return new TimezoneDTO($user->DbRecord->Timezone);
            } catch(Exception $e) {}
        }
        return new TimezoneDTO(date_default_timezone_get());
    }

}

?>