Welcome to mirror list, hosted at ThFree Co, Russian Federation.

UserBackend.php « Backend « lib - github.com/nextcloud/user_sql.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: fca2959d86d3a9b61458486ee00297e2ccb854c0 (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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
<?php
/**
 * Nextcloud - user_sql
 *
 * @copyright 2020 Marcin Łojewski <dev@mlojewski.me>
 * @author    Marcin Łojewski <dev@mlojewski.me>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

namespace OCA\UserSQL\Backend;

use OC\User\Backend;
use OCA\UserSQL\Action\EmailSync;
use OCA\UserSQL\Action\IUserAction;
use OCA\UserSQL\Action\NameSync;
use OCA\UserSQL\Action\QuotaSync;
use OCA\UserSQL\Cache;
use OCA\UserSQL\Constant\App;
use OCA\UserSQL\Constant\DB;
use OCA\UserSQL\Constant\Opt;
use OCA\UserSQL\Crypto\IPasswordAlgorithm;
use OCA\UserSQL\Model\User;
use OCA\UserSQL\Properties;
use OCA\UserSQL\Repository\UserRepository;
use OCP\IConfig;
use OCP\IL10N;
use OCP\ILogger;
use OCP\User\Backend\ABackend;
use OCP\User\Backend\ICheckPasswordBackend;
use OCP\User\Backend\ICountUsersBackend;
use OCP\User\Backend\IGetDisplayNameBackend;
use OCP\User\Backend\IGetHomeBackend;
use OCP\User\Backend\IPasswordConfirmationBackend;
use OCP\User\Backend\IProvideAvatarBackend;
use OCP\User\Backend\ISetDisplayNameBackend;
use OCP\User\Backend\ISetPasswordBackend;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\GenericEvent;

/**
 * The SQL user backend manager.
 *
 * @author Marcin Łojewski <dev@mlojewski.me>
 */
final class UserBackend extends ABackend implements
    ICheckPasswordBackend,
    ICountUsersBackend,
    IGetDisplayNameBackend,
    IGetHomeBackend,
    IPasswordConfirmationBackend,
    IProvideAvatarBackend,
    ISetDisplayNameBackend,
    ISetPasswordBackend
{
    /**
     * @var string The application name.
     */
    private $appName;
    /**
     * @var ILogger The logger instance.
     */
    private $logger;
    /**
     * @var Cache The cache instance.
     */
    private $cache;
    /**
     * @var UserRepository The user repository.
     */
    private $userRepository;
    /**
     * @var Properties The properties array.
     */
    private $properties;
    /**
     * @var IL10N The localization service.
     */
    private $localization;
    /**
     * @var IConfig The config instance.
     */
    private $config;
    /**
     * @var EventDispatcher The event dispatcher.
     */
    private $eventDispatcher;
    /**
     * @var IUserAction[] The actions to execute.
     */
    private $actions;

    /**
     * The default constructor.
     *
     * @param string          $AppName         The application name.
     * @param Cache           $cache           The cache instance.
     * @param ILogger         $logger          The logger instance.
     * @param Properties      $properties      The properties array.
     * @param UserRepository  $userRepository  The user repository.
     * @param IL10N           $localization    The localization service.
     * @param IConfig         $config          The config instance.
     * @param EventDispatcher $eventDispatcher The event dispatcher.
     */
    public function __construct(
        $AppName, Cache $cache, ILogger $logger, Properties $properties,
        UserRepository $userRepository, IL10N $localization, IConfig $config,
        EventDispatcher $eventDispatcher
    ) {
        $this->appName = $AppName;
        $this->cache = $cache;
        $this->logger = $logger;
        $this->properties = $properties;
        $this->userRepository = $userRepository;
        $this->localization = $localization;
        $this->config = $config;
        $this->eventDispatcher = $eventDispatcher;
        $this->actions = [];

        $this->initActions();
    }

    /**
     * Initiate the actions array.
     */
    private function initActions()
    {
        if (!empty($this->properties[Opt::EMAIL_SYNC])
            && !empty($this->properties[DB::USER_EMAIL_COLUMN])
        ) {
            $this->actions[] = new EmailSync(
                $this->appName, $this->logger, $this->properties, $this->config,
                $this->userRepository
            );
        }
        if (!empty($this->properties[Opt::QUOTA_SYNC])
            && !empty($this->properties[DB::USER_QUOTA_COLUMN])
        ) {
            $this->actions[] = new QuotaSync(
                $this->appName, $this->logger, $this->properties, $this->config,
                $this->userRepository
            );
        }
        if (!empty($this->properties[Opt::NAME_SYNC])
            && !empty($this->properties[DB::USER_NAME_COLUMN])
        ) {
            $this->actions[] = new NameSync(
                $this->appName, $this->logger, $this->properties, $this->config,
                $this->userRepository
            );
        }
    }

    /**
     * @inheritdoc
     */
    public function hasUserListings()
    {
        return true;
    }

    /**
     * Count users in the database.
     *
     * @return int The number of users.
     */
    public function countUsers()
    {
        $this->logger->debug(
            "Entering countUsers()", ["app" => $this->appName]
        );

        $cacheKey = self::class . "users#";
        $count = $this->cache->get($cacheKey);

        if (!is_null($count)) {
            $this->logger->debug(
                "Returning from cache countUsers(): $count",
                ["app" => $this->appName]
            );
            return $count;
        }

        $count = $this->userRepository->countAll("%");

        if ($count === false) {
            return 0;
        }

        $this->cache->set($cacheKey, $count);
        $this->logger->debug(
            "Returning countUsers(): $count", ["app" => $this->appName]
        );

        return $count;
    }

    /**
     * @inheritdoc
     */
    public function userExists($uid)
    {
        $this->logger->debug(
            "Entering userExists($uid)", ["app" => $this->appName]
        );

        $user = $this->getUser($uid);

        if ($user === false) {
            return false;
        }

        $exists = !is_null($user);
        $this->logger->debug(
            "Returning userExists($uid): " . ($exists ? "true" : "false"),
            ["app" => $this->appName]
        );

        return $exists;
    }

    /**
     * Get a user entity object. If it's found value from cache is used.
     *
     * @param string $uid The user ID.
     *
     * @return User The user entity, NULL if it does not exists or
     *              FALSE on failure.
     */
    private function getUser($uid)
    {
        $cacheKey = self::class . "user_" . $uid;
        $cachedUser = $this->cache->get($cacheKey);

        if (!is_null($cachedUser)) {
            $user = new User();
            foreach ($cachedUser as $key => $value) {
                $user->{$key} = $value;
            }

            $this->logger->debug(
                "Found user in cache: " . $user->uid, ["app" => $this->appName]
            );

            return $user;
        }

        $user = $this->userRepository->findByUid($uid);

        if ($user instanceof User) {
            $this->cache->set($cacheKey, $user);

            foreach ($this->actions as $action) {
                $action->doAction($user);
            }
        }

        return $user;
    }

    /**
     * @inheritdoc
     */
    public function getDisplayName($uid): string
    {
        $this->logger->debug(
            "Entering getDisplayName($uid)", ["app" => $this->appName]
        );

        $user = $this->getUser($uid);

        if (!($user instanceof User)) {
            return false;
        }

        if (is_null($user->name)) {
            return false;
        }

        $name = $user->name;
        $this->logger->debug(
            "Returning getDisplayName($uid): $name",
            ["app" => $this->appName]
        );

        return $name;
    }

    /**
     * Check if the user's password is correct then return its ID or
     * FALSE on failure.
     *
     * @param string $username The username.
     * @param string $password The password.
     *
     * @return string|bool The user ID on success, false otherwise.
     */
    public function checkPassword(string $username, string $password)
    {
        $this->logger->debug(
            "Entering checkPassword($username, *)", ["app" => $this->appName]
        );

        $passwordAlgorithm = $this->getPasswordAlgorithm();
        if ($passwordAlgorithm === null) {
            return false;
        }

        $caseSensitive = empty($this->properties[Opt::CASE_INSENSITIVE_USERNAME]);
        $emailLogin = !empty($this->properties[Opt::EMAIL_LOGIN]);
        if ($emailLogin) {
            $user = $this->userRepository->findByUsernameOrEmail($username, $caseSensitive);
        } else {
            $user = $this->userRepository->findByUsername($username, $caseSensitive);
        }

        if (!($user instanceof User)) {
            return false;
        }

        $uid = $user->uid;
        $password = $this->addSalt($user, $password);

        $isCorrect = $passwordAlgorithm->checkPassword(
            $password, $user->password, $user->salt
        );

        if ($user->active == false) {
            $this->logger->info(
                "User account is inactive for user: $uid",
                ["app" => $this->appName]
            );
            return false;
        }

        if ($isCorrect !== true) {
            $this->logger->info(
                "Invalid password attempt for user: $uid",
                ["app" => $this->appName]
            );
            return false;
        }

        $this->logger->info(
            "Successful password attempt for user: $uid",
            ["app" => $this->appName]
        );

        return $uid;
    }

    /**
     * Get a password algorithm implementation instance.
     *
     * @return IPasswordAlgorithm The password algorithm instance or FALSE
     * on failure.
     */
    private function getPasswordAlgorithm()
    {
        $cryptoType = $this->properties[Opt::CRYPTO_CLASS];
        $cryptoParam0 = $this->properties[Opt::CRYPTO_PARAM_0];
        $cryptoParam1 = $this->properties[Opt::CRYPTO_PARAM_1];
        $cryptoParam2 = $this->properties[Opt::CRYPTO_PARAM_2];
        $passwordAlgorithm = new $cryptoType(
            $this->localization, $cryptoParam0, $cryptoParam1, $cryptoParam2
        );

        if ($passwordAlgorithm === null) {
            $this->logger->error(
                "Cannot get password algorithm instance: " . $cryptoType,
                ["app" => $this->appName]
            );
        }

        return $passwordAlgorithm;
    }

    /**
     * Append or prepend salt from external column if available.
     *
     * @param User   $user     The user instance.
     * @param string $password The password.
     *
     * @return string Salted password.
     */
    private function addSalt(User $user, string $password): string
    {
        if ($user->salt !== null) {
            if (!empty($this->properties[Opt::APPEND_SALT])) {
                return $password . $user->salt;
            } elseif (!empty($this->properties[Opt::PREPEND_SALT])) {
                return $user->salt . $password;
            }
        }

        return $password;
    }

    /**
     * @inheritdoc
     */
    public function getDisplayNames($search = "", $limit = null, $offset = null)
    {
        $this->logger->debug(
            "Entering getDisplayNames($search, $limit, $offset)",
            ["app" => $this->appName]
        );

        $users = $this->getUsers(
            $search, $limit, $offset, function ($user) {
            return $user;
        }
        );

        $names = [];
        foreach ($users as $user) {
            if (is_null($user->name)) {
                $names[$user->uid] = $user->uid;
            } else {
                $names[$user->uid] = $user->name;
            }
        }

        $this->logger->debug(
            "Returning getDisplayNames($search, $limit, $offset): count("
            . count($users) . ")", ["app" => $this->appName]
        );

        return $names;
    }

    /**
     * @inheritdoc
     */
    public function getUsers($search = "", $limit = null, $offset = null, $callback = null)
    {
        $this->logger->debug(
            "Entering getUsers($search, $limit, $offset)",
            ["app" => $this->appName]
        );

        $cacheKey = self::class . "users_" . $search . "_" . $limit . "_"
            . $offset;
        $users = $this->cache->get($cacheKey);

        if (!is_null($users)) {
            $this->logger->debug(
                "Returning from cache getUsers($search, $limit, $offset): count("
                . count($users) . ")", ["app" => $this->appName]
            );
            return $users;
        }

        $users = $this->userRepository->findAllBySearchTerm(
            "%" . $search . "%", $limit, $offset
        );

        if ($users === false) {
            return [];
        }

        foreach ($users as $user) {
            $this->cache->set("user_" . $user->uid, $user);
        }

        $callback = is_callable($callback)
            ? $callback
            : function ($user) {
                return $user->uid;
            };
        $users = array_map($callback, $users);

        $this->cache->set($cacheKey, $users);
        $this->logger->debug(
            "Returning getUsers($search, $limit, $offset): count("
            . count(
                $users
            ) . ")", ["app" => $this->appName]
        );

        return $users;
    }

    /**
     * Set a user password.
     *
     * @param string $uid      The user ID.
     * @param string $password The password to set.
     *
     * @return bool TRUE if the password has been set, FALSE otherwise.
     */
    public function setPassword(string $uid, string $password): bool
    {
        $this->logger->debug(
            "Entering setPassword($uid, *)", ["app" => "user_sql"]
        );

        if (empty($this->properties[Opt::PASSWORD_CHANGE])) {
            return false;
        }

        $passwordAlgorithm = $this->getPasswordAlgorithm();
        if ($passwordAlgorithm === false) {
            return false;
        }

        $event = new GenericEvent($password);
        $this->eventDispatcher->dispatch(
            'OCP\PasswordPolicy::validate', $event
        );

        $user = $this->userRepository->findByUid($uid);
        if (!($user instanceof User)) {
            return false;
        }

        $password = $this->addSalt($user, $password);

        $passwordHash = $passwordAlgorithm->getPasswordHash($password);
        if ($passwordHash === false) {
            return false;
        }

        $user->password = $passwordHash;
        $result = $this->userRepository->save($user, UserRepository::PASSWORD_FIELD);

        if ($result === true) {
            $this->logger->info(
                "Password has been set successfully for user: $uid",
                ["app" => $this->appName]
            );
            return true;
        }

        return false;
    }

    /**
     * @inheritdoc
     */
    public function getHome(string $uid)
    {
        $this->logger->debug(
            "Entering getHome($uid)", ["app" => $this->appName]
        );

        if (empty($this->properties[Opt::HOME_MODE])) {
            return false;
        }

        $home = false;
        switch ($this->properties[Opt::HOME_MODE]) {
        case App::HOME_STATIC:
            $home = $this->properties[Opt::HOME_LOCATION];
            $home = str_replace("%u", $uid, $home);
            break;
        case App::HOME_QUERY:
            $user = $this->getUser($uid);
            if (!($user instanceof User)) {
                return false;
            }
            $home = $user->home;
            break;
        }

        $this->logger->debug(
            "Returning getHome($uid): " . $home, ["app" => $this->appName]
        );

        return $home;
    }

    /**
     * Can user change its avatar.
     *
     * @param string $uid The user ID.
     *
     * @return bool TRUE if the user can change its avatar, FALSE otherwise.
     */
    public function canChangeAvatar(string $uid): bool
    {
        $this->logger->debug(
            "Entering canChangeAvatar($uid)", ["app" => $this->appName]
        );

        if (empty($this->properties[DB::USER_AVATAR_COLUMN])) {
            return !empty($this->properties[Opt::PROVIDE_AVATAR]);
        }

        $user = $this->userRepository->findByUid($uid);
        if (!($user instanceof User)) {
            return false;
        }

        $avatar = $user->avatar;
        $this->logger->debug(
            "Returning canChangeAvatar($uid): " . ($avatar ? "true"
                : "false"), ["app" => $this->appName]
        );

        return $avatar;
    }

    /**
     * Set a user display name.
     *
     * @param string $uid         The user ID.
     * @param string $displayName The display name to set.
     *
     * @return bool TRUE if the password has been set, FALSE otherwise.
     */
    public function setDisplayName(string $uid, string $displayName): bool
    {
        $this->logger->debug(
            "Entering setDisplayName($uid, $displayName)",
            ["app" => $this->appName]
        );

        if (empty($this->properties[Opt::NAME_CHANGE])) {
            return false;
        }

        $user = $this->userRepository->findByUid($uid);
        if (!($user instanceof User)) {
            return false;
        }

        $user->name = $displayName;
        $result = $this->userRepository->save($user, UserRepository::DISPLAY_NAME_FIELD);

        if ($result === true) {
            $this->logger->info(
                "Display name has been set successfully for user: $uid",
                ["app" => $this->appName]
            );
            return true;
        }

        return false;
    }

    /**
     * Check if this backend is correctly set and can be enabled.
     *
     * @return bool TRUE if all necessary options for this backend
     *              are configured, FALSE otherwise.
     */
    public function isConfigured()
    {
        return !empty($this->properties[DB::DATABASE])
            && !empty($this->properties[DB::DRIVER])
            && !empty($this->properties[DB::HOSTNAME])
            && !empty($this->properties[DB::USERNAME])
            && !empty($this->properties[DB::USER_TABLE])
            && !empty($this->properties[DB::USER_UID_COLUMN])
            && !empty($this->properties[DB::USER_PASSWORD_COLUMN])
            && !empty($this->properties[Opt::CRYPTO_CLASS]);
    }

    /**
     * @inheritdoc
     */
    public function getBackendName()
    {
        return "User SQL";
    }

    /**
     * @inheritdoc
     */
    public function deleteUser($uid)
    {
        return false;
    }

    /**
     * @inheritdoc
     */
    public function implementsActions($actions): bool
    {
        if ($actions & Backend::SET_PASSWORD) {
            return !empty($this->properties[Opt::PASSWORD_CHANGE]);
        }

        return parent::implementsActions($actions);
    }

    /**
     * @inheritdoc
     */
    public function canConfirmPassword(string $uid): bool
    {
        return true;
    }
}