MemberAuthMiddleware.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. namespace App\Http\Middleware;
  3. use App\Exceptions\MemberAuthException;
  4. use App\Models\Member;
  5. use App\Servers\RedisDataServer;
  6. use Closure;
  7. use Illuminate\Support\Facades\Auth;
  8. class MemberAuthMiddleware
  9. {
  10. private $noAuth=[
  11. 'member.register',
  12. 'member.index',
  13. 'member.login',
  14. 'common.location',
  15. 'common.file',
  16. 'common.js',
  17. 'common.send',
  18. 'news.banner',
  19. 'news.notices',
  20. 'news.notice',
  21. 'news.about_us',
  22. 'common.start',
  23. 'common.app_version',
  24. 'common.privacy_info',//获取隐私协议
  25. ];
  26. /**
  27. * Handle an incoming request.
  28. *
  29. * @param \Illuminate\Http\Request $request
  30. * @param \Closure $next
  31. * @return mixed
  32. */
  33. public function handle($request, Closure $next)
  34. {
  35. //验证会员授权信息
  36. $clientRoute = request()->route()->getName();
  37. $token=request()->header('Authorization');
  38. if(empty($token)){
  39. $token = $request->input('token','');
  40. }
  41. if (!in_array($clientRoute, $this->noAuth)) {
  42. if ( empty($token) ) {
  43. throw new MemberAuthException('缺少认证信息', 401);
  44. }
  45. $member = RedisDataServer::creatServer()->getData( 'login_' . $token, 'json');
  46. if (empty($member)) {
  47. $member = Member::where('token_str', $token)->where('status',1)->select(['id', 'address', 'status', 'token_str', 'level_id'])->first();
  48. if(empty($member)){
  49. throw new MemberAuthException('认证信息已过期', 401);
  50. }
  51. }
  52. Auth::loginUsingId($member['id']);
  53. //用户信息缓存30秒
  54. RedisDataServer::creatServer()->setData($token . '_' . $token, $member, 'json', 300);
  55. }
  56. return $next($request);
  57. }
  58. }