AdminApiAuthMiddleware.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. namespace App\Http\Middleware;
  3. use App\Models\UserModels\User;
  4. use App\Servers\Common\RedisDataServer;
  5. use App\Servers\Logs\AdminLogsServer;
  6. use Closure;
  7. class AdminApiAuthMiddleware
  8. {
  9. private $noAuth = [
  10. 'adminApi.login',
  11. 'adminApi.logout',
  12. ];
  13. /**
  14. * Handle an incoming request.
  15. *
  16. * @param \Illuminate\Http\Request $request
  17. * @param \Closure $next
  18. * @return mixed
  19. */
  20. public function handle($request, Closure $next)
  21. {
  22. $clientRoute = request()->route()->getName();//获取当前路由
  23. if (in_array($clientRoute, $this->noAuth)) {//不需要验证的路由
  24. return $next($request);
  25. }
  26. //获取token
  27. $api_token = $request->input('api_token');
  28. if(empty($api_token)) $api_token = $request->header('ApiToken');
  29. if(empty($api_token)){
  30. return response()->json([
  31. 'msg' => '缺少认证信息',
  32. 'code' => 401,
  33. 'data' => []
  34. ]);
  35. }
  36. //获取当前用户
  37. $user = RedisDataServer::creatServer()->getData( 'gw_adminLogin_' . $api_token, 'json');
  38. if(!$user){
  39. //数据库查找当前用户
  40. $user = User::where('api_token', $api_token)->where('is_del', 0)->first();
  41. if($user){
  42. //用户信息缓存
  43. RedisDataServer::creatServer()->setData('gw_adminLogin_' . $api_token, $user, 'json', 300);
  44. }else{
  45. return response()->json([
  46. 'msg' => '身份验证失败',
  47. 'code' => 401,
  48. 'data' => []
  49. ]);
  50. }
  51. }
  52. //状态验证
  53. if($user['status'] == 2){
  54. return response()->json([
  55. 'msg' => '账号已关闭',
  56. 'code' => 402,
  57. 'data' => []
  58. ]);
  59. }
  60. $request->admin_user = $user;
  61. //日志记录
  62. AdminLogsServer::write('',$user['id']);
  63. return $next($request);
  64. }
  65. }