diff --git a/app.php b/app.php index 7ff895d1..7680c71c 100644 --- a/app.php +++ b/app.php @@ -67,7 +67,7 @@ if (!empty(GROCY_BASE_PATH)) $app->addRoutingMiddleware(); $errorMiddleware = $app->addErrorMiddleware(true, false, false); $errorMiddleware->setDefaultErrorHandler( - new \Grocy\Controllers\ExceptionController($app, $container) + new \Grocy\Controllers\ExceptionController($app, $container) ); $app->run(); diff --git a/controllers/BaseController.php b/controllers/BaseController.php index b82c22ba..8538fe6c 100644 --- a/controllers/BaseController.php +++ b/controllers/BaseController.php @@ -34,7 +34,7 @@ class BaseController $this->View->set('version', $versionInfo->Version); $this->View->set('releaseDate', $versionInfo->ReleaseDate); - $localizationService = $this->getLocalizationService(); + $localizationService = $this->getLocalizationService(); $this->View->set('__t', function(string $text, ...$placeholderValues) use($localizationService) { return $localizationService->__t($text, $placeholderValues); @@ -98,12 +98,12 @@ class BaseController return $this->render($response, $page, $data); } - protected function getDatabaseService() + protected function getDatabaseService() { return DatabaseService::getInstance(); } - protected function getDatabase() + protected function getDatabase() { return $this->getDatabaseService()->GetDbConnection(); } @@ -128,7 +128,7 @@ class BaseController return CalendarService::getInstance(); } - protected function getSessionService() + protected function getSessionService() { return SessionService::getInstance(); } @@ -143,12 +143,12 @@ class BaseController return StockService::getInstance(); } - protected function getTasksService() + protected function getTasksService() { return TasksService::getInstance(); } - protected function getUsersService() + protected function getUsersService() { return UsersService::getInstance(); } @@ -172,6 +172,6 @@ class BaseController { return FilesService::getInstance(); } - + protected $AppContainer; } diff --git a/controllers/BatteriesApiController.php b/controllers/BatteriesApiController.php index 271e6ed2..9464a3d7 100644 --- a/controllers/BatteriesApiController.php +++ b/controllers/BatteriesApiController.php @@ -13,9 +13,9 @@ class BatteriesApiController extends BaseApiController public function TrackChargeCycle(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - User::checkPermission($request, User::PERMISSION_BATTERY_TRACK_CHARGE_CYCLE); + User::checkPermission($request, User::PERMISSION_BATTERY_TRACK_CHARGE_CYCLE); - $requestBody = $request->getParsedBody(); + $requestBody = $request->getParsedBody(); try { @@ -53,9 +53,9 @@ class BatteriesApiController extends BaseApiController public function UndoChargeCycle(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - User::checkPermission($request, User::PERMISSION_BATTERY_UNDO_TRACK_CHARGE_CYCLE); + User::checkPermission($request, User::PERMISSION_BATTERY_UNDO_TRACK_CHARGE_CYCLE); - try + try { $this->ApiResponse($response, $this->getBatteriesService()->UndoChargeCycle($args['chargeCycleId'])); return $this->EmptyApiResponse($response); diff --git a/controllers/ChoresApiController.php b/controllers/ChoresApiController.php index b118e31d..d276b3e0 100644 --- a/controllers/ChoresApiController.php +++ b/controllers/ChoresApiController.php @@ -17,9 +17,9 @@ class ChoresApiController extends BaseApiController try { - User::checkPermission($request, User::PERMISSION_CHORE_TRACK); + User::checkPermission($request, User::PERMISSION_CHORE_TRACK); - $trackedTime = date('Y-m-d H:i:s'); + $trackedTime = date('Y-m-d H:i:s'); if (array_key_exists('tracked_time', $requestBody) && (IsIsoDateTime($requestBody['tracked_time']) || IsIsoDate($requestBody['tracked_time']))) { $trackedTime = $requestBody['tracked_time']; @@ -31,7 +31,7 @@ class ChoresApiController extends BaseApiController $doneBy = $requestBody['done_by']; } if($doneBy != GROCY_USER_ID) - User::checkPermission($request, User::PERMISSION_CHORE_TRACK_OTHERS); + User::checkPermission($request, User::PERMISSION_CHORE_TRACK_OTHERS); $choreExecutionId = $this->getChoresService()->TrackChore($args['choreId'], $trackedTime, $doneBy); return $this->ApiResponse($response, $this->getDatabase()->chores_log($choreExecutionId)); @@ -63,9 +63,9 @@ class ChoresApiController extends BaseApiController { try { - User::checkPermission($request, User::PERMISSION_CHORE_UNDO); + User::checkPermission($request, User::PERMISSION_CHORE_UNDO); - $this->ApiResponse($response, $this->getChoresService()->UndoChoreExecution($args['executionId'])); + $this->ApiResponse($response, $this->getChoresService()->UndoChoreExecution($args['executionId'])); return $this->EmptyApiResponse($response); } catch (\Exception $ex) @@ -78,9 +78,9 @@ class ChoresApiController extends BaseApiController { try { - User::checkPermission($request, User::PERMISSION_CHORE_EDIT); + User::checkPermission($request, User::PERMISSION_CHORE_EDIT); - $requestBody = $request->getParsedBody(); + $requestBody = $request->getParsedBody(); $choreId = null; if (array_key_exists('chore_id', $requestBody) && !empty($requestBody['chore_id']) && is_numeric($requestBody['chore_id'])) diff --git a/controllers/ExceptionController.php b/controllers/ExceptionController.php index 0cd6b99a..c681d98e 100644 --- a/controllers/ExceptionController.php +++ b/controllers/ExceptionController.php @@ -1,6 +1,5 @@ app = $app; - } + public function __construct(\Slim\App $app, \DI\Container $container) + { + parent::__construct($container); + $this->app = $app; + } - public function __invoke(ServerRequestInterface $request, - Throwable $exception, - bool $displayErrorDetails, - bool $logErrors, - bool $logErrorDetails, - ?LoggerInterface $logger = null) - { - $response = $this->app->getResponseFactory()->createResponse(); + public function __invoke(ServerRequestInterface $request, + Throwable $exception, + bool $displayErrorDetails, + bool $logErrors, + bool $logErrorDetails, + ?LoggerInterface $logger = null) + { + $response = $this->app->getResponseFactory()->createResponse(); - $isApiRoute = string_starts_with($request->getUri()->getPath(), '/api/'); - if ($isApiRoute) { - $status = 500; - if ($exception instanceof HttpException) { - $status = $exception->getCode(); - } - $data = [ - 'error_message' => $exception->getMessage(), - ]; - if ($displayErrorDetails) { - $data['error_details'] = [ - 'stack_trace' => $exception->getTraceAsString(), - 'file' => $exception->getFile(), - 'line' => $exception->getLine(), - ]; - } - return $this->ApiResponse($response->withStatus($status), $data); - } - if ($exception instanceof HttpNotFoundException) { - return $this->renderPage($response->withStatus(404), 'errors/404', [ - 'exception' => $exception - ]); - } - if ($exception instanceof HttpForbiddenException) { - return $this->renderPage($response->withStatus(403), 'errors/403', [ - 'exception' => $exception - ]); - } + $isApiRoute = string_starts_with($request->getUri()->getPath(), '/api/'); + if ($isApiRoute) { + $status = 500; + if ($exception instanceof HttpException) { + $status = $exception->getCode(); + } + $data = [ + 'error_message' => $exception->getMessage(), + ]; + if ($displayErrorDetails) { + $data['error_details'] = [ + 'stack_trace' => $exception->getTraceAsString(), + 'file' => $exception->getFile(), + 'line' => $exception->getLine(), + ]; + } + return $this->ApiResponse($response->withStatus($status), $data); + } + if ($exception instanceof HttpNotFoundException) { + return $this->renderPage($response->withStatus(404), 'errors/404', [ + 'exception' => $exception + ]); + } + if ($exception instanceof HttpForbiddenException) { + return $this->renderPage($response->withStatus(403), 'errors/403', [ + 'exception' => $exception + ]); + } - return $this->renderPage($response->withStatus(500), 'errors/500', [ - 'exception' => $exception - ]); + return $this->renderPage($response->withStatus(500), 'errors/500', [ + 'exception' => $exception + ]); - } + } } diff --git a/controllers/FilesApiController.php b/controllers/FilesApiController.php index 56847204..1ae1f8d0 100644 --- a/controllers/FilesApiController.php +++ b/controllers/FilesApiController.php @@ -16,9 +16,9 @@ class FilesApiController extends BaseApiController { try { - User::checkPermission($request, User::PERMISSION_UPLOAD_FILE); + User::checkPermission($request, User::PERMISSION_UPLOAD_FILE); - if (IsValidFileName(base64_decode($args['fileName']))) + if (IsValidFileName(base64_decode($args['fileName']))) { $fileName = base64_decode($args['fileName']); } @@ -100,9 +100,9 @@ class FilesApiController extends BaseApiController { try { - User::checkPermission($request, User::PERMISSION_DELETE_FILE); + User::checkPermission($request, User::PERMISSION_DELETE_FILE); - if (IsValidFileName(base64_decode($args['fileName']))) + if (IsValidFileName(base64_decode($args['fileName']))) { $fileName = base64_decode($args['fileName']); } diff --git a/controllers/GenericEntityApiController.php b/controllers/GenericEntityApiController.php index 28d7e8f6..cd1917b9 100644 --- a/controllers/GenericEntityApiController.php +++ b/controllers/GenericEntityApiController.php @@ -13,7 +13,7 @@ class GenericEntityApiController extends BaseApiController public function GetObjects(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - $objects = $this->getDatabase()->{$args['entity']}(); + $objects = $this->getDatabase()->{$args['entity']}(); $allUserfields = $this->getUserfieldsService()->GetAllValues($args['entity']); foreach ($objects as $object) @@ -43,7 +43,7 @@ class GenericEntityApiController extends BaseApiController public function GetObject(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - if ($this->IsValidEntity($args['entity']) && !$this->IsEntityWithPreventedListing($args['entity'])) + if ($this->IsValidEntity($args['entity']) && !$this->IsEntityWithPreventedListing($args['entity'])) { $userfields = $this->getUserfieldsService()->GetValues($args['entity'], $args['objectId']); if (count($userfields) === 0) @@ -52,9 +52,9 @@ class GenericEntityApiController extends BaseApiController } $object = $this->getDatabase()->{$args['entity']}($args['objectId']); - if ($object == null) { - return $this->GenericErrorResponse($response, 'Object not found', 404); - } + if ($object == null) { + return $this->GenericErrorResponse($response, 'Object not found', 404); + } $object['userfields'] = $userfields; @@ -68,9 +68,9 @@ class GenericEntityApiController extends BaseApiController public function AddObject(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - User::checkPermission($request, User::PERMISSION_MASTER_DATA_EDIT); + User::checkPermission($request, User::PERMISSION_MASTER_DATA_EDIT); - if ($this->IsValidEntity($args['entity'])) + if ($this->IsValidEntity($args['entity'])) { $requestBody = $request->getParsedBody(); @@ -101,9 +101,9 @@ class GenericEntityApiController extends BaseApiController public function EditObject(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - User::checkPermission($request, User::PERMISSION_MASTER_DATA_EDIT); + User::checkPermission($request, User::PERMISSION_MASTER_DATA_EDIT); - if ($this->IsValidEntity($args['entity'])) + if ($this->IsValidEntity($args['entity'])) { $requestBody = $request->getParsedBody(); @@ -132,9 +132,9 @@ class GenericEntityApiController extends BaseApiController public function DeleteObject(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - User::checkPermission($request, User::PERMISSION_MASTER_DATA_EDIT); + User::checkPermission($request, User::PERMISSION_MASTER_DATA_EDIT); - if ($this->IsValidEntity($args['entity'])) + if ($this->IsValidEntity($args['entity'])) { $row = $this->getDatabase()->{$args['entity']}($args['objectId']); $row->delete(); @@ -150,7 +150,7 @@ class GenericEntityApiController extends BaseApiController public function SearchObjects(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - if ($this->IsValidEntity($args['entity']) && !$this->IsEntityWithPreventedListing($args['entity'])) + if ($this->IsValidEntity($args['entity']) && !$this->IsEntityWithPreventedListing($args['entity'])) { try { @@ -169,7 +169,7 @@ class GenericEntityApiController extends BaseApiController public function GetUserfields(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - try + try { return $this->ApiResponse($response, $this->getUserfieldsService()->GetValues($args['entity'], $args['objectId'])); } @@ -181,9 +181,9 @@ class GenericEntityApiController extends BaseApiController public function SetUserfields(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - User::checkPermission($request, User::PERMISSION_MASTER_DATA_EDIT); + User::checkPermission($request, User::PERMISSION_MASTER_DATA_EDIT); - $requestBody = $request->getParsedBody(); + $requestBody = $request->getParsedBody(); try { diff --git a/controllers/RecipesApiController.php b/controllers/RecipesApiController.php index 02903efa..58eb8902 100644 --- a/controllers/RecipesApiController.php +++ b/controllers/RecipesApiController.php @@ -13,9 +13,9 @@ class RecipesApiController extends BaseApiController public function AddNotFulfilledProductsToShoppingList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - User::checkPermission($request, User::PERMISSION_SHOPPINGLIST_ITEMS_ADD); + User::checkPermission($request, User::PERMISSION_SHOPPINGLIST_ITEMS_ADD); - $requestBody = $request->getParsedBody(); + $requestBody = $request->getParsedBody(); $excludedProductIds = null; if ($requestBody !== null && array_key_exists('excludedProductIds', $requestBody)) @@ -29,9 +29,9 @@ class RecipesApiController extends BaseApiController public function ConsumeRecipe(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - User::checkPermission($request, User::PERMISSION_PRODUCT_CONSUME); + User::checkPermission($request, User::PERMISSION_PRODUCT_CONSUME); - try + try { $this->getRecipesService()->ConsumeRecipe($args['recipeId']); return $this->EmptyApiResponse($response); diff --git a/controllers/RecipesController.php b/controllers/RecipesController.php index 5e2a7540..ffacbf82 100644 --- a/controllers/RecipesController.php +++ b/controllers/RecipesController.php @@ -51,7 +51,7 @@ class RecipesController extends BaseController if ($selectedRecipe) { $selectedRecipeSubRecipes = $this->getDatabase()->recipes()->where('id IN (SELECT includes_recipe_id FROM recipes_nestings_resolved WHERE recipe_id = :1 AND includes_recipe_id != :1)', $selectedRecipe->id)->orderBy('name')->fetchAll(); - + $includedRecipeIdsAbsolute = array(); $includedRecipeIdsAbsolute[] = $selectedRecipe->id; foreach($selectedRecipeSubRecipes as $subRecipe) diff --git a/controllers/StockApiController.php b/controllers/StockApiController.php index bc2e5aa7..2c3a4174 100644 --- a/controllers/StockApiController.php +++ b/controllers/StockApiController.php @@ -63,9 +63,9 @@ class StockApiController extends BaseApiController public function AddProduct(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - User::checkPermission($request, User::PERMISSION_PRODUCT_PURCHASE); + User::checkPermission($request, User::PERMISSION_PRODUCT_PURCHASE); - $requestBody = $request->getParsedBody(); + $requestBody = $request->getParsedBody(); try { @@ -139,9 +139,9 @@ class StockApiController extends BaseApiController public function EditStockEntry(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - User::checkPermission($request, User::PERMISSION_STOCK_EDIT); + User::checkPermission($request, User::PERMISSION_STOCK_EDIT); - $requestBody = $request->getParsedBody(); + $requestBody = $request->getParsedBody(); try { @@ -190,9 +190,9 @@ class StockApiController extends BaseApiController public function TransferProduct(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - User::checkPermission($request, User::PERMISSION_STOCK_TRANSFER); + User::checkPermission($request, User::PERMISSION_STOCK_TRANSFER); - $requestBody = $request->getParsedBody(); + $requestBody = $request->getParsedBody(); try { @@ -246,9 +246,9 @@ class StockApiController extends BaseApiController public function ConsumeProduct(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - User::checkPermission($request, User::PERMISSION_PRODUCT_CONSUME); + User::checkPermission($request, User::PERMISSION_PRODUCT_CONSUME); - $requestBody = $request->getParsedBody(); + $requestBody = $request->getParsedBody(); $result = null; @@ -319,9 +319,9 @@ class StockApiController extends BaseApiController public function InventoryProduct(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - User::checkPermission($request, User::PERMISSION_STOCK_CORRECTION); + User::checkPermission($request, User::PERMISSION_STOCK_CORRECTION); - $requestBody = $request->getParsedBody(); + $requestBody = $request->getParsedBody(); try { @@ -383,9 +383,9 @@ class StockApiController extends BaseApiController public function OpenProduct(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - User::checkPermission($request, User::PERMISSION_PRODUCT_OPEN); + User::checkPermission($request, User::PERMISSION_PRODUCT_OPEN); - $requestBody = $request->getParsedBody(); + $requestBody = $request->getParsedBody(); try { @@ -452,9 +452,9 @@ class StockApiController extends BaseApiController public function AddMissingProductsToShoppingList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - User::checkPermission($request, User::PERMISSION_SHOPPINGLIST_ITEMS_ADD); + User::checkPermission($request, User::PERMISSION_SHOPPINGLIST_ITEMS_ADD); - try + try { $requestBody = $request->getParsedBody(); @@ -475,9 +475,9 @@ class StockApiController extends BaseApiController public function ClearShoppingList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - User::checkPermission($request, User::PERMISSION_SHOPPINGLIST_ITEMS_DELETE); + User::checkPermission($request, User::PERMISSION_SHOPPINGLIST_ITEMS_DELETE); - try + try { $requestBody = $request->getParsedBody(); @@ -499,9 +499,9 @@ class StockApiController extends BaseApiController public function AddProductToShoppingList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - User::checkPermission($request, User::PERMISSION_SHOPPINGLIST_ITEMS_ADD); + User::checkPermission($request, User::PERMISSION_SHOPPINGLIST_ITEMS_ADD); - try + try { $requestBody = $request->getParsedBody(); @@ -542,9 +542,9 @@ class StockApiController extends BaseApiController public function RemoveProductFromShoppingList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - User::checkPermission($request, User::PERMISSION_SHOPPINGLIST_ITEMS_DELETE); + User::checkPermission($request, User::PERMISSION_SHOPPINGLIST_ITEMS_DELETE); - try + try { $requestBody = $request->getParsedBody(); @@ -580,16 +580,16 @@ class StockApiController extends BaseApiController public function ExternalBarcodeLookup(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - User::checkPermission($request, User::PERMISSION_MASTER_DATA_EDIT); + User::checkPermission($request, User::PERMISSION_MASTER_DATA_EDIT); - try + try { $addFoundProduct = false; if (isset($request->getQueryParams()['add']) && ($request->getQueryParams()['add'] === 'true' || $request->getQueryParams()['add'] === 1)) { $addFoundProduct = true; } - + return $this->ApiResponse($response, $this->getStockService()->ExternalBarcodeLookup($args['barcode'], $addFoundProduct)); } catch (\Exception $ex) @@ -600,9 +600,9 @@ class StockApiController extends BaseApiController public function UndoBooking(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - User::checkPermission($request, User::PERMISSION_STOCK_CORRECTION); + User::checkPermission($request, User::PERMISSION_STOCK_CORRECTION); - try + try { $this->ApiResponse($response, $this->getStockService()->UndoBooking($args['bookingId'])); return $this->EmptyApiResponse($response); @@ -615,9 +615,9 @@ class StockApiController extends BaseApiController public function UndoTransaction(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - User::checkPermission($request, User::PERMISSION_STOCK_CORRECTION); + User::checkPermission($request, User::PERMISSION_STOCK_CORRECTION); - try + try { $this->ApiResponse($response, $this->getStockService()->UndoTransaction($args['transactionId'])); return $this->EmptyApiResponse($response); @@ -659,7 +659,7 @@ class StockApiController extends BaseApiController { throw new \Exception('Stock booking does not exist'); } - + return $this->ApiResponse($response, $stockLogRow); } catch (\Exception $ex) @@ -678,7 +678,7 @@ class StockApiController extends BaseApiController { throw new \Exception('No transaction was found by the given transaction id'); } - + return $this->ApiResponse($response, $transactionRows); } catch (\Exception $ex) diff --git a/controllers/StockController.php b/controllers/StockController.php index ab88ffaa..a6327c62 100644 --- a/controllers/StockController.php +++ b/controllers/StockController.php @@ -16,7 +16,7 @@ class StockController extends BaseController $nextXDays = $usersService->GetUserSettings(GROCY_USER_ID)['stock_expring_soon_days']; return $this->renderPage($response, 'stockoverview', [ - 'currentStock' => $this->getStockService()->GetCurrentStockOverview(), + 'currentStock' => $this->getStockService()->GetCurrentStockOverview(), 'locations' => $this->getDatabase()->locations()->orderBy('name'), 'currentStockLocations' => $this->getStockService()->GetCurrentStockLocations(), 'nextXDays' => $nextXDays, diff --git a/controllers/SystemApiController.php b/controllers/SystemApiController.php index a28634d8..50cc2160 100644 --- a/controllers/SystemApiController.php +++ b/controllers/SystemApiController.php @@ -11,9 +11,9 @@ class SystemApiController extends BaseApiController public function GetDbChangedTime(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - return $this->ApiResponse($response, array( - 'changed_time' => $this->getDatabaseService()->GetDbChangedTime() - )); + return $this->ApiResponse($response, array( + 'changed_time' => $this->getDatabaseService()->GetDbChangedTime() + )); } public function GetConfig(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) diff --git a/controllers/TasksApiController.php b/controllers/TasksApiController.php index 657a5cd6..5fab39f1 100644 --- a/controllers/TasksApiController.php +++ b/controllers/TasksApiController.php @@ -18,9 +18,9 @@ class TasksApiController extends BaseApiController public function MarkTaskAsCompleted(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - User::checkPermission($request, User::PERMISSION_TASKS_MARK_COMPLETED); + User::checkPermission($request, User::PERMISSION_TASKS_MARK_COMPLETED); - $requestBody = $request->getParsedBody(); + $requestBody = $request->getParsedBody(); try { @@ -41,9 +41,9 @@ class TasksApiController extends BaseApiController public function UndoTask(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - User::checkPermission($request, User::PERMISSION_TASKS_UNDO); + User::checkPermission($request, User::PERMISSION_TASKS_UNDO); - try + try { $this->getTasksService()->UndoTask($args['taskId']); return $this->EmptyApiResponse($response); diff --git a/controllers/Users/PermissionMissingException.php b/controllers/Users/PermissionMissingException.php index 5bbc616e..690e5db1 100644 --- a/controllers/Users/PermissionMissingException.php +++ b/controllers/Users/PermissionMissingException.php @@ -8,8 +8,8 @@ use Throwable; class PermissionMissingException extends HttpForbiddenException { - public function __construct(ServerRequestInterface $request, string $permission, ?Throwable $previous = null) - { - parent::__construct($request, 'Permission missing: ' . $permission, $previous); - } -} \ No newline at end of file + public function __construct(ServerRequestInterface $request, string $permission, ?Throwable $previous = null) + { + parent::__construct($request, 'Permission missing: ' . $permission, $previous); + } +} diff --git a/controllers/Users/User.php b/controllers/Users/User.php index ca285a6c..92b5e6bc 100644 --- a/controllers/Users/User.php +++ b/controllers/Users/User.php @@ -7,85 +7,85 @@ use LessQL\Result; class User { - const PERMISSION_ADMIN = 'ADMIN'; - const PERMISSION_CREATE_USER = 'CREATE_USER'; - const PERMISSION_EDIT_USER = 'EDIT_USER'; - const PERMISSION_READ_USER = 'READ_USER'; - const PERMISSION_EDIT_SELF = 'EDIT_SELF'; - const PERMISSION_BATTERY_UNDO_TRACK_CHARGE_CYCLE = 'BATTERY_UNDO_TRACK_CHARGE_CYCLE'; - const PERMISSION_BATTERY_TRACK_CHARGE_CYCLE = 'BATTERY_TRACK_CHARGE_CYCLE'; - const PERMISSION_CHORE_TRACK = 'CHORE_TRACK'; - const PERMISSION_CHORE_TRACK_OTHERS = 'CHORE_TRACK_OTHERS'; - const PERMISSION_CHORE_EDIT = 'CHORE_EDIT'; - const PERMISSION_CHORE_UNDO = 'CHORE_UNDO'; - const PERMISSION_UPLOAD_FILE = 'UPLOAD_FILE'; - const PERMISSION_DELETE_FILE = 'DELETE_FILE'; - const PERMISSION_MASTER_DATA_EDIT = 'MASTER_DATA_EDIT'; - const PERMISSION_TASKS_UNDO = 'TASKS_UNDO'; - const PERMISSION_TASKS_MARK_COMPLETED = 'TASKS_MARK_COMPLETED'; - const PERMISSION_STOCK_TRANSFER = 'STOCK_TRANSFER'; - const PERMISSION_STOCK_EDIT = 'STOCK_EDIT'; - const PERMISSION_PRODUCT_CONSUME = 'PRODUCT_CONSUME'; - const PERMISSION_STOCK_CORRECTION = 'STOCK_CORRECTION'; - const PERMISSION_PRODUCT_OPEN = 'PRODUCT_OPEN'; - const PERMISSION_SHOPPINGLIST_ITEMS_ADD = 'SHOPPINGLIST_ITEMS_ADD'; - const PERMISSION_SHOPPINGLIST_ITEMS_DELETE = 'SHOPPINGLIST_ITEMS_DELETE'; - const PERMISSION_PRODUCT_PURCHASE = 'PRODUCT_PURCHASE'; + const PERMISSION_ADMIN = 'ADMIN'; + const PERMISSION_CREATE_USER = 'CREATE_USER'; + const PERMISSION_EDIT_USER = 'EDIT_USER'; + const PERMISSION_READ_USER = 'READ_USER'; + const PERMISSION_EDIT_SELF = 'EDIT_SELF'; + const PERMISSION_BATTERY_UNDO_TRACK_CHARGE_CYCLE = 'BATTERY_UNDO_TRACK_CHARGE_CYCLE'; + const PERMISSION_BATTERY_TRACK_CHARGE_CYCLE = 'BATTERY_TRACK_CHARGE_CYCLE'; + const PERMISSION_CHORE_TRACK = 'CHORE_TRACK'; + const PERMISSION_CHORE_TRACK_OTHERS = 'CHORE_TRACK_OTHERS'; + const PERMISSION_CHORE_EDIT = 'CHORE_EDIT'; + const PERMISSION_CHORE_UNDO = 'CHORE_UNDO'; + const PERMISSION_UPLOAD_FILE = 'UPLOAD_FILE'; + const PERMISSION_DELETE_FILE = 'DELETE_FILE'; + const PERMISSION_MASTER_DATA_EDIT = 'MASTER_DATA_EDIT'; + const PERMISSION_TASKS_UNDO = 'TASKS_UNDO'; + const PERMISSION_TASKS_MARK_COMPLETED = 'TASKS_MARK_COMPLETED'; + const PERMISSION_STOCK_TRANSFER = 'STOCK_TRANSFER'; + const PERMISSION_STOCK_EDIT = 'STOCK_EDIT'; + const PERMISSION_PRODUCT_CONSUME = 'PRODUCT_CONSUME'; + const PERMISSION_STOCK_CORRECTION = 'STOCK_CORRECTION'; + const PERMISSION_PRODUCT_OPEN = 'PRODUCT_OPEN'; + const PERMISSION_SHOPPINGLIST_ITEMS_ADD = 'SHOPPINGLIST_ITEMS_ADD'; + const PERMISSION_SHOPPINGLIST_ITEMS_DELETE = 'SHOPPINGLIST_ITEMS_DELETE'; + const PERMISSION_PRODUCT_PURCHASE = 'PRODUCT_PURCHASE'; - /** - * @var \LessQL\Database|null - */ - protected $db; + /** + * @var \LessQL\Database|null + */ + protected $db; - public function __construct() - { - $this->db = DatabaseService::getInstance()->GetDbConnection(); + public function __construct() + { + $this->db = DatabaseService::getInstance()->GetDbConnection(); - } + } - protected function getPermissions(): Result - { - return $this->db->user_permissions_resolved()->where('user_id', GROCY_USER_ID); - } + protected function getPermissions(): Result + { + return $this->db->user_permissions_resolved()->where('user_id', GROCY_USER_ID); + } - public function hasPermission(string $permission): bool - { - // global $PERMISSION_CACHE; - // if(isset($PERMISSION_CACHE[$permission])) - // return $PERMISSION_CACHE[$permission]; - return $this->getPermissions()->where('permission_name', $permission)->fetch() !== null; - } + public function hasPermission(string $permission): bool + { + // global $PERMISSION_CACHE; + // if(isset($PERMISSION_CACHE[$permission])) + // return $PERMISSION_CACHE[$permission]; + return $this->getPermissions()->where('permission_name', $permission)->fetch() !== null; + } - public static function checkPermission($request, string ...$permissions): void - { - $user = new User(); - foreach ($permissions as $permission) { - if (!$user->hasPermission($permission)) { - throw new PermissionMissingException($request, $permission); - } - } + public static function checkPermission($request, string ...$permissions): void + { + $user = new User(); + foreach ($permissions as $permission) { + if (!$user->hasPermission($permission)) { + throw new PermissionMissingException($request, $permission); + } + } - } + } - public function getPermissionList() - { - return $this->db->uihelper_user_permissions()->where('user_id', GROCY_USER_ID); - } + public function getPermissionList() + { + return $this->db->uihelper_user_permissions()->where('user_id', GROCY_USER_ID); + } - public static function hasPermissions(string ...$permissions) - { - $user = new User(); - foreach ($permissions as $permission) { - if (!$user->hasPermission($permission)) { - return false; - } - } - return true; - } + public static function hasPermissions(string ...$permissions) + { + $user = new User(); + foreach ($permissions as $permission) { + if (!$user->hasPermission($permission)) { + return false; + } + } + return true; + } - public static function PermissionList() - { - $user = new User(); - return $user->getPermissionList(); - } + public static function PermissionList() + { + $user = new User(); + return $user->getPermissionList(); + } } diff --git a/controllers/UsersApiController.php b/controllers/UsersApiController.php index 20f4a00b..f19d5776 100644 --- a/controllers/UsersApiController.php +++ b/controllers/UsersApiController.php @@ -13,8 +13,8 @@ class UsersApiController extends BaseApiController public function GetUsers(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - User::checkPermission($request, User::PERMISSION_READ_USER); - try + User::checkPermission($request, User::PERMISSION_READ_USER); + try { return $this->ApiResponse($response, $this->getUsersService()->GetUsersAsDto()); } @@ -26,7 +26,7 @@ class UsersApiController extends BaseApiController public function CreateUser(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - User::checkPermission($request, User::PERMISSION_CREATE_USER); + User::checkPermission($request, User::PERMISSION_CREATE_USER); $requestBody = $request->getParsedBody(); try @@ -47,8 +47,8 @@ class UsersApiController extends BaseApiController public function DeleteUser(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - User::checkPermission($request, User::PERMISSION_EDIT_USER); - try + User::checkPermission($request, User::PERMISSION_EDIT_USER); + try { $this->getUsersService()->DeleteUser($args['userId']); return $this->EmptyApiResponse($response); @@ -61,12 +61,12 @@ class UsersApiController extends BaseApiController public function EditUser(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - if ($args['userId'] == GROCY_USER_ID) { - User::checkPermission($request, User::PERMISSION_EDIT_SELF); - } else { - User::checkPermission($request, User::PERMISSION_EDIT_USER); - } - $requestBody = $request->getParsedBody(); + if ($args['userId'] == GROCY_USER_ID) { + User::checkPermission($request, User::PERMISSION_EDIT_SELF); + } else { + User::checkPermission($request, User::PERMISSION_EDIT_USER); + } + $requestBody = $request->getParsedBody(); try { @@ -119,65 +119,65 @@ class UsersApiController extends BaseApiController } } - public function AddPermission(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) - { - try { - User::checkPermission($request, User::PERMISSION_ADMIN); - $requestBody = $request->getParsedBody(); + public function AddPermission(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) + { + try { + User::checkPermission($request, User::PERMISSION_ADMIN); + $requestBody = $request->getParsedBody(); - $this->getDatabase()->user_permissions()->createRow(array( - 'user_id' => $args['userId'], - 'permission_id' => $requestBody['permission_id'], - ))->save(); - return $this->EmptyApiResponse($response); - } catch (\Slim\Exception\HttpSpecializedException $ex) { - return $this->GenericErrorResponse($response, $ex->getMessage(), $ex->getCode()); - } catch (\Exception $ex) { - return $this->GenericErrorResponse($response, $ex->getMessage()); - } - } + $this->getDatabase()->user_permissions()->createRow(array( + 'user_id' => $args['userId'], + 'permission_id' => $requestBody['permission_id'], + ))->save(); + return $this->EmptyApiResponse($response); + } catch (\Slim\Exception\HttpSpecializedException $ex) { + return $this->GenericErrorResponse($response, $ex->getMessage(), $ex->getCode()); + } catch (\Exception $ex) { + return $this->GenericErrorResponse($response, $ex->getMessage()); + } + } - public function ListPermissions(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) - { - try { - User::checkPermission($request, User::PERMISSION_ADMIN); + public function ListPermissions(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) + { + try { + User::checkPermission($request, User::PERMISSION_ADMIN); - return $this->ApiResponse($response, - $this->getDatabase()->user_permissions()->where($args['userId']) - ); - } catch (\Slim\Exception\HttpSpecializedException $ex) { - return $this->GenericErrorResponse($response, $ex->getMessage(), $ex->getCode()); - } catch (\Exception $ex) { - return $this->GenericErrorResponse($response, $ex->getMessage()); - } - } + return $this->ApiResponse($response, + $this->getDatabase()->user_permissions()->where($args['userId']) + ); + } catch (\Slim\Exception\HttpSpecializedException $ex) { + return $this->GenericErrorResponse($response, $ex->getMessage(), $ex->getCode()); + } catch (\Exception $ex) { + return $this->GenericErrorResponse($response, $ex->getMessage()); + } + } - public function SetPermissions(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) - { - try { - User::checkPermission($request, User::PERMISSION_ADMIN); - $requestBody = $request->getParsedBody(); - $db = $this->getDatabase(); - $db->user_permissions() - ->where('user_id', $args['userId']) - ->delete(); + public function SetPermissions(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) + { + try { + User::checkPermission($request, User::PERMISSION_ADMIN); + $requestBody = $request->getParsedBody(); + $db = $this->getDatabase(); + $db->user_permissions() + ->where('user_id', $args['userId']) + ->delete(); - $perms = []; + $perms = []; - foreach ($requestBody['permissions'] as $perm_id) { - $perms[] = array( - 'user_id' => $args['userId'], - 'permission_id' => $perm_id - ); - } + foreach ($requestBody['permissions'] as $perm_id) { + $perms[] = array( + 'user_id' => $args['userId'], + 'permission_id' => $perm_id + ); + } - $db->insert('user_permissions', $perms, 'batch'); + $db->insert('user_permissions', $perms, 'batch'); - return $this->EmptyApiResponse($response); - } catch (\Slim\Exception\HttpSpecializedException $ex) { - return $this->GenericErrorResponse($response, $ex->getMessage(), $ex->getCode()); - } catch (\Exception $ex) { - return $this->GenericErrorResponse($response, $ex->getMessage()); - } - } + return $this->EmptyApiResponse($response); + } catch (\Slim\Exception\HttpSpecializedException $ex) { + return $this->GenericErrorResponse($response, $ex->getMessage(), $ex->getCode()); + } catch (\Exception $ex) { + return $this->GenericErrorResponse($response, $ex->getMessage()); + } + } } diff --git a/controllers/UsersController.php b/controllers/UsersController.php index 5ebc38fa..f911aec1 100644 --- a/controllers/UsersController.php +++ b/controllers/UsersController.php @@ -8,8 +8,8 @@ class UsersController extends BaseController { public function UsersList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) { - User::checkPermission($request, User::PERMISSION_READ_USER); - return $this->renderPage($response, 'users', [ + User::checkPermission($request, User::PERMISSION_READ_USER); + return $this->renderPage($response, 'users', [ 'users' => $this->getDatabase()->users()->orderBy('username') ]); } @@ -18,30 +18,30 @@ class UsersController extends BaseController { if ($args['userId'] == 'new') { - User::checkPermission($request, User::PERMISSION_CREATE_USER); - return $this->renderPage($response, 'userform', [ + User::checkPermission($request, User::PERMISSION_CREATE_USER); + return $this->renderPage($response, 'userform', [ 'mode' => 'create' ]); } else { - if($args['userId'] == GROCY_USER_ID) - User::checkPermission($request, User::PERMISSION_EDIT_SELF); - else User::checkPermission($request, User::PERMISSION_EDIT_USER); - return $this->renderPage($response, 'userform', [ + if($args['userId'] == GROCY_USER_ID) + User::checkPermission($request, User::PERMISSION_EDIT_SELF); + else User::checkPermission($request, User::PERMISSION_EDIT_USER); + return $this->renderPage($response, 'userform', [ 'user' => $this->getDatabase()->users($args['userId']), 'mode' => 'edit' ]); } } - public function PermissionList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) - { - User::checkPermission($request, User::PERMISSION_READ_USER); - return $this->renderPage($response, 'userpermissions', [ - 'user' => $this->getDatabase()->users($args['userId']), - 'permissions' => $this->getDatabase()->uihelper_user_permissions() - ->where('parent IS NULL')->where('user_id', $args['userId']), - ]); - } + public function PermissionList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) + { + User::checkPermission($request, User::PERMISSION_READ_USER); + return $this->renderPage($response, 'userpermissions', [ + 'user' => $this->getDatabase()->users($args['userId']), + 'permissions' => $this->getDatabase()->uihelper_user_permissions() + ->where('parent IS NULL')->where('user_id', $args['userId']), + ]); + } } diff --git a/helpers/PrerequisiteChecker.php b/helpers/PrerequisiteChecker.php index 66701d04..16c01e24 100644 --- a/helpers/PrerequisiteChecker.php +++ b/helpers/PrerequisiteChecker.php @@ -7,61 +7,61 @@ const REQUIRED_SQLITE_VERSION = "3.8.3"; class PrerequisiteChecker { - public function checkRequirements() - { - self::checkForConfigFile(); - self::checkForConfigDistFile(); - self::checkForComposer(); - self::checkForPhpExtensions(); - self::checkForSqliteVersion(); - } - - - private function checkForConfigFile() - { - if (!file_exists(GROCY_DATAPATH . '/config.php')) - { - throw new ERequirementNotMet('config.php in data directory (' . GROCY_DATAPATH . ') not found. Have you copied config-dist.php to the data directory and renamed it to config.php?'); - } - } - - private function checkForConfigDistFile() - { - if (!file_exists(__DIR__ . '/../config-dist.php')) - { - throw new ERequirementNotMet('config-dist.php not found. Please do not remove this file.'); - } - } - - private function checkForComposer() - { - if (!file_exists(__DIR__ . '/../vendor/autoload.php')) - { - throw new ERequirementNotMet('/vendor/autoload.php not found. Have you run Composer?'); - } - } - - private function checkForPhpExtensions() - { - $loadedExtensions = get_loaded_extensions(); - foreach (REQUIRED_PHP_EXTENSIONS as $extension) - { - if (!in_array($extension, $loadedExtensions)) - { - throw new ERequirementNotMet("PHP module '{$extension}' not installed, but required."); - } - } - } + public function checkRequirements() + { + self::checkForConfigFile(); + self::checkForConfigDistFile(); + self::checkForComposer(); + self::checkForPhpExtensions(); + self::checkForSqliteVersion(); + } - private function checkForSqliteVersion() - { - $sqliteVersion = self::getSqlVersionAsString(); - if (version_compare($sqliteVersion, REQUIRED_SQLITE_VERSION, '<')) - { - throw new ERequirementNotMet('SQLite ' . REQUIRED_SQLITE_VERSION . ' is required, however you are running ' . $sqliteVersion); - } - } + private function checkForConfigFile() + { + if (!file_exists(GROCY_DATAPATH . '/config.php')) + { + throw new ERequirementNotMet('config.php in data directory (' . GROCY_DATAPATH . ') not found. Have you copied config-dist.php to the data directory and renamed it to config.php?'); + } + } + + private function checkForConfigDistFile() + { + if (!file_exists(__DIR__ . '/../config-dist.php')) + { + throw new ERequirementNotMet('config-dist.php not found. Please do not remove this file.'); + } + } + + private function checkForComposer() + { + if (!file_exists(__DIR__ . '/../vendor/autoload.php')) + { + throw new ERequirementNotMet('/vendor/autoload.php not found. Have you run Composer?'); + } + } + + private function checkForPhpExtensions() + { + $loadedExtensions = get_loaded_extensions(); + foreach (REQUIRED_PHP_EXTENSIONS as $extension) + { + if (!in_array($extension, $loadedExtensions)) + { + throw new ERequirementNotMet("PHP module '{$extension}' not installed, but required."); + } + } + } + + + private function checkForSqliteVersion() + { + $sqliteVersion = self::getSqlVersionAsString(); + if (version_compare($sqliteVersion, REQUIRED_SQLITE_VERSION, '<')) + { + throw new ERequirementNotMet('SQLite ' . REQUIRED_SQLITE_VERSION . ' is required, however you are running ' . $sqliteVersion); + } + } private function getSqlVersionAsString() { diff --git a/localization/permissions.pot b/localization/permissions.pot index 1d265271..c5dba3f4 100644 --- a/localization/permissions.pot +++ b/localization/permissions.pot @@ -82,4 +82,4 @@ msgid "SHOPPINGLIST_ITEMS_ADD" msgstr "" msgid "SHOPPINGLIST_ITEMS_DELETE" -msgstr "" \ No newline at end of file +msgstr "" diff --git a/middleware/ApiKeyAuthMiddleware.php b/middleware/ApiKeyAuthMiddleware.php index 3f1679da..42c29079 100644 --- a/middleware/ApiKeyAuthMiddleware.php +++ b/middleware/ApiKeyAuthMiddleware.php @@ -10,67 +10,67 @@ use Grocy\Services\ApiKeyService; class ApiKeyAuthMiddleware extends AuthMiddleware { - public function __construct(\DI\Container $container, ResponseFactoryInterface $responseFactory) - { - parent::__construct($container, $responseFactory); - $this->ApiKeyHeaderName = $this->AppContainer->get('ApiKeyHeaderName'); - } + public function __construct(\DI\Container $container, ResponseFactoryInterface $responseFactory) + { + parent::__construct($container, $responseFactory); + $this->ApiKeyHeaderName = $this->AppContainer->get('ApiKeyHeaderName'); + } - protected $ApiKeyHeaderName; + protected $ApiKeyHeaderName; - function authenticate(Request $request) - { - if (!defined('GROCY_SHOW_AUTH_VIEWS')) - { - define('GROCY_SHOW_AUTH_VIEWS', true); - } + function authenticate(Request $request) + { + if (!defined('GROCY_SHOW_AUTH_VIEWS')) + { + define('GROCY_SHOW_AUTH_VIEWS', true); + } - $routeContext = RouteContext::fromRequest($request); - $route = $routeContext->getRoute(); - $routeName = $route->getName(); + $routeContext = RouteContext::fromRequest($request); + $route = $routeContext->getRoute(); + $routeName = $route->getName(); - $validApiKey = true; - $usedApiKey = null; + $validApiKey = true; + $usedApiKey = null; - $apiKeyService = new ApiKeyService(); + $apiKeyService = new ApiKeyService(); - // First check of the API key in the configured header - if (!$request->hasHeader($this->ApiKeyHeaderName) || !$apiKeyService->IsValidApiKey($request->getHeaderLine($this->ApiKeyHeaderName))) - { - $validApiKey = false; - } - else - { - $usedApiKey = $request->getHeaderLine($this->ApiKeyHeaderName); - } + // First check of the API key in the configured header + if (!$request->hasHeader($this->ApiKeyHeaderName) || !$apiKeyService->IsValidApiKey($request->getHeaderLine($this->ApiKeyHeaderName))) + { + $validApiKey = false; + } + else + { + $usedApiKey = $request->getHeaderLine($this->ApiKeyHeaderName); + } - // Not recommended, but it's also possible to provide the API key via a query parameter (same name as the configured header) - if (!$validApiKey && !empty($request->getQueryParam($this->ApiKeyHeaderName)) && $apiKeyService->IsValidApiKey($request->getQueryParam($this->ApiKeyHeaderName))) - { - $validApiKey = true; - $usedApiKey = $request->getQueryParam($this->ApiKeyHeaderName); - } + // Not recommended, but it's also possible to provide the API key via a query parameter (same name as the configured header) + if (!$validApiKey && !empty($request->getQueryParam($this->ApiKeyHeaderName)) && $apiKeyService->IsValidApiKey($request->getQueryParam($this->ApiKeyHeaderName))) + { + $validApiKey = true; + $usedApiKey = $request->getQueryParam($this->ApiKeyHeaderName); + } - // Handling of special purpose API keys - if (!$validApiKey) - { - if ($routeName === 'calendar-ical') - { - if ($request->getQueryParam('secret') !== null && $apiKeyService->IsValidApiKey($request->getQueryParam('secret'), ApiKeyService::API_KEY_TYPE_SPECIAL_PURPOSE_CALENDAR_ICAL)) - { - $validApiKey = true; - } - } - } + // Handling of special purpose API keys + if (!$validApiKey) + { + if ($routeName === 'calendar-ical') + { + if ($request->getQueryParam('secret') !== null && $apiKeyService->IsValidApiKey($request->getQueryParam('secret'), ApiKeyService::API_KEY_TYPE_SPECIAL_PURPOSE_CALENDAR_ICAL)) + { + $validApiKey = true; + } + } + } - if ($validApiKey) - { - return $apiKeyService->GetUserByApiKey($usedApiKey); + if ($validApiKey) + { + return $apiKeyService->GetUserByApiKey($usedApiKey); - } - else - { - return null; - } - } + } + else + { + return null; + } + } } diff --git a/middleware/AuthMiddleware.php b/middleware/AuthMiddleware.php index 7c7e1afa..6d99dbbd 100644 --- a/middleware/AuthMiddleware.php +++ b/middleware/AuthMiddleware.php @@ -12,73 +12,73 @@ use Grocy\Services\SessionService; abstract class AuthMiddleware extends BaseMiddleware { - public function __construct(\DI\Container $container, ResponseFactoryInterface $responseFactory) - { - parent::__construct($container); - $this->ResponseFactory = $responseFactory; - } + public function __construct(\DI\Container $container, ResponseFactoryInterface $responseFactory) + { + parent::__construct($container); + $this->ResponseFactory = $responseFactory; + } - protected $ResponseFactory; + protected $ResponseFactory; - public function __invoke(Request $request, RequestHandler $handler): Response - { - $routeContext = RouteContext::fromRequest($request); - $route = $routeContext->getRoute(); - $routeName = $route->getName(); - $isApiRoute = string_starts_with($request->getUri()->getPath(), '/api/'); + public function __invoke(Request $request, RequestHandler $handler): Response + { + $routeContext = RouteContext::fromRequest($request); + $route = $routeContext->getRoute(); + $routeName = $route->getName(); + $isApiRoute = string_starts_with($request->getUri()->getPath(), '/api/'); - if ($routeName === 'root') - { - return $handler->handle($request); - } - else if ($routeName === 'login') - { - define('GROCY_AUTHENTICATED', false); - return $handler->handle($request); - } - if (GROCY_MODE === 'dev' || GROCY_MODE === 'demo' || GROCY_MODE === 'prerelease' || GROCY_IS_EMBEDDED_INSTALL || GROCY_DISABLE_AUTH) - { - $sessionService = SessionService::getInstance(); - $user = $sessionService->GetDefaultUser(); + if ($routeName === 'root') + { + return $handler->handle($request); + } + else if ($routeName === 'login') + { + define('GROCY_AUTHENTICATED', false); + return $handler->handle($request); + } + if (GROCY_MODE === 'dev' || GROCY_MODE === 'demo' || GROCY_MODE === 'prerelease' || GROCY_IS_EMBEDDED_INSTALL || GROCY_DISABLE_AUTH) + { + $sessionService = SessionService::getInstance(); + $user = $sessionService->GetDefaultUser(); - define('GROCY_AUTHENTICATED', true); - define('GROCY_USER_USERNAME', $user->username); + define('GROCY_AUTHENTICATED', true); + define('GROCY_USER_USERNAME', $user->username); - return $handler->handle($request); - } - else - { - $user = $this->authenticate($request); + return $handler->handle($request); + } + else + { + $user = $this->authenticate($request); - if ($user === null) - { - define('GROCY_AUTHENTICATED', false); + if ($user === null) + { + define('GROCY_AUTHENTICATED', false); - $response = $this->ResponseFactory->createResponse(); - if ($isApiRoute) - { - return $response->withStatus(401); - } - else - { - return $response->withHeader('Location', $this->AppContainer->get('UrlManager')->ConstructUrl('/login')); - } - } - else - { - define('GROCY_AUTHENTICATED', true); - define('GROCY_USER_ID', $user->id); - define('GROCY_USER_USERNAME', $user->username); + $response = $this->ResponseFactory->createResponse(); + if ($isApiRoute) + { + return $response->withStatus(401); + } + else + { + return $response->withHeader('Location', $this->AppContainer->get('UrlManager')->ConstructUrl('/login')); + } + } + else + { + define('GROCY_AUTHENTICATED', true); + define('GROCY_USER_ID', $user->id); + define('GROCY_USER_USERNAME', $user->username); - return $response = $handler->handle($request); - } - } - } + return $response = $handler->handle($request); + } + } + } - /** - * @param Request $request - * @return mixed|null the user row or null if the request is not authenticated - * @throws \Exception Throws an \Exception if config is invalid. - */ - protected abstract function authenticate(Request $request); + /** + * @param Request $request + * @return mixed|null the user row or null if the request is not authenticated + * @throws \Exception Throws an \Exception if config is invalid. + */ + protected abstract function authenticate(Request $request); } diff --git a/middleware/DefaultAuthMiddleware.php b/middleware/DefaultAuthMiddleware.php index cb28e934..d16b0d21 100644 --- a/middleware/DefaultAuthMiddleware.php +++ b/middleware/DefaultAuthMiddleware.php @@ -6,19 +6,19 @@ use Psr\Http\Message\ServerRequestInterface as Request; class DefaultAuthMiddleware extends AuthMiddleware { - protected function authenticate(Request $request) - { - // First try to authenticate by API key - $auth = new ApiKeyAuthMiddleware($this->AppContainer, $this->ResponseFactory); - $user = $auth->authenticate($request); - if ($user !== null) - { - return $user; - } + protected function authenticate(Request $request) + { + // First try to authenticate by API key + $auth = new ApiKeyAuthMiddleware($this->AppContainer, $this->ResponseFactory); + $user = $auth->authenticate($request); + if ($user !== null) + { + return $user; + } - // Then by session cookie - $auth = new SessionAuthMiddleware($this->AppContainer, $this->ResponseFactory); - $user = $auth->authenticate($request); - return $user; - } + // Then by session cookie + $auth = new SessionAuthMiddleware($this->AppContainer, $this->ResponseFactory); + $user = $auth->authenticate($request); + return $user; + } } diff --git a/middleware/ReverseProxyAuthMiddleware.php b/middleware/ReverseProxyAuthMiddleware.php index a0536ca4..2e6e5d76 100644 --- a/middleware/ReverseProxyAuthMiddleware.php +++ b/middleware/ReverseProxyAuthMiddleware.php @@ -9,32 +9,32 @@ use Grocy\Services\UsersService; class ReverseProxyAuthMiddleware extends AuthMiddleware { - function authenticate(Request $request) - { - if (!defined('GROCY_SHOW_AUTH_VIEWS')) - { - define('GROCY_SHOW_AUTH_VIEWS', false); - } + function authenticate(Request $request) + { + if (!defined('GROCY_SHOW_AUTH_VIEWS')) + { + define('GROCY_SHOW_AUTH_VIEWS', false); + } - $db = DatabaseService::getInstance()->GetDbConnection(); + $db = DatabaseService::getInstance()->GetDbConnection(); - $username = $request->getHeader(GROCY_REVERSE_PROXY_AUTH_HEADER); - - if (count($username) !== 1) - { - // Invalid configuration of Proxy - throw new \Exception("ReverseProxyAuthMiddleware: Invalid username from proxy: " . var_dump($username)); - } + $username = $request->getHeader(GROCY_REVERSE_PROXY_AUTH_HEADER); - $username = $username[0]; + if (count($username) !== 1) + { + // Invalid configuration of Proxy + throw new \Exception("ReverseProxyAuthMiddleware: Invalid username from proxy: " . var_dump($username)); + } - $user = $db->users()->where('username', $username)->fetch(); - - if ($user == null) - { - $user = UsersService::getInstance()->CreateUser($username, '', '', ''); - } + $username = $username[0]; - return $user; - } + $user = $db->users()->where('username', $username)->fetch(); + + if ($user == null) + { + $user = UsersService::getInstance()->CreateUser($username, '', '', ''); + } + + return $user; + } } diff --git a/middleware/SessionAuthMiddleware.php b/middleware/SessionAuthMiddleware.php index aa0b2de6..2a716720 100644 --- a/middleware/SessionAuthMiddleware.php +++ b/middleware/SessionAuthMiddleware.php @@ -10,29 +10,29 @@ use Grocy\Services\SessionService; class SessionAuthMiddleware extends AuthMiddleware { - public function __construct(\DI\Container $container, ResponseFactoryInterface $responseFactory) - { - parent::__construct($container, $responseFactory); - $this->SessionCookieName = $this->AppContainer->get('LoginControllerInstance')->GetSessionCookieName(); - } + public function __construct(\DI\Container $container, ResponseFactoryInterface $responseFactory) + { + parent::__construct($container, $responseFactory); + $this->SessionCookieName = $this->AppContainer->get('LoginControllerInstance')->GetSessionCookieName(); + } - protected $SessionCookieName; + protected $SessionCookieName; - function authenticate(Request $request) - { - if (!defined('GROCY_SHOW_AUTH_VIEWS')) - { - define('GROCY_SHOW_AUTH_VIEWS', true); - } + function authenticate(Request $request) + { + if (!defined('GROCY_SHOW_AUTH_VIEWS')) + { + define('GROCY_SHOW_AUTH_VIEWS', true); + } - $sessionService = SessionService::getInstance(); - if (!isset($_COOKIE[$this->SessionCookieName]) || !$sessionService->IsValidSession($_COOKIE[$this->SessionCookieName])) - { - return null; - } - else - { - return $sessionService->GetUserBySessionKey($_COOKIE[$this->SessionCookieName]); - } - } + $sessionService = SessionService::getInstance(); + if (!isset($_COOKIE[$this->SessionCookieName]) || !$sessionService->IsValidSession($_COOKIE[$this->SessionCookieName])) + { + return null; + } + else + { + return $sessionService->GetUserBySessionKey($_COOKIE[$this->SessionCookieName]); + } + } } diff --git a/public/css/grocy.css b/public/css/grocy.css index e259138f..c94204d4 100644 --- a/public/css/grocy.css +++ b/public/css/grocy.css @@ -79,7 +79,7 @@ a.discrete-link:focus { top: 0; left: 0; } - + body.fullscreen-card { overflow: hidden; } @@ -575,13 +575,13 @@ canvas.drawingBuffer { } .print-view { - width: 100%; - max-width: 100%; - flex-basis: 100%; + width: 100%; + max-width: 100%; + flex-basis: 100%; } } .not-allowed { - pointer-events: none; + pointer-events: none; opacity: 0.5; -} \ No newline at end of file +} diff --git a/public/css/grocy_night_mode.css b/public/css/grocy_night_mode.css index 801f9901..e01d0c8c 100644 --- a/public/css/grocy_night_mode.css +++ b/public/css/grocy_night_mode.css @@ -220,23 +220,23 @@ } .night-mode .note-editor.note-frame .note-editing-area .note-editable { - color: #c1c1c1; - background-color: #333131; + color: #c1c1c1; + background-color: #333131; } .night-mode .bootstrap-datetimepicker-widget table td.day { - background-color: #333131; + background-color: #333131; } .night-mode .bootstrap-datetimepicker-widget table td { - background-color: #333131; + background-color: #333131; } -.night-mode .bootstrap-datetimepicker-widget table td, +.night-mode .bootstrap-datetimepicker-widget table td, .night-mode .bootstrap-datetimepicker-widget table th { - background-color: #333131; + background-color: #333131; } .night-mode .dropdown-menu { - background-color: #333131; + background-color: #333131; } diff --git a/public/index.php b/public/index.php index 55eef364..b022a1e3 100644 --- a/public/index.php +++ b/public/index.php @@ -36,7 +36,7 @@ try } catch (ERequirementNotMet $ex) { - die('Unable to run grocy: ' . $ex->getMessage()); + die('Unable to run grocy: ' . $ex->getMessage()); } require_once __DIR__ . '/../app.php'; diff --git a/public/js/extensions.js b/public/js/extensions.js index ad580f00..a3197eed 100644 --- a/public/js/extensions.js +++ b/public/js/extensions.js @@ -91,25 +91,25 @@ FindObjectInArrayByPropertyValue = function(array, propertyName, propertyValue) { if (array[i][propertyName] == propertyValue) { - return array[i]; - } + return array[i]; + } } - - return null; + + return null; } FindAllObjectsInArrayByPropertyValue = function(array, propertyName, propertyValue) { var returnArray = []; - + for (var i = 0; i < array.length; i++) { if (array[i][propertyName] == propertyValue) { returnArray.push(array[i]); - } + } } - + return returnArray; } @@ -137,7 +137,7 @@ function Delay(callable, delayMilliseconds) { var context = this; var args = arguments; - + clearTimeout(timer); timer = setTimeout(function() { @@ -150,7 +150,7 @@ $.fn.isVisibleInViewport = function(extraHeightPadding = 0) { var elementTop = $(this).offset().top; var viewportTop = $(window).scrollTop() - extraHeightPadding; - + return elementTop + $(this).outerHeight() > viewportTop && elementTop < viewportTop + $(window).height(); }; @@ -163,7 +163,7 @@ function animateCSS(selector, animationName, callback, speed = "faster") { nodes.removeClass('animated').removeClass(speed).removeClass(animationName); nodes.unbind('animationend', handleAnimationEnd); - + if (typeof callback === 'function') { callback(); diff --git a/public/js/grocy.js b/public/js/grocy.js index 4f45cb0f..91e38909 100644 --- a/public/js/grocy.js +++ b/public/js/grocy.js @@ -234,7 +234,7 @@ __t = function(text, ...placeholderValues) var text2 = text; Grocy.Api.Post('system/log-missing-localization', { "text": text2 }); } - + return Grocy.Translator.__(text, ...placeholderValues) } __n = function(number, singularForm, pluralForm) @@ -572,7 +572,7 @@ function RefreshLocaleNumberDisplay(rootSelector = "#page-content") { return; } - + $(this).text(parseFloat($(this).text()).toLocaleString(undefined, { minimumFractionDigits: 0, maximumFractionDigits: 2 })); }); } @@ -625,7 +625,7 @@ $(document).on("click", ".show-as-dialog-link", function(e) e.preventDefault(); var link = $(e.currentTarget).attr("href"); - + bootbox.dialog({ message: '', size: 'large', diff --git a/public/js/grocy_nightmode.js b/public/js/grocy_nightmode.js index 7615b073..2fb118a1 100644 --- a/public/js/grocy_nightmode.js +++ b/public/js/grocy_nightmode.js @@ -38,7 +38,7 @@ $(document).on("keyup", "#auto-night-mode-time-range-from, #auto-night-mode-time { var value = $(this).val(); var valueIsValid = moment(value, "HH:mm", true).isValid(); - + if (valueIsValid) { $(this).removeClass("bg-danger"); @@ -105,7 +105,7 @@ function CheckNightMode() $("body").removeClass("night-mode"); $("#currently-inside-night-mode-range").prop("checked", false); $("#currently-inside-night-mode-range").trigger("change"); - } + } } } if (Grocy.UserId !== -1) diff --git a/public/viewjs/barcodescannertesting.js b/public/viewjs/barcodescannertesting.js index 15a86dc1..6a6a2937 100644 --- a/public/viewjs/barcodescannertesting.js +++ b/public/viewjs/barcodescannertesting.js @@ -54,7 +54,7 @@ function OnBarcodeScanned(barcode) { return; } - + var bgClass = ""; if (barcode != $("#expected_barcode").val()) { @@ -91,6 +91,6 @@ $(document).on("Grocy.BarcodeScanned", function(e, barcode, target) { return; } - + OnBarcodeScanned(barcode); }); diff --git a/public/viewjs/choreform.js b/public/viewjs/choreform.js index 78ceba52..057240e6 100644 --- a/public/viewjs/choreform.js +++ b/public/viewjs/choreform.js @@ -7,7 +7,7 @@ { jsonData.assignment_config = $("#assignment_config").val().join(","); } - + Grocy.FrontendHelpers.BeginUiBusy("chore-form"); if (Grocy.EditMode === 'create') diff --git a/public/viewjs/components/barcodescanner.js b/public/viewjs/components/barcodescanner.js index f469765b..a9dd93f4 100644 --- a/public/viewjs/components/barcodescanner.js +++ b/public/viewjs/components/barcodescanner.js @@ -8,14 +8,14 @@ Grocy.Components.BarcodeScanner.CheckCapabilities = async function() if (typeof track.getCapabilities === 'function') { capabilities = track.getCapabilities(); } - + // If there is more than 1 camera, show the camera selection var cameras = await Quagga.CameraAccess.enumerateVideoDevices(); var cameraSelect = document.querySelector('.cameraSelect-wrapper'); if (cameraSelect) { cameraSelect.style.display = cameras.length > 1 ? 'inline-block' : 'none'; } - + // Check if the camera is capable to turn on a torch. var canTorch = typeof capabilities.torch === 'boolean' && capabilities.torch // Remove the torch button, if either the device can not torch or AutoTorchOn is set. @@ -133,7 +133,7 @@ Grocy.Components.BarcodeScanner.StartScanning = function() Grocy.Components.BarcodeScanner.StopScanning = function() { Quagga.stop(); - + Grocy.Components.BarcodeScanner.DecodedCodesCount = 0; Grocy.Components.BarcodeScanner.DecodedCodesErrorCount = 0; @@ -143,9 +143,9 @@ Grocy.Components.BarcodeScanner.StopScanning = function() Grocy.Components.BarcodeScanner.TorchOn = function(track) { if (track) { - track.applyConstraints({ + track.applyConstraints({ advanced: [ - { + { torch: true } ] @@ -214,7 +214,7 @@ $(document).on("click", "#barcodescanner-start-button", async function(e) } Grocy.Components.BarcodeScanner.CurrentTarget = inputElement.attr("data-target"); - + var dialog = bootbox.dialog({ message: '
diff --git a/views/batteriesoverview.blade.php b/views/batteriesoverview.blade.php index 91aa97d2..e23acd28 100644 --- a/views/batteriesoverview.blade.php +++ b/views/batteriesoverview.blade.php @@ -62,7 +62,7 @@ @include('components.userfields_thead', array( 'userfields' => $userfields )) - +
diff --git a/views/components/shoppinglocationpicker.blade.php b/views/components/shoppinglocationpicker.blade.php index 83aaf767..c72c6928 100644 --- a/views/components/shoppinglocationpicker.blade.php +++ b/views/components/shoppinglocationpicker.blade.php @@ -16,5 +16,5 @@ @endforeach -{!! $exception->getFile() !!}:{!! $exception->getLine() !!}
- {!! $exception->getMessage() !!}
- {!! $exception->getTraceAsString() !!}
- {!! $exception->getFile() !!}:{!! $exception->getLine() !!}
+ {!! $exception->getMessage() !!}
+ {!! $exception->getTraceAsString() !!}
+