Debian Codegraph @

classes/Users/DbUser.php

raw symbols SCIP
1 <?php
2
3 /**
4 * dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
5 * Copyright (C) 2023-2024 Aleksey Andreev (liuch)
6 *
7 * Available at:
8 * https://github.com/liuch/dmarc-srg
9 *
10 * This program is free software: you can redistribute it and/or modify it
11 * under the terms of the GNU General Public License as published by the Free
12 * Software Foundation, either version 3 of the License.
13 *
14 * This program is distributed in the hope that it will be useful, but WITHOUT
15 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
17 * more details.
18 *
19 * You should have received a copy of the GNU General Public License along with
20 * this program. If not, see <http://www.gnu.org/licenses/>.
21 *
22 * =========================
23 *
24 * This file contains the class DbUser
25 *
26 * @category API
27 * @package DmarcSrg
28 * @author Aleksey Andreev (liuch)
29 * @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
30 */
31
32 namespace Liuch\DmarcSrg\Users;
33
34 use Liuch\DmarcSrg\Core;
35 use Liuch\DmarcSrg\Common;
36 use Liuch\DmarcSrg\Exception\SoftException;
37 use Liuch\DmarcSrg\Exception\LogicException;
38 use Liuch\DmarcSrg\Exception\DatabaseNotFoundException;
39
40 /**
41 * It's a class for accessing to stored user data
42 *
43 * This class is designed for storing and manipulating user data.
44 * All queries to the database are made in lazy mode.
45 */
46 class DbUser extends User
47 {
48 private $db = null;
49 private $ex_f = null;
50 private $data = [
51 'id' => null,
52 'name' => null,
53 'enabled' => null,
54 'password' => null, // If the password exists (boolean)
55 'level' => null,
56 'email' => null,
57 'key' => null,
58 'session' => null,
59 'domains' => null,
60 'created_time' => null,
61 'updated_time' => null
62 ];
63
64 /**
65 * Constructor
66 *
67 * Some examples of use:
68 * (new DbUser('user1'))->verifyPassword($passw) - will verify password $passw for user with name 'user1'
69 * (new DbUser([ 'name' => 'user2', 'level' => 10, 'enabled' => true ]))->save() - will add this user to
70 * the database if it doesn't exist or update it otherwise.
71 *
72 * @param int|string|array $data Some user data to identify it
73 * string value is treated as a name
74 * array value is threated as user data with fields
75 * @param \Liuch\DmarcSrg\Database\DatabaseController $db The database controller
76 *
77 * @return void
78 */
79 public function __construct($data, $db = null)
80 {
81 $this->db = $db ?? Core::instance()->database();
82 switch (gettype($data)) {
83 case 'string':
84 $this->data['name'] = strtolower(trim($data));
85 $this->checkName();
86 return;
87 case 'integer':
88 if ($data <= 0) {
89 break;
90 }
91 $this->data['id'] = $data;
92 return;
93 case 'array':
94 if (isset($data['id'])) {
95 if (gettype($data['id']) !== 'integer' || $data['id'] <= 0) {
96 break;
97 }
98 $this->data['id'] = $data['id'];
99 }
100 if (isset($data['name'])) {
101 if (gettype($data['name']) !== 'string') {
102 break;
103 }
104 $this->data['name'] = strtolower(trim($data['name']));
105 $this->checkName();
106 }
107 if (isset($data['enabled'])) {
108 if (gettype($data['enabled']) !== 'boolean') {
109 break;
110 }
111 $this->data['enabled'] = $data['enabled'];
112 }
113 if (isset($data['level'])) {
114 if (gettype($data['level']) !== 'integer') {
115 break;
116 }
117 $this->data['level'] = $data['level'];
118 }
119 if (isset($data['email'])) {
120 if (gettype($data['email']) !== 'string') {
121 break;
122 }
123 $this->data['email'] = $data['email'];
124 }
125 if (isset($data['key'])) {
126 if (gettype($data['key']) !== 'string') {
127 break;
128 }
129 $this->data['key'] = $data['key'];
130 }
131 if (isset($data['created_time'])) {
132 if (gettype($data['created_time']) !== 'object') {
133 break;
134 }
135 $this->data['created_time'] = $data['created_time'];
136 }
137 if (isset($data['updated_time'])) {
138 if (gettype($data['updated_time']) !== 'object') {
139 break;
140 }
141 $this->data['updated_time'] = $data['updated_time'];
142 }
143 if (isset($data['domains'])) {
144 if (!is_int($data['domains'])) {
145 break;
146 }
147 $this->data['domains'] = $data['domains'];
148 }
149 if (!is_null($this->data['id']) || !is_null($this->data['name'])) {
150 return;
151 }
152 }
153 throw new LogicException('Wrong user data');
154 }
155
156 /**
157 * Returns true if the user exists in the database or false otherwise
158 *
159 * @return bool Whether the user exists
160 */
161 public function exists(): bool
162 {
163 if (is_null($this->ex_f)) {
164 $this->ex_f = $this->db->getMapper('user')->exists($this->data);
165 }
166 return $this->ex_f;
167 }
168
169 /**
170 * Ensures the user is in the specified state and throws an exception if it is not.
171 *
172 * @param string $state Can be one of these values: 'exist', 'nonexist'
173 *
174 * @throws SoftException
175 *
176 * @return void
177 */
178 public function ensure(string $state): void
179 {
180 switch ($state) {
181 case 'exist':
182 if (!$this->exists()) {
183 throw new SoftException('The user does not exist');
184 }
185 break;
186 case 'nonexist':
187 if ($this->exists()) {
188 throw new SoftException('The user already exists');
189 }
190 break;
191 default:
192 throw new LogicException('Unknown user state');
193 }
194 }
195
196 /**
197 * Returns the user id
198 *
199 * @return int
200 */
201 public function id(): int
202 {
203 if (is_null($this->data['id'])) {
204 $this->fetchData();
205 }
206 return $this->data['id'];
207 }
208
209 /**
210 * Returns the user name
211 *
212 * @return string
213 */
214 public function name(): string
215 {
216 if (is_null($this->data['name'])) {
217 $this->fetchData();
218 }
219 return $this->data['name'];
220 }
221
222 /**
223 * Returns the user access level
224 *
225 * @return int
226 */
227 public function level(): int
228 {
229 if (is_null($this->data['level'])) {
230 $this->fetchData();
231 }
232 return $this->data['level'];
233 }
234
235 /**
236 * Checks if the user is enabled
237 *
238 * @return bool
239 */
240 public function isEnabled(): bool
241 {
242 if (is_null($this->data['enabled'])) {
243 $this->fetchData();
244 }
245 return $this->data['enabled'];
246 }
247
248 /**
249 * Sets the list of domains available to the user
250 *
251 * @param array $domains Array of domain names
252 *
253 * @return void
254 */
255 public function assignDomains(array &$domains): void
256 {
257 $this->db->getMapper('domain')->updateUserDomains($domains, $this->id());
258 }
259
260 /**
261 * Returns the sequence number of the session
262 *
263 * It changes when the user credentials or state are changed.
264 *
265 * @return int
266 */
267 public function session(): int
268 {
269 if (is_null($this->data['session'])) {
270 $this->fetchData();
271 }
272 return $this->data['session'];
273 }
274
275 /**
276 * Returns the user's data as an array
277 *
278 * @return array
279 */
280 public function toArray(): array
281 {
282 foreach ([ 'id', 'name', 'level', 'enabled' ] as $it) {
283 if (is_null($this->data[$it])) {
284 $this->fetchData();
285 break;
286 }
287 }
288 $res = $this->data;
289 unset($res['id']);
290 unset($res['session']);
291 return $res;
292 }
293
294 /**
295 * Saves the user's data to the database
296 *
297 * Updates the user's data in the database if the user exists or insert a new record otherwise.
298 * The user id is ignored in the insert mode.
299 *
300 * @return void
301 */
302 public function save(): void
303 {
304 $this->db->getMapper('user')->save($this->data);
305 $this->ex_f = true;
306 }
307
308 /**
309 * Deletes the user from the database
310 *
311 * @return void
312 */
313 public function delete(): void
314 {
315 if (is_null($this->data['id'])) {
316 $this->fetchData();
317 }
318 $this->db->getMapper('user')->delete($this->data);
319 $this->ex_f = false;
320 }
321
322 /**
323 * Verifies the passed password with the hash stored in the database
324 *
325 * @param string $password Password to validate
326 *
327 * @return bool
328 */
329 public function verifyPassword(string $password): bool
330 {
331 if (empty($password)) {
332 return false;
333 }
334 $hash = null;
335 try {
336 $hash = $this->db->getMapper('user')->getPasswordHash($this->data);
337 } catch (DatabaseNotFoundException $e) {
338 $this->ex_f = false;
339 return false;
340 }
341 return password_verify($password, $hash);
342 }
343
344 /**
345 * Store the passed password to the database as a hash with salt
346 *
347 * @param string $password Password to store
348 *
349 * @return void
350 */
351 public function setPassword(string $password): void
352 {
353 $hash = password_hash($password, PASSWORD_DEFAULT);
354 $this->db->getMapper('user')->savePasswordHash($this->data, $hash);
355 }
356
357 /**
358 * Returns a random string bound to the user
359 *
360 * @return string
361 */
362 public function verificationString(): string
363 {
364 if (is_null($this->data['key'])) {
365 $this->fetchData();
366 }
367 if (empty($this->data['key'])) {
368 $this->db->getMapper('user')->setUserKey($this->data, Common::randomString(32));
369 }
370 return $this->data['key'];
371 }
372
373 /**
374 * Checks if the username value is correct
375 *
376 * @return void
377 */
378 private function checkName(): void
379 {
380 if (empty($this->data['name'])) {
381 throw new SoftException('The user name must not be an empty string');
382 }
383 if ($this->data['name'] === 'admin') {
384 throw new SoftException('Incorrect user name');
385 }
386 }
387
388 /**
389 * Fetches the user data from the database by its name
390 *
391 * @return void
392 */
393 private function fetchData(): void
394 {
395 if ($this->ex_f === false) {
396 return;
397 }
398
399 try {
400 $this->db->getMapper('user')->fetch($this->data);
401 $this->ex_f = true;
402 } catch (DatabaseNotFoundException $e) {
403 $this->ex_f = false;
404 throw new SoftException('User not found');
405 }
406 }
407 }