<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Crypt;
use DB;

class AppRole
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // 当前访问的控制器方法名
        $current_path = \Route::current()->getActionName().',';

        try{
            $api_token = Crypt::decrypt($request['api_token']);
        }catch (\Exception $e){
            return response()->json(["code"=>500,'msg'=>'error','data'=>'非法api_token']);
        }
        //获取当前账号所有的路径
        $auth_routes = DB::table('login_webapp')
                                ->leftjoin('admin','login_temporary.adm_id','=','admin.adm_id')
                                ->where('api_token','=',$api_token)
                                ->select('auth_routes','admin.adm_cid')
                                ->first();
        $auth_routes = json_decode($auth_routes['auth_routes']);
        // print_r($auth_routes);
        // print_r($current_path);die;

        // 如果当前访问路径存在于当前账号角色权限中就放行
        if(in_array($current_path,$auth_routes))
        {
            return $next($request);
        }else{
            return response()->json(["code"=>500,'msg'=>'error','data'=>'此账号无权访问']);
        }
    }
}
