Restrict user file access via relative url

83 views Asked by At

I have setup a cms application using Yii2 php framework. However, I have run into the situation where if a user can create a post that includes images or documents, she/he can look at the html source code for that post in the WYSIWIG editor and change the src link to another user's content. For example, if Fred has link that looks like this userfiles/fred/myimage.png He can look at the html source and change it to userfiles/john/anotherimage.png.

How can I make it so that Fred can only access userfiles/fred with relative Urls in his cms posts?

I have tried researching .htaccess but I am stuck as to how to apply that to specific users logged into my application.

1

There are 1 answers

0
e-frank On
  1. don't store your file in @web, but some higher level
  2. write a custom action, streaming the requested file. you can handle permissions here (Yii::$app->user->can('doit')), sending could be:

    if (file_exists($filename)) {
        Yii::$app->response->format = \yii\web\Response::FORMAT_RAW;
        Yii::$app->response->headers->add('Content-Type', FileHelper::getMimeTypeByExtension($filename));
        Yii::$app->response->headers->add('Content-Length', filesize($filename));
    
        return file_get_contents($filename);
    } else {
        throw new yii\web\NotFoundHttpException($filename);
    }
    

see getMimeTypeByExtension