Restrict assets file type when uploading via API

It seems Cockpit allow all file types by default when uploading via “/api/cockpit/addAssets”.

Is there any proper way to just allow uploading image only ( png, gif, jpg, jpeg )?

I found out the way to restrict without modifying cockpit code.

I use the below codes as an addon.

bootstrap.php

<?php

/**
 * Secure Uploading Assets
 * Only allow image type (png,jpeg,jpg,gif)
 */

function validateImageType(){

        $files = $_FILES['files'];

        foreach($files['tmp_name'] as $key => $file){

            $info = getimagesize($file);

            if ($info === FALSE || ($info[2] !== IMAGETYPE_GIF) && ($info[2] !== IMAGETYPE_JPEG) && ($info[2] !== IMAGETYPE_PNG)) {

                die('Please only upload image file, thanks.');

            }

        }

    }

if(COCKPIT_API_REQUEST){
    $app->on('cockpit.rest.init', function($routes) {
        if($this['route'] == '/api/cockpit/addAssets'){
            validateImageType();
        }
    });
}

You can also set allowed file extensions via /path/to/cockpit/config/config.php:

return [

    // restrict allowed file extensions for assets

    // for  all users
    'allowed_uploads' => 'jpg, jpeg, png, gif',

    // for groups
    'groups' => [
        'author' => [
            '$vars' => [
                'assets.allowed_uploads' => 'jpg, jpeg, png, gif'
            ],
        ]
    ],
];

see also:

1 Like

Thanks @raffaelj , this method is way more elegant than mine.