Skip to content

Commit

Permalink
feat(file): Added file management compatibility
Browse files Browse the repository at this point in the history
  • Loading branch information
anibalealvarezs committed Mar 6, 2022
1 parent d4e3ec9 commit c2bf41a
Show file tree
Hide file tree
Showing 13 changed files with 599 additions and 8 deletions.
5 changes: 3 additions & 2 deletions src/Controllers/Config/PbConfigController.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

use Auth;
use DB;
use ReflectionException;
use Session;

use Inertia\Response as InertiaResponse;
Expand Down Expand Up @@ -43,7 +44,7 @@ function __construct(Request $request, $crud_perms = false)
*
* @param string $route
* @return InertiaResponse|JsonResponse
* @throws \ReflectionException
* @throws ReflectionException
*/
public function create(string $route = 'level'): InertiaResponse|JsonResponse
{
Expand Down Expand Up @@ -73,7 +74,7 @@ public function store(Request $request): Redirector|RedirectResponse|Application
* @param bool $multiple
* @param string $route
* @return RedirectResponse|InertiaResponse|JsonResponse
* @throws \ReflectionException
* @throws ReflectionException
*/
public function edit(
int $id,
Expand Down
210 changes: 210 additions & 0 deletions src/Controllers/File/PbFileController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,210 @@
<?php

namespace Anibalealvarezs\Projectbuilder\Controllers\File;

use Anibalealvarezs\Projectbuilder\Controllers\PbBuilderController;
use Anibalealvarezs\Projectbuilder\Utilities\PbUtilities;
use Anibalealvarezs\Projectbuilder\Utilities\PbCache;
use App\Http\Requests;
use Illuminate\Http\Request;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Http\RedirectResponse;
use Illuminate\Routing\Redirector;

use Auth;

class PbFileController extends PbBuilderController
{
function __construct(Request $request, $crud_perms = false)
{
$this->varsObject([
'keys' => [
'level' => 'File'
],
'validationRules' => [
'name' => ['max:128'],
'description' => [],
'alt' => [],
],
'modelExclude' => ['file'],
'showId' => true,
'defaults' => [
'status' => 1,
],
]);
// Parent construct
parent::__construct($request, true);
}

/**
* Store a newly created resource in storage.
*
* @param Request $request
* @return Application|Redirector|RedirectResponse|null
*/
public function store(Request $request): Redirector|RedirectResponse|Application|null
{
$this->pushValidationRules([
'file' => ['required', 'file', 'mimes:jpeg,png,jpg,gif,svg,pdf', 'max:8192'],
'module' => ['nullable', 'max:32'],
'permission' => ['required', 'max:32'],
]);

// Validation
if ($failed = $this->validateRequest($this->vars->validationRules, $request)) {
return $failed;
}

$file = $request->file('file');

// Process
try {
// Build model
$model = resolve($this->vars->level->modelPath)->setLocale(app()->getLocale());
// Add requests
$model = $this->processModelRequests(
validationRules: $this->vars->validationRules,
request: $request,
replacers: $this->vars->replacers,
model: $model
);

// Default module for file storage
$model->module = $model->module ?: $this->vars->level->name;

$name = PbUtilities::checkName(
dir: $model->module ?: $this->vars->level->name,
name: ($model->name ?: $file->getClientOriginalName()),
extension: $file->extension()
);
if (!$name) {
return $this->redirectResponseCRUDFail($request, 'create', 'No valid name for file');
}
if ($newfile = PbUtilities::saveFile($file, $model->module, $name)) {
$model->name = $name;
$model->mime_type = $newfile->getMimeType();
$model->user_id = Auth::user()->id;
$model->hash = md5($newfile->getContent());
if (!$model->save()) {
return $this->redirectResponseCRUDFail($request, 'create', "Error saving {$this->vars->level->name}");
}

PbCache::clearIndex(
package: $this->vars->helper->package,
models: $this->vars->level->names,
);
} else {
return $this->redirectResponseCRUDFail($request, 'create', 'File could not be saved');
}

return $this->redirectResponseCRUDSuccess($request, 'create');
} catch (Exception $e) {
return $this->redirectResponseCRUDFail($request, 'create', $e->getMessage());
}
}

/**
* Update the specified resource in storage.
*
* @param Request $request
* @param int $id
* @return Application|Redirector|RedirectResponse|null
*/
public function update(Request $request, int $id): Redirector|RedirectResponse|Application|null
{
// Validation
if ($failed = $this->validateRequest($this->vars->validationRules, $request)) {
return $failed;
}

// Set cache/methods arguments
$this->initArgs([
'function' => 'update',
]);

// Process
try {
// Build model
if (!$model = $this->vars->level->modelPath::find($id)) {
return $this->redirectResponseCRUDFail($request, 'update', "Error finding {$this->vars->level->name} with id $id");
}
// Check Permissions
$this->checkPermissions($model);
// Set Locale
$model->setLocale(app()->getLocale());
// Prepare file name and extension
$currentName = $model->name;
$extension = PbUtilities::getFileExtension($model->name);
// Build requests
$model = $this->processModelRequests(
validationRules: $this->vars->validationRules,
request: $request,
replacers: $this->vars->replacers,
model: $model
);
$updateAuthor = true;
if (!$model->name) {
$model->name = $currentName;
} elseif ($currentName != $model->name) {
$model->name = PbUtilities::checkName($model->module, $model->name, $extension, "", $currentName);
if ($currentName != $model->name) {
$updateAuthor = PbUtilities::updateFile($model->module, $currentName, $model->name);
}
}
if ($updateAuthor) {
$model->user_id = Auth::user()->id;
// Model update
if (!$model->save()) {
return $this->redirectResponseCRUDFail($request, 'update', "Error updating {$this->vars->level->name}");
}

PbCache::clearModel(
package: $this->vars->helper->package,
models: $this->vars->level->names,
modelId: $id,
);
} else {
return $this->redirectResponseCRUDFail($request, 'update', 'File could not be saved');
}

return $this->redirectResponseCRUDSuccess($request, 'update');
} catch (Exception $e) {
return $this->redirectResponseCRUDFail($request, 'update', $e->getMessage());
}
}

/**
* Remove the specified resource from storage.
*
* @param Request $request
* @param int $id
* @return Application|Redirector|RedirectResponse
*/
public function destroy(Request $request, int $id): Redirector|RedirectResponse|Application
{
// Set cache/methods arguments
$this->initArgs([
'function' => 'destroy',
]);
// Process
try {
if (!$model = $this->vars->level->modelPath::find($id)) {
return $this->redirectResponseCRUDFail($request, 'delete', "Error finding {$this->vars->level->name}");
}
// Check Permissions
$this->checkPermissions($model);
if (PbUtilities::deleteFile($model->module, $model->name)) {
// Model delete
if (!$model->delete()) {
return $this->redirectResponseCRUDFail($request, 'delete', "Error deleting {$this->vars->level->name}");
}

PbCache::clearAll();
}

return $this->redirectResponseCRUDSuccess($request, 'delete');
} catch (Exception $e) {
return $this->redirectResponseCRUDFail($request, 'delete', $e->getMessage());
}
}
}
39 changes: 39 additions & 0 deletions src/Database/Migrations/create_files_table.php.stub
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateFilesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('files', function (Blueprint $table) {
$table->id();
$table->string('name', 128)->nullable(false);
$table->json('description')->nullable();
$table->json('alt')->nullable();
$table->string('mime_type', 32)->nullable(false);
$table->string('hash', 32)->nullable(false);
$table->string('module', 32)->nullable(false);
$table->string('permission', 32)->nullable(false);
$table->unsignedInteger('user_id')->nullable(false);
$table->timestamps();
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('files');
}
}
2 changes: 2 additions & 0 deletions src/Database/Seeders/PbConfigSeeder.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ class PbConfigSeeder extends Seeder
public function run()
{
$moduleConfig = PbModule::where('modulekey', 'config')->first();
$moduleFile = PbModule::where('modulekey', 'file')->first();
// Default Config
Config::upsert([
['configkey' => '_APP_NAME_', 'configvalue' => 'Builder', 'name' => json_encode(['en' => 'App Name', 'es' => 'Nombre de la Aplicación']), 'description' => json_encode(['en' => 'App Description', 'es' => 'Nombre de la Aplicación']), 'module_id' => $moduleConfig->id],
Expand All @@ -32,6 +33,7 @@ public function run()
['configkey' => '_DISABLE_REGISTER_', 'configvalue' => false, 'name' => json_encode(['en' => 'Disable registration form', 'es' => 'Deshabilitar formulario de registro']), 'description' => json_encode(['en' => 'Disable the registration form', 'es' => 'Deshabilitar el formulario de registro']), 'module_id' => $moduleConfig->id],
['configkey' => '_DEFAULT_TABLE_SIZE_', 'configvalue' => false, 'name' => json_encode(['en' => 'Default table size', 'es' => 'Tamaño de la tabla por defecto']), 'description' => json_encode(['en' => 'Number of rows to be shown in tables per page', 'es' => 'Número de registros a mostrar en las tablas por defecto']), 'module_id' => $moduleConfig->id],
['configkey' => '_CACHE_ENABLED_', 'configvalue' => false, 'name' => json_encode(['en' => 'Enable Cache', 'es' => 'Habilitar Caché']), 'description' => json_encode(['en' => 'Enable queries caching to increase performance', 'es' => 'Habilitar el caché de consultas para mejorar el rendimiento']), 'module_id' => $moduleConfig->id],
['configkey' => '_HASH_FILE_NAME_', 'configvalue' => '0', 'name' => json_encode(['en' => 'File Name Hashing', 'es' => 'Hashear Nombres de Archivos']), 'description' => json_encode(['en' => 'Force file names hashing (recommended for higher security)', 'es' => 'Forzar hasheo de nombres (recomendado para mayor seguridad)']), 'module_id' => $moduleFile->id],
], ['configkey'], ['configvalue', 'name', 'description', 'module_id']);
}
}
1 change: 1 addition & 0 deletions src/Database/Seeders/PbModulesSeeder.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ public function run()
['modulekey' => 'permission', 'name' => json_encode(['en' => 'Permissions', 'es' => 'Permisos']), 'status' => 1],
['modulekey' => 'role', 'name' => json_encode(['en' => 'Roles', 'es' => 'Roles']), 'status' => 1],
['modulekey' => 'logger', 'name' => json_encode(['en' => 'Logger', 'es' => 'Logger']), 'status' => 1],
['modulekey' => 'file', 'name' => json_encode(['en' => 'Files Manager', 'es' => 'Administrador de Archivos']), 'status' => 1],
], ['modulekey'], ['name', 'status']);
}
}
10 changes: 10 additions & 0 deletions src/Database/Seeders/PbNavigationSeeder.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,13 @@ public function run()
$readConfigsPermission = PbPermission::where('name', 'read configs')->first();
$readNavigationsPermission = PbPermission::where('name', 'read navigations')->first();
$readLoggersPermission = PbPermission::where('name', 'read loggers')->first();
$readFilemanagerPermission = PbPermission::where('name', 'read files')->first();
$moduleUser = PbModule::where('modulekey', 'user')->first();
$moduleConfig = PbModule::where('modulekey', 'config')->first();
$moduleNavigation = PbModule::where('modulekey', 'navigation')->first();
$moduleRole = PbModule::where('modulekey', 'role')->first();
$modulePermission = PbModule::where('modulekey', 'permission')->first();
$moduleFilemanager = PbModule::where('modulekey', 'file')->first();

Navigation::query()->delete();

Expand Down Expand Up @@ -67,5 +69,13 @@ public function run()
['destiny' => 'navigations.index', 'module_id' => $moduleNavigation->id, 'name' => json_encode(['en' => 'Navigation', 'es' => 'Navegación']), 'type' => 'route', 'parent' => $settingsParent->id, 'permission_id' => $readNavigationsPermission->id, 'position' => 1],
], ['destiny', 'module_id'], ['name', 'type', 'parent', 'permission_id', 'position']);
}

// Files
if ($filesParent = Navigation::updateOrCreate(['destiny' => 'files.index', 'module_id' => $moduleFilemanager->id], ['name' => 'Files List', 'type' => 'route', 'parent' => 0, 'permission_id' => $readFilemanagerPermission->id, 'position' => 0])) {
// Spanish name update
$filesParent->setLocale('es');
$filesParent->name = 'Lista de Archivos';
$filesParent->save();
}
}
}
18 changes: 15 additions & 3 deletions src/Database/Seeders/PbSpatieSeeder.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ public function run()
$moduleNavigation = PbModule::whereModulekey('navigation')->first();
$moduleRole = PbModule::whereModulekey('role')->first();
$modulePermission = PbModule::whereModulekey('permission')->first();
$moduleFile = PbModule::where('modulekey', 'file')->first();

Permission::query()->delete();
Role::query()->delete();
Expand Down Expand Up @@ -76,12 +77,18 @@ public function run()
['guard_name' => 'admin', 'name' => 'create roles', 'alias' => json_encode(['en' => 'Create Roles', 'es' => 'Crear Roles']), 'module_id' => $moduleRole->id],
['guard_name' => 'admin', 'name' => 'read roles', 'alias' => json_encode(['en' => 'Read Roles', 'es' => 'Leer Roles']), 'module_id' => $moduleRole->id],
['guard_name' => 'admin', 'name' => 'update roles', 'alias' => json_encode(['en' => 'Update Roles', 'es' => 'Actualizar Roles']), 'module_id' => $moduleRole->id],
['guard_name' => 'admin', 'name' => 'delete roles', 'alias' => json_encode(['en' => 'Delete Roles', 'es' => 'Borrar Roles']), 'module_id' => $moduleRole->id]
['guard_name' => 'admin', 'name' => 'delete roles', 'alias' => json_encode(['en' => 'Delete Roles', 'es' => 'Borrar Roles']), 'module_id' => $moduleRole->id],
// CRUD Files
['guard_name' => 'admin', 'name' => 'config files', 'alias' => json_encode(['en' => 'Configure Files', 'es' => 'Configurar Archivos']), 'module_id' => $moduleFile->id],
['guard_name' => 'admin', 'name' => 'create files', 'alias' => json_encode(['en' => 'Create Files', 'es' => 'Crear Archivos']), 'module_id' => $moduleFile->id],
['guard_name' => 'admin', 'name' => 'read files', 'alias' => json_encode(['en' => 'Read Files', 'es' => 'Leer Archivos']), 'module_id' => $moduleFile->id],
['guard_name' => 'admin', 'name' => 'update files', 'alias' => json_encode(['en' => 'Update Files', 'es' => 'Actualizar Archivos']), 'module_id' => $moduleFile->id],
['guard_name' => 'admin', 'name' => 'delete files', 'alias' => json_encode(['en' => 'Delete Files', 'es' => 'Borrar Archivos']), 'module_id' => $moduleFile->id],
], ['guard_name', 'name'], ['alias', 'module_id']);

// updateOrCreate roles and assign updateOrCreated permissions
Role::updateOrCreate(['guard_name' => 'admin', 'name' => 'user'], ['guard_name' => 'admin', 'name' => 'user', 'alias' => ['en' => 'User', 'es' => 'Usuario']])
->givePermissionTo(['login']);
->givePermissionTo(['login', 'create files', 'read files', 'update files', 'delete files', 'config files']);
Role::updateOrCreate(['guard_name' => 'admin', 'name' => 'api-user'], ['guard_name' => 'admin', 'name' => 'api-user', 'alias' => ['en' => 'API User', 'es' => 'Usuario API']])
->givePermissionTo(['api access']);
Role::updateOrCreate(['guard_name' => 'admin', 'name' => 'admin'], ['guard_name' => 'admin', 'name' => 'admin', 'alias' => ['en' => 'Admin', 'es' => 'Administrador']])
Expand All @@ -99,9 +106,14 @@ public function run()
'config builder',
'login',
'clear cache',
'config files',
'create files',
'read files',
'update files',
'delete files',
]);
Role::updateOrCreate(['guard_name' => 'admin', 'name' => 'developer'], ['guard_name' => 'admin', 'name' => 'developer', 'alias' => ['en' => 'Developer', 'es' => 'Desarrollador']])
->givePermissionTo(['developer options', 'read loggers', 'delete loggers', 'config loggers', 'clear cache']);
->givePermissionTo(['developer options', 'read loggers', 'delete loggers', 'config loggers', 'clear cache', 'create files', 'read files', 'update files', 'delete files', 'config files']);
Role::updateOrCreate(['guard_name' => 'admin', 'name' => 'super-admin'], ['guard_name' => 'admin', 'name' => 'super-admin', 'alias' => ['en' => 'Super Admin', 'es' => 'Superadministrador']])
->givePermissionTo(Permission::all());
}
Expand Down
Loading

0 comments on commit c2bf41a

Please sign in to comment.