<?php
declare (strict_types = 1);

namespace app\admin\middleware;

use think\facade\Session;

/**
 * 验证登录中间件
 * Class Auth
 * @package app\admin\middleware
 */
class Auth
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        //
        $master = Session::get('master','');
        $currentUrl = explode("/",$request->url());
        $currentRoute = array_pop($currentUrl) ;

        if( empty( $master ) && strpos($currentRoute,'login') === false ){
            if( $request->isAjax() ){
                abort(401);
            }
            return redirect($request->rootUrl().'/login') ;
        }

        if( !empty( $master ) && strpos($currentRoute,'login') !== false){
            return redirect($request->rootUrl().'/') ;
        }

        return $next($request);
    }
}
