菜谱项目

SignToken.php 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. namespace App\Http\Middleware;
  3. use Closure;
  4. use App\User;
  5. use App\Error;
  6. class SignToken
  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. $sign=$request->get('sign');
  18. if(!empty($sign)){
  19. $flag = $this->validSign($request);
  20. }else{
  21. $flag = $this->checkToken($request);
  22. }
  23. if($flag) {
  24. return $next($request);
  25. } else {
  26. return json_encode(['rst'=>['msg'=>'sign or token is error'], 'errno'=>'401', 'err'=>Error::getError(401),'timestamp'=>time().'']);
  27. }
  28. }
  29. //验证token是否有效
  30. private function checkToken($request) {
  31. $token = $request->headers->get('token') ? $request->headers->get('token') : ($request->get('token') ? $request->get('token') : null);
  32. if(empty($token)) return false;
  33. $data = User::parseToken($token);
  34. if(empty($data) || ($token!=$data->token && (($data->last_login_time - 30 *86400) > time()))) {
  35. return false;
  36. }
  37. return true;
  38. }
  39. public function validSign($request) {
  40. // print_r($request->all());exit;
  41. $params=$request->all();
  42. $sign=$request->get('sign');
  43. if(empty($sign)){
  44. return false;
  45. }
  46. $makesign = $this->getSignature($params, Config('constants.SMS_SECRET_KEY'));
  47. if($makesign == $sign) {
  48. return true;
  49. }
  50. return false;
  51. }
  52. public function getSignature($params, $secret_key) {
  53. // 按数组键名 正序排序
  54. ksort($params);
  55. $tem = array();
  56. foreach ($params as $k => $v) {
  57. if ($k !== 'sign') {
  58. $tem[] = "$k=$v";
  59. }
  60. }
  61. $sk = implode('&', $tem) . $secret_key;
  62. return md5($sk);
  63. }
  64. }