Admin.php 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. <?php
  2. namespace App\Http\Middleware;
  3. use Closure;
  4. use Illuminate\Support\Facades\Cache;
  5. class Admin
  6. {
  7. /**
  8. * Handle an incoming request.
  9. *
  10. * @param \Illuminate\Http\Request $request
  11. * @param \Closure $next
  12. * @return mixed
  13. */
  14. public function handle($request, Closure $next)
  15. {
  16. $authorization = $request->input('auth_data') ?? $request->header('authorization');
  17. if (!$authorization) abort(403, '未登录或登陆已过期');
  18. $authData = explode(':', base64_decode($authorization));
  19. if (!Cache::has($authorization)) {
  20. if (!isset($authData[1]) || !isset($authData[0])) abort(403, '鉴权失败,请重新登入');
  21. $user = \App\Models\User::where('password', $authData[1])
  22. ->where('email', $authData[0])
  23. ->select([
  24. 'id',
  25. 'email',
  26. 'is_admin',
  27. 'is_staff'
  28. ])
  29. ->first();
  30. if (!$user) abort(403, '鉴权失败,请重新登入');
  31. if (!$user->is_admin) abort(403, '鉴权失败,请重新登入');
  32. Cache::put($authorization, $user->toArray(), 3600);
  33. }
  34. $request->merge([
  35. 'user' => Cache::get($authorization)
  36. ]);
  37. return $next($request);
  38. }
  39. }