MultiGuardUserProvider.php 2.6 KB

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