Private Assets per User

First post.

First, this is a great framework, reviewing all free opensource headless API Cockpit’s Wins with almost needed functions included.

But sadly it desperate need’s better documentation. I spent hours searching for information…

Ok, Private Assets, for all how wish to use assets per user (except admin’s), put the fowling code in some bootstrap, like “config/bootstrap.php”

/**
 * Filter Assets to user
 */
$app->on('cockpit.assets.find', function(&$options) use ($app) {
  if ($app->user['group'] != 'admin') {
    $options['filter']['_by'] = $app->user['_id'];
  };
});

/**
 * Filter Assets Folders to user
 */
$app->on('cockpit.assetsfolders.find.before', function(&$options) use ($app) {
  if ($app->user['group'] != 'admin') {
    $options['filter']['_by'] = $app->user['_id'];
  };
});

An great thanks to Cockpit creator and all it’s supporters!

3 Likes

Hi, glad you like Cockpit. You can simplify the above code:

$app->on(['cockpit.assets.find', 'cockpit.assetsfolders.find.before'], function(&$options) use ($app) {
  if (!$app->module('cockpit')->isSuperAdmin()) {
    $options['filter']['_by'] = $app->user['_id'];
  };
});

A long time ago had similar request but also isolating in the filesystem the uploads of each user, I ended to doing something like below:

<?php

$this->on('cockpit.assets.find', function(&$options) use ($app) {
  $user = $app->module('cockpit')->getUser();
  $options['filter']['_by'] = $user['_id'];
});

$this->on('cockpit.asset.upload', function (&$asset, &$_meta, &$opts, &$file, &$path) use ($app) {
  $user = $app->module('cockpit')->getUser();
  if (!$app->helper('fs')->path("assets://{$user['_id']}")) {
    $app->helper('fs')->mkdir("assets://{$user['_id']}");
  }

  $clean = uniqid().preg_replace('/[^a-zA-Z0-9-_\.]/','', str_replace(' ', '-', $asset['title']));
  $path  = '/' . $user['_id'] . '/' .date('Y/m/d') . '/' . $clean;
  $asset['path'] = $path;
});


$this->on('cockpit.assetsfolders.find.before', function(&$options) use ($app) {
  $user = $app->module('cockpit')->getUser();
  $options['filter']['_by'] = $user['_id'];
});