MemberAuthMiddleware.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. class MemberAuthMiddleware
  8. {
  9. private $noAuth=[
  10. 'member.register',
  11. 'member.index',
  12. 'member.login',
  13. 'common.location',
  14. 'common.file',
  15. 'common.js',
  16. 'common.index',
  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. app()->setLocale(request()->input('lang', 'zh-Hans'));
  37. //验证会员授权信息
  38. $clientRoute = request()->route()->getName();
  39. $token=request()->header('Authorization');
  40. if(empty($token)){
  41. $token = request()->input('token','');
  42. }
  43. if (!in_array($clientRoute, $this->noAuth)) {
  44. if ( empty($token) ) {
  45. throw new MemberAuthException('auth.no_key', 401);
  46. }
  47. $member = RedisDataServer::creatServer()->getData( 'login_' . $token, 'json');
  48. if (empty($member)) {
  49. $member = Member::where('token_str', $token)->select(['id', 'address', 'status', 'token_str', 'level_id'])->first();
  50. if(empty($member)){
  51. throw new MemberAuthException('auth.login_error', 401);
  52. }
  53. }
  54. //用户信息缓存30秒
  55. RedisDataServer::creatServer()->setData($token . '_' . $token, $member, 'json', 300);
  56. $request->member = $member;
  57. }else{
  58. if( $token){
  59. $member = RedisDataServer::creatServer()->getData( 'login_' . $token, 'json');
  60. if (empty($member)) {
  61. $member = Member::where('token_str', $token)->where('status',1)->select(['id', 'address', 'status', 'token_str', 'level_id'])->first();
  62. }
  63. //用户信息缓存30秒
  64. if($member){
  65. RedisDataServer::creatServer()->setData('login_' . $token, $member, 'json', 300);
  66. $request->member = $member;
  67. }else{
  68. $request->member = ['id'=>0];
  69. }
  70. }else{
  71. $request->member = ['id'=>0];
  72. }
  73. }
  74. return $next($request);
  75. }
  76. }