User.php 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. <?php
  2. namespace App\Http\Middleware;
  3. use Closure;
  4. use Illuminate\Support\Facades\Cache;
  5. class User
  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. Cache::put($authorization, $user->toArray(), 3600);
  32. }
  33. $request->merge([
  34. 'user' => Cache::get($authorization)
  35. ]);
  36. return $next($request);
  37. }
  38. }