EloquentUserProvider.php 2.5 KB

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