Yii - 如何实现用户只能更新和删除自己的文件?

时间:2014-04-03 04:08:56

标签: php yii

我有这样的关系: relation

因此,当我创建/上传文件时,它将由用户上传。我希望用户只能更新/删除自己上传的文件。删除文件的示例,我试过这样的:

FileController.php中的

<?php
public function actionDelete($id)
{
    if($model->pengunggah=Yii::app()->user->id) // This is my modification

    $model = $this->loadModel($id);
    unlink(getcwd().'/files/'.$model->nama_file);

    if(Yii::app()->request->isPostRequest)
    {
        // we only allow deletion via POST request
        $this->loadModel($id)->delete();

        // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
        if(!isset($_GET['ajax']))
            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
    }
    else
        throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
}
?>

然后在protected / views / file / admin.php

array(
        'header'=>'Aksi',
        'class'=>'bootstrap.widgets.TbButtonColumn',
            'template'=>'{view}{update}{delete}', //'visible'=> (Yii::app()->user->getLevel()==1),
            'deleteConfirmation'=>"js: 'Are you want to delete '+$(this).parent().parent().children(':first-child').text()+ '?'",        
            'buttons'=>array(
                'update' => array(
                    'visible'=> 'Yii::app()->user->getLevel()==1',
                ),
                'view' => array(
                    'visible'=> 'Yii::app()->user->getLevel()==1',
                ),
                'delete' => array(
                    'visible'=>'Yii::app()->user->id',
                ), // This is my modification, I wanted to show delete button if the GridView is visited by a user whose have the file
            )   
    ),

我试过这样,但是用户仍然可以删除所有用户仍然可见的其他文件和按钮删除。我怎样才能做到这一点?非常感谢。

2 个答案:

答案 0 :(得分:2)

改变这个:

if($model->pengunggah=Yii::app()->user->id)

到此:

if($model->pengunggah != Yii::app()->user->id)
    throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');

您使用=代替==

你需要改变这个:

'delete' => array(
     'visible'=>'Yii::app()->user->id',
), 

到此:

'delete' => array(
     'visible'=>'$data->pengunggah == Yii::app()->user->id',
), 

或者如果您经常使用它,您可以在模块文件

中实现一个功能
public function checkUserAccess(){
    return $this->pengunggha == Yii::app()->user->id;
}

并像这样使用它:

if(!$model->checkUserAccess())
    throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');


'$data->checkUserAcces()'

答案 1 :(得分:0)

只需构建简单函数返回布尔结果,例如:

模型

<?php
...
public function checkAccess($if_file){
$model=Files::model()->find("if_file=:if_file and userId=:userId",array(':if_file'=>$if_file,':userId'=>Yii::app()->user->id));
if(count($model)>0){
    return true;
}else{
    return false;
}

}
...

?>
Now call your function in your gridview and in any another place need it.