EloquentUserProvider.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. /*
  3. * This file is part of the Jiannei/lumen-api-starter.
  4. *
  5. * (c) Jiannei <longjian.huang@foxmail.com>
  6. *
  7. * This source file is subject to the MIT license that is bundled
  8. * with this source code in the file LICENSE.
  9. */
  10. namespace App\Providers;
  11. use App\Repositories\Enums\CacheEnum;
  12. use Illuminate\Auth\EloquentUserProvider as BaseEloquentUserProvider;
  13. use Illuminate\Contracts\Support\Arrayable;
  14. use Illuminate\Support\Facades\Cache;
  15. use Illuminate\Support\Str;
  16. class EloquentUserProvider extends BaseEloquentUserProvider
  17. {
  18. /**
  19. * Retrieve a user by their unique identifier.
  20. *
  21. * @param mixed $identifier
  22. * @return \Illuminate\Contracts\Auth\Authenticatable|null
  23. */
  24. public function retrieveById($identifier)
  25. {
  26. $cacheKey = CacheEnum::getCacheKey(CacheEnum::AUTHORIZATION_USER, $identifier);
  27. $cacheExpireTime = CacheEnum::getCacheExpireTime(CacheEnum::AUTHORIZATION_USER);
  28. return Cache::remember($cacheKey, $cacheExpireTime, function () use ($identifier) {
  29. $model = $this->createModel();
  30. return $this->newModelQuery($model)
  31. ->where($model->getAuthIdentifierName(), $identifier)
  32. ->first();
  33. });
  34. }
  35. /**
  36. * Retrieve a user by the given credentials.
  37. *
  38. * @param array $credentials
  39. * @return \Illuminate\Contracts\Auth\Authenticatable|null
  40. */
  41. public function retrieveByCredentials(array $credentials)
  42. {
  43. if (empty($credentials) ||
  44. (count($credentials) === 1 &&
  45. Str::contains($this->firstCredentialKey($credentials), 'password'))) {
  46. return;
  47. }
  48. // First we will add each credential element to the query as a where clause.
  49. // Then we can execute the query and, if we found a user, return it in a
  50. // Eloquent User "model" that will be utilized by the Guard instances.
  51. $query = $this->newModelQuery();
  52. foreach ($credentials as $key => $value) {
  53. if (Str::contains($key, 'password')) {
  54. continue;
  55. }
  56. if (is_array($value) || $value instanceof Arrayable) {
  57. $query->whereIn($key, $value);
  58. } else {
  59. $query->where($key, $value);
  60. }
  61. }
  62. return $query->first();
  63. }
  64. }