<?php

namespace App\Http\Middleware;

use Closure;
use DB;
use Illuminate\Support\Facades\Crypt;
class WebLogin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(!$request->exists('api_token')){
            return response()->json(["code"=>300,'msg'=>'登录失败，token错误','data'=>'']);
        }
        $request['api_token_old'] = $request['api_token'];
        // 解密api_token，如果不是系统生成的token会解密失败
        try{
            $api_token = Crypt::decrypt($request['api_token']);
        }catch (\Exception $e){
            return response()->json(["code"=>300,'msg'=>'非法api_token','data'=>'']);
        }

        // 拿到token获取登录表信息
        $login_webapp = DB::table('login_webapp')
                        ->where('api_token','=',$api_token)
                        ->select('lowe_last_login','api_token')
                        ->first();
        if(empty($login_webapp)){
            return response()->json(["code"=>300,'msg'=>'不是系统api_token','data'=>'']);
        }

        // 判断api_token是否与数据库token一致
        if($api_token !== $login_webapp->api_token){
            return response()->json(["code"=>300,'msg'=>'api_token错误','data'=>'']);
        }

        // 当前时间
        $hours = time();
        // 如果最后登录时间小于当前时间,说明登陆过期
        if($login_webapp->lowe_last_login < $hours){
            return response()->json(["code"=>300,'msg'=>'登陆过期','data'=>'']);
        }

        // 如果一直在操作就当前时间加2小时
        DB::table('login_webapp')->where('api_token','=',$api_token)->update(['lowe_last_login'=>$hours + 2*60*60]);

        $request['api_token'] = $api_token;//赋值解密后的token值
        return $next($request);
    }
}
