You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

54 lines
1.4 KiB

  1. <?php
  2. namespace App\Utilities\Providers;
  3. use App\Models\User;
  4. use Illuminate\Http\Request;
  5. use Illuminate\Support\Arr;
  6. use Illuminate\Support\Facades\Auth;
  7. use Illuminate\Support\Facades\Http;
  8. use Illuminate\Support\ServiceProvider;
  9. class AuthServiceProvider extends ServiceProvider
  10. {
  11. public function boot()
  12. {
  13. $this->app['auth']->viaRequest('api', function (Request $request) {
  14. // with token
  15. if ($request->bearerToken()) {
  16. return $this->loginUserWithToken($request);
  17. }
  18. // first party
  19. if ($request->getHost() === $container_name = getenv('CONTAINER_NAME')) {
  20. return $this->loginServiceWithSetUser($container_name);
  21. }
  22. // without token
  23. return null;
  24. });
  25. }
  26. public function loginUserWithToken(Request $request): User
  27. {
  28. $attributes = Http::retry(3, 100)
  29. ->withToken($request->bearerToken())
  30. ->get(env('USER_URL') . 'auth')
  31. ->json();
  32. $attributes = Arr::get($attributes, 'data',[]);
  33. // dd($attributes);
  34. return new User($attributes);
  35. }
  36. public function loginServiceWithSetUser(string $container_name): User
  37. {
  38. Auth::setUser($user = new User([
  39. 'name' => $container_name,
  40. 'is_service' => true,
  41. ]));
  42. return $user;
  43. }
  44. }