2016-03-04 104 views
1

我在我的項目中爲用戶提供了一個特例。如果用戶的訂閱已過期(我在login action中查看),他將被重定向到他的profile以編輯一些選擇。我如何防止他訪問除他的profile之外的任何頁面。這是我在login action如何只訪問一個特定頁面YII2(高級模板)?

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]); 

        } 

       } 

回答

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), 
     ]); 
    } 
}