123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 |
- <?php
- namespace App\Http\Middleware;
- use Closure;
- use App\User;
- use App\Error;
- class SignToken
- {
- /**
- * Handle an incoming request.
- *
- * @param \Illuminate\Http\Request $request
- * @param \Closure $next
- * @return mixed
- */
- public function handle($request, Closure $next)
- {
- $sign=$request->get('sign');
- if(!empty($sign)){
- $flag = $this->validSign($request);
- }else{
- $flag = $this->checkToken($request);
- }
- if($flag) {
- return $next($request);
- } else {
- return json_encode(['rst'=>['msg'=>'sign or token is error'], 'errno'=>'401', 'err'=>Error::getError(401),'timestamp'=>time().'']);
- }
- }
- //验证token是否有效
- private function checkToken($request) {
- $token = $request->headers->get('token') ? $request->headers->get('token') : ($request->get('token') ? $request->get('token') : null);
- if(empty($token)) return false;
- $data = User::parseToken($token);
- if(empty($data) || ($token!=$data->token && (($data->last_login_time - 30 *86400) > time()))) {
- return false;
- }
- return true;
- }
- public function validSign($request) {
- // print_r($request->all());exit;
- $params=$request->all();
- $sign=$request->get('sign');
- if(empty($sign)){
- return false;
- }
- $makesign = $this->getSignature($params, Config('constants.SMS_SECRET_KEY'));
- if($makesign == $sign) {
- return true;
- }
- return false;
- }
- public function getSignature($params, $secret_key) {
- // 按数组键名 正序排序
- ksort($params);
- $tem = array();
- foreach ($params as $k => $v) {
- if ($k !== 'sign') {
- $tem[] = "$k=$v";
- }
- }
- $sk = implode('&', $tem) . $secret_key;
- return md5($sk);
- }
- }
|