Passed
Push — 3.0 ( 8cdcee...90ba03 )
by Rubén
07:01
created

UserService::getUserEmailForAll()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * sysPass
4
 *
5
 * @author    nuxsmin
6
 * @link      https://syspass.org
7
 * @copyright 2012-2018, Rubén Domínguez nuxsmin@$syspass.org
8
 *
9
 * This file is part of sysPass.
10
 *
11
 * sysPass is free software: you can redistribute it and/or modify
12
 * it under the terms of the GNU General Public License as published by
13
 * the Free Software Foundation, either version 3 of the License, or
14
 * (at your option) any later version.
15
 *
16
 * sysPass is distributed in the hope that it will be useful,
17
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19
 * GNU General Public License for more details.
20
 *
21
 * You should have received a copy of the GNU General Public License
22
 *  along with sysPass.  If not, see <http://www.gnu.org/licenses/>.
23
 */
24
25
namespace SP\Services\User;
26
27
use SP\Core\Crypt\Hash;
28
use SP\Core\Exceptions\ConstraintException;
29
use SP\Core\Exceptions\QueryException;
30
use SP\Core\Exceptions\SPException;
31
use SP\DataModel\ItemSearchData;
32
use SP\DataModel\UserData;
33
use SP\DataModel\UserPreferencesData;
34
use SP\Repositories\DuplicatedItemException;
35
use SP\Repositories\NoSuchItemException;
36
use SP\Repositories\User\UserRepository;
37
use SP\Services\Service;
38
use SP\Services\ServiceException;
39
use SP\Services\ServiceItemTrait;
40
use SP\Storage\Database\QueryResult;
41
use SP\Util\Util;
42
43
/**
44
 * Class UserService
45
 *
46
 * @package SP\Services\User
47
 */
48
final class UserService extends Service
49
{
50
    use ServiceItemTrait;
51
52
    /**
53
     * @var UserRepository
54
     */
55
    protected $userRepository;
56
    /**
57
     * @var UserPassService
58
     */
59
    protected $userPassService;
60
61
    /**
62
     * @param UserData $userData
63
     *
64
     * @return UserLoginResponse
65
     */
66
    public static function mapUserLoginResponse(UserData $userData)
67
    {
68
        return (new UserLoginResponse())->setId($userData->getId())
69
            ->setName($userData->getName())
70
            ->setLogin($userData->getLogin())
71
            ->setSsoLogin($userData->getSsoLogin())
72
            ->setEmail($userData->getEmail())
73
            ->setPass($userData->getPass())
74
            ->setHashSalt($userData->getHashSalt())
75
            ->setMPass($userData->getMPass())
76
            ->setMKey($userData->getMKey())
77
            ->setLastUpdateMPass($userData->getLastUpdateMPass())
78
            ->setUserGroupId($userData->getUserGroupId())
79
            ->setUserGroupName($userData->getUserGroupName())
80
            ->setUserProfileId($userData->getUserProfileId())
81
            ->setPreferences(self::getUserPreferences($userData->getPreferences()))
82
            ->setIsLdap($userData->isLdap())
83
            ->setIsAdminAcc($userData->isAdminAcc())
84
            ->setIsAdminApp($userData->isAdminApp())
85
            ->setIsMigrate($userData->isMigrate())
86
            ->setIsChangedPass($userData->isChangedPass())
87
            ->setIsChangePass($userData->isChangePass())
88
            ->setIsDisabled($userData->isDisabled())
89
            ->setLastUpdate((int)strtotime($userData->getLastUpdate()));
90
    }
91
92
    /**
93
     * Returns user's preferences object
94
     *
95
     * @param string $preferences
96
     *
97
     * @return UserPreferencesData
98
     */
99
    public static function getUserPreferences($preferences)
100
    {
101
        if (!empty($preferences)) {
102
            return Util::unserialize(UserPreferencesData::class, $preferences, 'SP\UserPreferences');
0 ignored issues
show
Bug Best Practice introduced by
The expression return SP\Util\Util::uns..., 'SP\UserPreferences') also could return the type string which is incompatible with the documented return type SP\DataModel\UserPreferencesData.
Loading history...
103
        }
104
105
        return new UserPreferencesData();
106
    }
107
108
    /**
109
     * Actualiza el último inicio de sesión del usuario en la BBDD.
110
     *
111
     * @param $id int El id del usuario
112
     *
113
     * @return int
114
     * @throws ConstraintException
115
     * @throws NoSuchItemException
116
     * @throws QueryException
117
     */
118
    public function updateLastLoginById($id)
119
    {
120
        $result = $this->userRepository->updateLastLoginById($id);
121
122
        if ($this->userRepository->updateLastLoginById($id) === 0) {
123
            throw new NoSuchItemException(__u('User does not exist'));
124
        }
125
126
        return $result;
127
    }
128
129
    /**
130
     * @param $login
131
     *
132
     * @return bool
133
     * @throws ConstraintException
134
     * @throws QueryException
135
     */
136
    public function checkExistsByLogin($login)
137
    {
138
        return $this->userRepository->checkExistsByLogin($login);
139
    }
140
141
    /**
142
     * Returns the item for given id
143
     *
144
     * @param int $id
145
     *
146
     * @return UserData
147
     * @throws SPException
148
     */
149
    public function getById($id)
150
    {
151
        $result = $this->userRepository->getById($id);
152
153
        if ($result->getNumRows() === 0) {
154
            throw new NoSuchItemException(__u('User does not exist'));
155
        }
156
157
        return $result->getData();
158
    }
159
160
    /**
161
     * Returns the item for given id
162
     *
163
     * @param $login
164
     *
165
     * @return UserData
166
     * @throws SPException
167
     */
168
    public function getByLogin($login)
169
    {
170
        $result = $this->userRepository->getByLogin($login);
171
172
        if ($result->getNumRows() === 0) {
173
            throw new NoSuchItemException(__u('User does not exist'));
174
        }
175
176
        return $result->getData();
177
    }
178
179
    /**
180
     * Deletes an item
181
     *
182
     * @param $id
183
     *
184
     * @return UserService
185
     * @throws ConstraintException
186
     * @throws QueryException
187
     * @throws NoSuchItemException
188
     */
189
    public function delete($id)
190
    {
191
        if ($this->userRepository->delete($id) === 0) {
192
            throw new NoSuchItemException(__u('User not found'), NoSuchItemException::INFO);
193
        }
194
195
        return $this;
196
    }
197
198
    /**
199
     * @param array $ids
200
     *
201
     * @return int
202
     * @throws ServiceException
203
     * @throws ConstraintException
204
     * @throws QueryException
205
     */
206
    public function deleteByIdBatch(array $ids)
207
    {
208
        if (($count = $this->userRepository->deleteByIdBatch($ids)) !== count($ids)) {
209
            throw new ServiceException(__u('Error while deleting the users'), ServiceException::WARNING);
210
        }
211
212
        return $count;
213
    }
214
215
    /**
216
     * Creates an item
217
     *
218
     * @param UserLoginRequest $userLoginRequest
219
     *
220
     * @return int
221
     * @throws SPException
222
     */
223
    public function createOnLogin(UserLoginRequest $userLoginRequest)
224
    {
225
        $userData = new UserData();
226
        $userData->setLogin($userLoginRequest->getLogin());
227
        $userData->setName($userLoginRequest->getName());
228
        $userData->setEmail($userLoginRequest->getEmail());
229
        $userData->setIsLdap($userLoginRequest->getisLdap());
0 ignored issues
show
Bug introduced by
$userLoginRequest->getisLdap() of type integer is incompatible with the type boolean expected by parameter $isLdap of SP\DataModel\UserData::setIsLdap(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

229
        $userData->setIsLdap(/** @scrutinizer ignore-type */ $userLoginRequest->getisLdap());
Loading history...
230
        $userData->setPass($userLoginRequest->getPassword());
231
232
        $configData = $this->config->getConfigData();
233
234
        if ($userLoginRequest->getisLdap() === 1) {
235
            $userData->setUserGroupId($configData->getLdapDefaultGroup());
236
            $userData->setUserProfileId($configData->getLdapDefaultProfile());
237
        } else {
238
            $userData->setUserGroupId($configData->getSsoDefaultGroup());
239
            $userData->setUserProfileId($configData->getSsoDefaultProfile());
240
        }
241
242
        return $this->create($userData);
243
    }
244
245
    /**
246
     * Creates an item
247
     *
248
     * @param UserData $itemData
249
     *
250
     * @return int
251
     * @throws SPException
252
     */
253
    public function create(UserData $itemData)
254
    {
255
        $itemData->setPass(Hash::hashKey($itemData->getPass()));
256
257
        return $this->userRepository->create($itemData);
258
    }
259
260
    /**
261
     * Creates an item
262
     *
263
     * @param UserData $itemData
264
     * @param string   $userPass
265
     * @param string   $masterPass
266
     *
267
     * @return int
268
     * @throws SPException
269
     * @throws \Defuse\Crypto\Exception\CryptoException
270
     */
271
    public function createWithMasterPass(UserData $itemData, $userPass, $masterPass)
272
    {
273
        $response = $this->userPassService->createMasterPass($masterPass, $itemData->getLogin(), $userPass);
274
275
        $itemData->setMPass($response->getCryptMasterPass());
276
        $itemData->setMKey($response->getCryptSecuredKey());
277
        $itemData->setLastUpdateMPass(time());
278
        $itemData->setPass($userPass);
279
280
        return $this->create($itemData);
281
    }
282
283
    /**
284
     * Searches for items by a given filter
285
     *
286
     * @param ItemSearchData $SearchData
287
     *
288
     * @return QueryResult
289
     * @throws ConstraintException
290
     * @throws QueryException
291
     */
292
    public function search(ItemSearchData $SearchData)
293
    {
294
        return $this->userRepository->search($SearchData);
295
    }
296
297
    /**
298
     * Updates an item
299
     *
300
     * @param UserData $itemData
301
     *
302
     * @throws ConstraintException
303
     * @throws QueryException
304
     * @throws DuplicatedItemException
305
     * @throws ServiceException
306
     */
307
    public function update($itemData)
308
    {
309
        if ($this->userRepository->update($itemData) === 0) {
310
            throw new ServiceException(__u('Error while updating the user'));
311
        }
312
    }
313
314
    /**
315
     * Updates an user's pass
316
     *
317
     * @param int    $userId
318
     * @param string $pass
319
     *
320
     * @throws ConstraintException
321
     * @throws QueryException
322
     * @throws ServiceException
323
     */
324
    public function updatePass($userId, $pass)
325
    {
326
        $passRequest = new UpdatePassRequest(Hash::hashKey($pass));
327
        $passRequest->setIsChangePass(0);
328
        $passRequest->setIsChangedPass(1);
329
330
        if ($this->userRepository->updatePassById($userId, $passRequest) === 0) {
331
            throw new ServiceException(__u('Error while updating the password'));
332
        }
333
    }
334
335
    /**
336
     * @param                     $userId
337
     * @param UserPreferencesData $userPreferencesData
338
     *
339
     * @return int
340
     * @throws ConstraintException
341
     * @throws QueryException
342
     */
343
    public function updatePreferencesById($userId, UserPreferencesData $userPreferencesData)
344
    {
345
        return $this->userRepository->updatePreferencesById($userId, $userPreferencesData);
346
    }
347
348
    /**
349
     * @param UserLoginRequest $userLoginRequest
350
     *
351
     * @return int
352
     * @throws ConstraintException
353
     * @throws QueryException
354
     */
355
    public function updateOnLogin(UserLoginRequest $userLoginRequest)
356
    {
357
        $userData = new UserData();
358
        $userData->setLogin($userLoginRequest->getLogin());
359
        $userData->setName($userLoginRequest->getName());
360
        $userData->setEmail($userLoginRequest->getEmail());
361
        $userData->setIsLdap($userLoginRequest->getisLdap());
0 ignored issues
show
Bug introduced by
$userLoginRequest->getisLdap() of type integer is incompatible with the type boolean expected by parameter $isLdap of SP\DataModel\UserData::setIsLdap(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

361
        $userData->setIsLdap(/** @scrutinizer ignore-type */ $userLoginRequest->getisLdap());
Loading history...
362
        $userData->setPass(Hash::hashKey($userLoginRequest->getPassword()));
363
364
        return $this->userRepository->updateOnLogin($userData);
365
    }
366
367
    /**
368
     * Get all items from the service's repository
369
     *
370
     * @return UserData[]
371
     * @throws ConstraintException
372
     * @throws QueryException
373
     */
374
    public function getAllBasic()
375
    {
376
        return $this->userRepository->getBasicInfo()->getDataAsArray();
377
    }
378
379
    /**
380
     * Obtener el email de los usuarios de un grupo
381
     *
382
     * @param $groupId
383
     *
384
     * @return array
385
     * @throws ConstraintException
386
     * @throws QueryException
387
     */
388
    public function getUserEmailForGroup($groupId)
389
    {
390
        return $this->userRepository->getUserEmailForGroup($groupId)->getDataAsArray();
391
    }
392
393
    /**
394
     * Obtener el email de los usuarios de un grupo
395
     *
396
     * @return array
397
     * @throws ConstraintException
398
     * @throws QueryException
399
     *
400
     * @TODO create unit test
401
     */
402
    public function getUserEmailForAll()
403
    {
404
        return $this->userRepository->getUserEmail()->getDataAsArray();
405
    }
406
407
    /**
408
     * Returns the usage of the given user's id
409
     *
410
     * @param int $id
411
     *
412
     * @return array
413
     * @throws ConstraintException
414
     * @throws QueryException
415
     */
416
    public function getUsageForUser($id)
417
    {
418
        return $this->userRepository->getUsageForUser($id)->getDataAsArray();
419
    }
420
421
    /**
422
     * @throws \Psr\Container\ContainerExceptionInterface
423
     * @throws \Psr\Container\NotFoundExceptionInterface
424
     */
425
    protected function initialize()
426
    {
427
        $this->userRepository = $this->dic->get(UserRepository::class);
428
        $this->userPassService = $this->dic->get(UserPassService::class);
429
    }
430
}