summaryrefslogtreecommitdiff
path: root/app/php/facades/UserFacade.php
blob: 69d634a97d2d00bb2db1d5c099e638683b7fb4ad (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
<?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($login) {
        return User::finder()->findByLogin($login);
    }

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

    public function registerUser($login, $password, $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, $pass) {
        if (!$user->IsGuest) {
            $user->DbRecord->Password = $this->generatePassword($pass);
            $user->DbRecord->save();
        }
    }

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

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

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

    public function setTimezonePreference(DbUser $user, $timezone) {
        if ($user->IsGuest) {
            throw new TInvalidDataException(
                '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());
    }

}

?>