EloquentUserProvider.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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\Facades\Log;
  16. use Illuminate\Support\Str;
  17. class EloquentUserProvider extends BaseEloquentUserProvider
  18. {
  19. /**
  20. * Retrieve a user by their unique identifier.
  21. *
  22. * @param mixed $identifier
  23. * @return \Illuminate\Contracts\Auth\Authenticatable|null
  24. */
  25. public function retrieveById($identifier)
  26. {
  27. /**
  28. * 区别guards
  29. * mead
  30. */
  31. // $class_name = get_class($this->createModel());
  32. // $cacheKey = CacheEnum::getCacheKey(CacheEnum::AUTHORIZATION_USER, $identifier) . ":{$class_name}";
  33. $cacheKey = CacheEnum::getCacheKey(CacheEnum::AUTHORIZATION_USER, $identifier);
  34. $cacheExpireTime = CacheEnum::getCacheExpireTime(CacheEnum::AUTHORIZATION_USER);
  35. return Cache::remember($cacheKey, $cacheExpireTime, function () use ($identifier) {
  36. $model = $this->createModel();
  37. return $this->newModelQuery($model)
  38. ->where($model->getAuthIdentifierName(), $identifier)
  39. ->first();
  40. });
  41. }
  42. /**
  43. * Retrieve a user by the given credentials.
  44. *
  45. * @param array $credentials
  46. * @return \Illuminate\Contracts\Auth\Authenticatable|null
  47. */
  48. public function retrieveByCredentials(array $credentials)
  49. {
  50. if (empty($credentials) ||
  51. (count($credentials) === 1 &&
  52. Str::contains($this->firstCredentialKey($credentials), 'password'))) {
  53. return;
  54. }
  55. // First we will add each credential element to the query as a where clause.
  56. // Then we can execute the query and, if we found a user, return it in a
  57. // Eloquent User "model" that will be utilized by the Guard instances.
  58. $query = $this->newModelQuery();
  59. foreach ($credentials as $key => $value) {
  60. if (Str::contains($key, 'password')) {
  61. continue;
  62. }
  63. if (is_array($value) || $value instanceof Arrayable) {
  64. $query->whereIn($key, $value);
  65. } else {
  66. $query->where($key, $value);
  67. }
  68. }
  69. return $query->first();
  70. }
  71. }