同福

为页面/接口添加访问认证机制

开发

建立user模型

model/user.inc.php

class user extends tfmodel{
    public function __construct(tfphp $tfphp){
        $tableUser = new tfphp_members($tfphp);
        parent::__construct($tfphp, [
            "user"=>$tableUser,
        ]);
    }
    public function loadLoginUser(): ?array{
        $user = $this->getDAOSingle("user");
        $loginId = $_COOKIE["tfams_id"];
        if(!$loginId){
            return null;
        }
        $loginUser = $user->select(["mId"=>$loginId]);
        if($loginUser === null){
            return null;
        }
        return $loginUser;
    }
    public function authorizedTest(?array $loginUser, bool $API=false){
        if(!$loginUser){
            if(!$API){
                $this->tfphp->location("/login.html");
            }
            else{
                $this->tfphp->responseJsonData(["errcode"=>"1", "errmsg"=>"not authorized"]);
            }
        }
    }
    public function unauthorizedTest(?array $loginUser, bool $API=false){
        if($loginUser){
            if(!$API){
                $this->tfphp->location("/");
            }
            else{
                $this->tfphp->responseJsonData(["errcode"=>"1", "errmsg"=>"already authorized"]);
            }
        }
    }
}

给控制器添加访问认证机制

controller/member/index.inc.php

class index extends tfpage {
    protected function onLoad(){
        $user = new user($this->tfphp);
        // permit
        $loginUser = $user->loadLoginUser();
        $user->authorizedTest($loginUser);
    }
}