MemberAuthMiddleware.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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.send',
  17. 'news.banner',
  18. 'news.notices',
  19. 'news.notice',
  20. 'news.about_us',
  21. 'common.start',
  22. 'common.app_version',
  23. 'common.privacy_info',//获取隐私协议
  24. ];
  25. /**
  26. * Handle an incoming request.
  27. *
  28. * @param \Illuminate\Http\Request $request
  29. * @param \Closure $next
  30. * @return mixed
  31. */
  32. public function handle($request, Closure $next)
  33. {
  34. //设置系统语言包
  35. app()->setLocale(request()->input('lang', 'zh-Hans'));
  36. //验证会员授权信息
  37. $clientRoute = request()->route()->getName();
  38. $token=request()->header('Authorization');
  39. if(empty($token)){
  40. $token = request()->input('token','');
  41. }
  42. if (!in_array($clientRoute, $this->noAuth)) {
  43. if ( empty($token) ) {
  44. throw new MemberAuthException('auth.no_key', 401);
  45. }
  46. $member = RedisDataServer::creatServer()->getData( 'login_' . $token, 'json');
  47. if (empty($member)) {
  48. $member = Member::where('token_str', $token)->select(['id', 'address', 'status', 'token_str', 'level_id'])->first();
  49. if(empty($member)){
  50. throw new MemberAuthException('auth.login_error', 401);
  51. }
  52. }
  53. //用户信息缓存30秒
  54. RedisDataServer::creatServer()->setData($token . '_' . $token, $member, 'json', 300);
  55. $request->member = $member;
  56. }else{
  57. if( $token){
  58. $member = RedisDataServer::creatServer()->getData( 'login_' . $token, 'json');
  59. if (empty($member)) {
  60. $member = Member::where('token_str', $token)->where('status',1)->select(['id', 'address', 'status', 'token_str', 'level_id'])->first();
  61. }
  62. //用户信息缓存30秒
  63. if($member){
  64. RedisDataServer::creatServer()->setData('login_' . $token, $member, 'json', 300);
  65. $request->member = $member;
  66. }else{
  67. $request->member = ['id'=>0];
  68. }
  69. }else{
  70. $request->member = ['id'=>0];
  71. }
  72. }
  73. return $next($request);
  74. }
  75. }