php - Yii2 - 限制未确认账户的访问
问题描述
我正在尝试实施电子邮件帐户验证。
如果用户没有确认他们的电子邮件,他们仍然可以登录,但他们应该无法访问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,
]);
}
}
我遇到的问题是它给了我一个错误:
“试图获取非对象的属性‘配置文件’”。
我认为错误的原因是因为它似乎将重定向分配给$user
,而不是在重定向处实际终止请求。
我知道我可以在控制器动作中执行它而不是return $this->redirect()
执行findUser()
它,但是我必须为每个动作执行此操作。有没有更好的方法来做到这一点?也许某种访问规则或行为?
解决方案
$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.');
}
推荐阅读
- python - 如何为图例的单个值设置唯一颜色
- database - Laravel 多对多关系集合为空
- python - 基于公共字段将两行合并为一
- mysql - 在带有 IN 子句的第二个查询中使用查询结果
- go - Go 无法识别安装在 ubuntu 18.04 上的 Goose
- postgresql - Postgres 在 UPDATE 语句中包含 REINDEX
- css - 角度 ng-table 的水平滚动
- python - Python Pandas:TypeError:只能将整数标量数组转换为标量索引
- css - CSS 样式的最高优先级
- spark-cassandra-connector - 这条消息的含义是什么 StorageProxy.java:2358 - 模式与 Cassandra debug.log 一致