Skip to content

armgit / Vvveb

Public Imported from GitHub
0

Powerful and easy to use cms to build websites, blogs or ecommerce stores.

7.8 KB
Raw Blame
<?php

/**
 * Vvveb
 *
 * Copyright (C) 2022  Ziadin Givan
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 */

namespace Vvveb\Controller;

use function Vvveb\__;
use function Vvveb\config;
use function Vvveb\siteSettings;
use Vvveb\System\Core\FrontController;
use Vvveb\System\Core\Request;
use Vvveb\System\Core\Response;
use Vvveb\System\Event;
use Vvveb\System\Extensions\Plugins;
use Vvveb\System\Session;
use Vvveb\System\Traits\Permission;
use Vvveb\System\User\Admin;

#[\AllowDynamicProperties]
class Base {
	use Permission;

	/** @var array<string, mixed> */
	protected array $global = [];

	/**
	 * Authenticate the current admin user via HTTP or token-based auth.
	 *
	 * @return void
	 */
	public function auth(): void {
		$admin = Admin::current();

		if (!$admin) {
			$authMode = config(APP . '.auth.mode');

			if ($authMode == 'http') {
				if (isset($_SERVER['PHP_AUTH_USER'])) {
					$user      = $_SERVER['PHP_AUTH_USER'];
					$password  = $_SERVER['PHP_AUTH_PW'] ?? '';
					$loginData = compact('user', 'password');
					$feedback  = [];

					if ($userInfo = Admin::login($loginData, [], $feedback)) {
					} else {
						$this->response->addHeader('WWW-Authenticate', 'Basic realm="REST Api"');
						$this->response->addHeader('HTTP/1.0 401 Unauthorized');
						$message = __('Auth failed!');

						if (DEBUG) {
							$message .= ' ' . ($feedback['message'] ?? '');
							$message .= " auth.mode = $authMode";
						}
						//FrontController::notFound(false, $message, 403);
						$this->notFound($message, 403);
					}
				} else {
					$this->response->addHeader('WWW-Authenticate', 'Basic realm="REST Api"');
					$this->response->addHeader('HTTP/1.0 401 Unauthorized');
					$message = __('Auth failed!');

					if (DEBUG) {
						$message .= __('No credentials!');
						$message .= " auth.mode = $authMode";
					}
					//FrontController::notFound(false, $message, 403);
					$this->notFound($message, 403);
				}
			} else {
				if ($authMode == 'token') {
					$headers = getallheaders();
					$token   = $headers['Bearer'] ?? $_SERVER['HTTP_BEARER'] ?? null;

					if (!$token) {
						$token = $headers['Authorization'] ?? $_SERVER['HTTP_AUTHORIZATION'] ?? '';
						$token = trim(substr($token, 6)) ?: $this->request->get['_token'] ?? false;
					}

					if ($token) {
						$feedback = [];
						if ($userInfo = Admin::auth($token, [], $feedback)) {
						} else {
							$this->response->addHeader('HTTP/1.0 401 Unauthorized');
							$message = __('Auth failed!');

							if (DEBUG) {
								$message .= ' ' . ($feedback['message'] ?? '');
								$message .= " auth.mode = $authMode";
							}
							//FrontController::notFound(false, $message, 403);
							$this->notFound($message, 403);
						}
					} else {
						$this->response->addHeader('HTTP/1.0 401 Unauthorized');
						$message = __('Auth failed!');

						if (DEBUG) {
							$message .= __('No credentials!');
							$message .= " auth.mode = $authMode";
						}
						//FrontController::notFound(false, $message, 403);
						$this->notFound($message, 403);
					}
				}
			}
		}
	}

	/**
	 * Initialize ecommerce tax rules for the given region.
	 *
	 * @param int $countryId
	 * @param int $regionId
	 *
	 * @return void
	 */
	protected function initEcommerce(int $countryId, int $regionId): void {
		$tax = \Vvveb\System\Cart\Tax::getInstance();
		$tax->setRegionRules($countryId, $regionId, 'store');
	}

	/**
	 * Initialize the REST controller: set up request/response/session, authenticate, and load global settings.
	 *
	 * @return string|null HTTP method for write operations, or null
	 */
	public function init(): ?string {
		$this->response = Response::getInstance();
		$this->request  = Request::getInstance();
		$this->session  = Session::getInstance();

		$this->response->setType('json');

		if (!REST) {
			$this->notFound(__('REST is disabled!'), 404);
		}

		$this->auth();

		//alow method override via get parameter to avoid issues with unsupported put and patch on some webservers
		$method     = $this->request->get['_method'] ?? $this->request->getMethod();

		$permission = str_replace('/rest/', '', ($this->request->get['route'] ?? '') . '/' . $method);
		//Check permissions
		$className = static::class;

		if ($className != 'Vvveb\Controller\Error403') {
			$this->permission($permission);
		}

		Plugins :: loadPlugins();
		$site = siteSettings();

		[$site] = Event::trigger(__CLASS__, __FUNCTION__, $site);

		$user                                = Admin::current();
		$this->global['site_id']             = SITE_ID;
		$this->global['language_id']         = $this->session->get('language_id') ?? $site['language_id'] ?? 1;
		$this->global['default_language_id'] = $this->session->get('default_language_id') ?? $site['language_id'] ?? 1;
		$this->global['limit']               = 10;
		$this->global['start']               = 0;
		$this->global['user_id']             = $user['user_id'] ?? false;
		$this->global['user_group_id']       = $user['user_group_id'] ?? 1;
		$this->global['site']                = &$site;
		$this->global['user']                = $user;

		$language_id = $this->global['language_id'];

		if (isset($site['description'][$language_id])) {
			$site['description'] = $site['description'][$language_id];
		}

		if (isset($site['country_id'])) {
			$this->initEcommerce($site['country_id'], $site['region_id']);
		}

		$this->global['site'] = &$site;

		[$this->global] = Event::trigger(__CLASS__, __FUNCTION__ . ':after', $this->global);

		if (in_array($method, ['post', 'put', 'delete', 'patch'])) {
			return $method;
		}

		return null;
	}

	/**
	 * Call this function if the requested information was not found, for example if the specified news, image, profile etc is not found then call this function.
	 * It shows a "Not found" page and it also sends 404 http status code, this is useful for search engines etc.
	 *
	 * @param array<string, mixed>|string|null $message
	 * @param int                              $statusCode
	 * @param bool                             $service
	 *
	 * @return never
	 */
	protected function notFound(array|string|null $message = null, int $statusCode = 404, bool $service = false): never {
		$response = Response::getInstance();
		http_response_code($statusCode);

		$output = [
			'openapi' => '3.1.0',
			'info'    => [
				'title'       => 'Vvveb',
				'description' => 'Vvveb',
				'version'     => '1',
				'contact'     => [
				],
			],
			'servers'    => [['url' => '/rest']],
			'tags'       => [['name' => 'v1', 'description' => '']],
			'security'   => [['bearerAuth' => [], 'basicAuth' => []]],
			'components' => [
				'securitySchemes' => [
					'bearerAuth' => [
						'type'        => 'http',
						'scheme'      => 'bearer',
						'in'          => 'header',
						'description' => 'Use api auth token as credential',
					],
					'basicAuth' => [
						'type'        => 'http',
						'scheme'      => 'basic',
						'in'          => 'header',
						'username'    => '',
						'password'    => '',
						'description' => 'Use admin user and password as credentials',
					],
				],
				'schemas' => [],
			],
			'code' => $statusCode,
		];

		if (is_array($message)) {
			$output += $message;
		} else {
			$output['message'] = $message;
		}

		$response->output($output);

		exit();
	}
}