菜谱项目

TokenAuth.php 980B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. <?php
  2. namespace App\Http\Middleware;
  3. use Closure;
  4. use App\User;
  5. use App\Error;
  6. class TokenAuth
  7. {
  8. /**
  9. * Handle an incoming request.
  10. *
  11. * @param \Illuminate\Http\Request $request
  12. * @param \Closure $next
  13. * @return mixed
  14. */
  15. public function handle($request, Closure $next)
  16. {
  17. $flag = $this->checkToken($request);
  18. if($flag) {
  19. return $next($request);
  20. } else {
  21. return json_encode(['rst'=>['msg'=>'token is error'], 'errno'=>'401', 'err'=>Error::getError(401),'timestamp'=>time().'']);
  22. }
  23. }
  24. //验证token是否有效
  25. private function checkToken($request) {
  26. $token = $request->headers->get('token') ? $request->headers->get('token') : ($request->get('token') ? $request->get('token') : null);
  27. if(empty($token)) return false;
  28. $data = User::parseToken($token);
  29. if(empty($data) || ($token!=$data->token && (($data->last_login_time - 30 *86400) > time()))) {
  30. return false;
  31. }
  32. return true;
  33. }
  34. }