首页 > 解决方案 > Yii2 - 限制未确认账户的访问

问题描述

我正在尝试实施电子邮件帐户验证。

如果用户没有确认他们的电子邮件,他们仍然可以登录,但他们应该无法访问account模块中的任何操作。例如,如果他们尝试访问:

它应该将用户重定向到/account/default/confirm,显示一条消息:

“您尚未确认您的账户,请点击确认邮件中的链接,或点击此处重新发送确认邮件”。

我尝试了以下方法:

BaseController:

class BaseController extends Controller
{
    protected function findUser($id)
    {
        if (($model = User::findOne(['id' => $id, 'deleted_at' => null])) !== null) {
            if ($model->confirmed_at == null) {
                return $this->redirect(['/account/default/confirm']);
            }

            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}

ProfileController:

class ProfileController extends BaseController
{
    public function actionEdit()
    {
        $user = $this->findUser(Yii::$app->user->id);
        $profile = $user->profile; // getProfile() relation in User model

        return $this->render('index', [
            'profile' => $profile,
        ]);
    }
}

我遇到的问题是它给了我一个错误:

“试图获取非对象的属性‘配置文件’”。

我认为错误的原因是因为它似乎将重定向分配给$user,而不是在重定向处实际终止请求。

我知道我可以在控制器动作中执行它而不是return $this->redirect()执行findUser()它,但是我必须为每个动作执行此操作。有没有更好的方法来做到这一点?也许某种访问规则或行为?

标签: phpyiiyii2

解决方案


$this->redirect()Response将返回响应对象 - 如果此类方法可能返回完全不相关的对象(或User),它看起来真的很糟糕。您可能应该调用Application::end()终止应用程序,因此重定向将在不继续执行控制器操作的情况下生效。

protected function findUser($id) {
    if (($model = User::findOne(['id' => $id, 'deleted_at' => null])) !== null) {
        if ($model->confirmed_at == null) {
            $this->redirect(['/account/default/confirm']);
            Yii::$app->end();
        }

        return $model;
    }

    throw new NotFoundHttpException('The requested page does not exist.');
}

推荐阅读