CakePHP Auth-允许未登录用户访问,但随后根据其他条件进行限制


CakePHP Auth - Allow access to non-logged in users, but then restrict based on other criteria

我将直接讨论这个问题。

我有用户,拥有隐私权。隐私可以是公开的,也可以是私人的。我希望能够允许未登录的用户能够查看另一个用户,只要该用户是公共用户,当然,如果他们是私人用户,请检查该用户是否为当前用户。

我想不出最好的方法来做这件事,因为isAuthorized只对登录的用户调用,而我不能只允许操作,因为那时根本不调用isAuthorified。

如有任何帮助,我们将不胜感激。

您需要在控制器操作中准备一些逻辑,以验证配置文件是公共的还是私有的,以及它是私有的,当前登录的用户(如果有的话)是否是配置文件的所有者。像这样的东西应该可以做到:

// app/Controller/UsersController.php
public function view($id) {
    // Check the privacy setting
    if ($this->User->isPrivate($id)) {
        // Private profile, check if user is logged in and id matches
        if (empty($this->Auth->user()) || $this->Auth->user('id') != $id) {
            // User is either not logged in or not the person we want to view
            $this->Session->setFlash(
                // Inspired by Cartman rage... you might want to change it ;-)
                __('No kitty, this is my profile!')
            );
            // Redirect the user back to our index action (or anywhere else)
            $this->redirect(array('action' => 'index'));
        }
    }
}

并确保在您的模型中创建isPrivate检查方法:

// app/Model/User.php
public function isPrivate($id) {
    $privacy = $this->field('privacy', array('id' => $id));
    if ($privacy == 'private') {
        // This is a private profile
        return true;
    }
    // This is a public profile
    return false;
}