如何仅访问一个特定页面YII2(高级模板)?

时间:2016-03-04 19:23:39

标签: php yii2 yii2-advanced-app

我的项目中有一个特殊用户。如果用户的订阅已过期(我在login action中查看),他将被重定向到他的profile以编辑某些选项。如何阻止他访问除profile以外的任何页面。这是我在login action

中的代码
 if($subPaymentType == 'free'){
                    $subHours = $data[0]['sub_hours'];

                    $minutes = $subHours * 60 * 60;
                    $start_time = date('d-m-Y H:i:s', $startDate);
                    $endDate = $minutes + strtotime($start_time);
                    $endDate = date('d-m-Y H:i:s', $endDate);

                    if(strtotime(date('d-m-Y:')) < strtotime($endDate)){
                        $model->login();
                    }else{
                        $model->login();
                        //User can access this only page only
                        return $this->redirect(['user/view/?id='.Yii::$app->user->id]);

                    }

                }

1 个答案:

答案 0 :(得分:2)

您可以在控制器中使用AccessControl

yii\filters\AccessControl;



class YourSiteController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['login','profile'],
                        'allow' => true,
                        'roles' => ['*'],
                    ],
                    // allow authenticated users
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ],   
                ],
            ],         
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

请参阅本指南了解更多http://www.yiiframework.com/doc-2.0/yii-filters-accesscontrol.html

并在相关的actionView

public function actionView($id)
{
   if ($id != Yii::$app->user->id){
     // not allowed  ... perform the action you need in this case 
   } else {
      return $this->render('view', [
          'model' => $this->findModel($id),
      ]);
   }
}