summaryrefslogtreecommitdiff
path: root/app/frontend/facades/UserFacade.php
blob: 5e04319c102636abf4d3f388b1adb504d784a6ee (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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
<?php

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

class UserFacade extends Facade {

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

    public function findByEMail(string $email) {
        return User::finder()->findByEMail($email);
    }

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

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

    public function registerUser(
        string $login,
        string $password,
        string $email,
        bool $admin=FALSE) {
        $transaction = $this->beginTransaction();
        try {
            $newUser = new User();
            $newUser->Login = $login;
            $newUser->Password = $this->generatePassword($password);
            $newUser->EMail = $email;
            $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 requestActivation(User $user) {
        $user->IsActive = FALSE;
        $user->ActivationHash = md5(mt_rand());
        $user->save();
        $this->_sendActivationMail($user);
    }

    protected function _generateActivationLink($email, $hash) {
        $application = Prado::getApplication();
        return $application->Request->getBaseUrl()
            . $application->Service->constructUrl(
                'Activate',
                ['email' => base64_encode($email),
                 'hash' => $hash]
            );
    }

    protected function _sendActivationMail(User $user) {
        $mailModule = Prado::getApplication()->getModule('mail');
        $mailer = $mailModule->getMailer();
        $template = $mailModule->getTemplate('activation-link');
        $template->link = $this->_generateActivationLink(
            $user->EMail, $user->ActivationHash
        );
        $mailer->sendTemplate(
            $template,
            Prado::localize('rcal - account activation'),
            $user->EMail,
            $user->Login
        );
    }

    public function activateUser(string $email, string $hash) {
        $user = $this->findByEMail(
            base64_decode($email)
        );
        $activation = $user && !$user->IsActive
            && ($user->ActivationHash === $hash);
        if ($activation) {
            $user->IsActive = TRUE;
            $user->ActivationDate = (new DateTime('UTC'))->format('Y-m-d H:i:s');
            $user->ActivationHash = NULL;
            $user->save();
            return TRUE;
        }
        return FALSE;
    }

    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 && $user->DbRecord->Timezone) {
            try {
                return new TimezoneDTO($user->DbRecord->Timezone);
            } catch(Exception $e) {}
        }
        return new TimezoneDTO(date_default_timezone_get());
    }

    public function setLanguagePreference(DbUser $user, string $lang) {
        if ($user->IsGuest) {
            throw new TInvlaidDataException(
                Prado::localize(
                    'Language preference change impossible for guest user'
                )
            );
        }
        $user->DbRecord->Language = $lang;
        $user->DbRecord->save();
    }

    public function getLanguagePreference(DbUser $user) {
        if (!$user->IsGuest) {
            try {
                if ($user->DbRecord->Language) {
                    return new LanguageDTO($user->DbRecord->Language);
                }
            } catch(Exception $e) {}
        }
        return NULL;
    }

    public function setGroupedViewPreference(DbUser $user, bool $value) {
        if ($user->IsGuest) {
            throw new TInvlaidDataException(
                Prado::localize(
                    'Grouped view preference change impossible for guest user'
                )
            );
        }
        $user->DbRecord->GroupedView = $value;
        $user->DbRecord->save();
    }

    public function getGroupedViewPreference(DbUser $user) {
        if (!$user->IsGuest) {
            return TPropertyValue::ensureBoolean(
                $user->DbRecord->GroupedView
            );
        }
        return FALSE;
    }

    public function createUserAuthKey(DbUser $user) {
        if ($user->IsGuest) {
            return NULL;
        }
        $authKey = new UserAuthKey();
        $authKey->AuthKey = md5(mt_rand());
        $authKey->IPAddress = Prado::getApplication()->Request->UserHostAddress;
        $authKey->UserID = $user->DbRecord->ID;
        $authKey->save();
        $dto = new UserKeyDTO();
        $dto->loadRecord($authKey);
        return $dto;
    }

    public function compileCookieData(UserKeyDTO $key) {
        $data = base64_encode(serialize($key));
        return Prado::getApplication()->SecurityManager->hashData($data);
    }

    public function getUserFromCookieData(THttpCookie $cookie) {
        $application = Prado::getApplication();
        try {
            $data = $application->SecurityManager->validateData($cookie->getValue());
            if ($data) {
                $data = unserialize(base64_decode($data));
                if ($data instanceof UserKeyDTO) {
                    $dataRecord = UserAuthKey::finder()->findByAuthKey($data->Key);
                    if ($dataRecord
                        && $data->User === $dataRecord->User->Login
                        && $data->IPAddress === $application->Request->UserHostAddress) {
                        return $data;
                    }
                }
            }
            return NULL;
        } catch (Exception $e) {
            return NULL;
        }
    }

    public function clearUserAuthKey(DbUser $user) {
        if (!$user->IsGuest && $user->DbRecord && $user->AuthKey) {
            $keyRecord = UserAuthKey::finder()->findByAuthKey($user->AuthKey);
            if ($keyRecord && $keyRecord->UserID == $user->DbRecord->ID) {
                $keyRecord->delete();
            }
        }
    }

}

?>