|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Binarcode\LaravelDeveloper\Middleware; |
| 4 | + |
| 5 | +use Closure; |
| 6 | +use Illuminate\Http\Request; |
| 7 | +use Illuminate\Support\Facades\App; |
| 8 | + |
| 9 | +class DevSanctumAuthMiddleware |
| 10 | +{ |
| 11 | + /** |
| 12 | + * @var Closure |
| 13 | + */ |
| 14 | + public static $resolveUser; |
| 15 | + |
| 16 | + /** |
| 17 | + * Handle an incoming request. |
| 18 | + * |
| 19 | + * @param \Illuminate\Http\Request $request |
| 20 | + * @param \Closure $next |
| 21 | + * @return mixed |
| 22 | + */ |
| 23 | + public function handle(Request $request, Closure $next) |
| 24 | + { |
| 25 | + if (! App::environment('local')) { |
| 26 | + return $next($request); |
| 27 | + } |
| 28 | + |
| 29 | + if ($request->header('Authorization') !== 'Bearer testing') { |
| 30 | + return $next($request); |
| 31 | + } |
| 32 | + |
| 33 | + if (is_callable(static::$resolveUser)) { |
| 34 | + $user = call_user_func(static::$resolveUser, $request); |
| 35 | + } else { |
| 36 | + /** * @var string $class */ |
| 37 | + $class = config('app.providers.users.model'); |
| 38 | + |
| 39 | + $user = $class::query()->first(); |
| 40 | + } |
| 41 | + |
| 42 | + |
| 43 | + if (is_null($user)) { |
| 44 | + return $next($request); |
| 45 | + } |
| 46 | + |
| 47 | + if (! in_array(\Laravel\Sanctum\HasApiTokens::class, class_uses_recursive($user))) { |
| 48 | + return $next($request); |
| 49 | + } |
| 50 | + |
| 51 | + $token = $user->createToken('login')->plainTextToken; |
| 52 | + |
| 53 | + $bag = $request->headers; |
| 54 | + |
| 55 | + $bag->add([ |
| 56 | + 'Authorization' => "Bearer {$token}", |
| 57 | + ]); |
| 58 | + |
| 59 | + return $next($request); |
| 60 | + } |
| 61 | + |
| 62 | + public static function resolveUserUsing(Closure $resolveUser): string |
| 63 | + { |
| 64 | + static::$resolveUser = $resolveUser; |
| 65 | + |
| 66 | + return static::class; |
| 67 | + } |
| 68 | +} |
0 commit comments