我正在尝试实施电子邮件帐户验证。
如果用户尚未确认其电子邮件,他们仍然可以登录,但是他们将无法访问account
模块中的任何操作。因此,例如,如果他们尝试访问:
/account/profile/edit
/account/listing/add
它应将用户重定向到/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,
]);
}
}
我遇到的问题是它给了我一个错误:
“试图获取非对象的属性'profile'”。
我认为该错误的原因是因为它似乎是将重定向分配给$user
,而不是实际上在重定向处终止了请求。
我知道可以在控制器动作中执行此操作,而不是在return $this->redirect()
中执行findUser()
,但是然后我将必须为每个动作执行此操作。有更好的方法吗?也许是某种访问规则或行为?
答案 0 :(得分:0)
在这里尝试在!empty()
这样的访问权限之前检查$model
class BaseController extends Controller
{
protected function findUser($id)
{
if (($model = User::findOne(['id' => $id, 'deleted_at' => null])) !== null) {
if (!empty($model->confirmed_at)) {
return $model;
}
return $this->redirect(['/account/default/confirm']);
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
答案 1 :(得分:0)
$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.');
}