Add access rules for the specified public key

@param EventInterface $event The current event
430778
public function addRules(EventInterface $event) {
        $accessControl = $event->getAccessControl();

        if (!($accessControl instanceof MutableAdapterInterface)) {
            throw new ResourceException('Access control adapter is immutable', 405);
        }

        $request = $event->getRequest();
        $publicKey = $request->getRoute()->get('publickey');
        $data = json_decode($request->getContent(), true);

        if (!is_array($data)) {
            throw new InvalidArgumentException('No access rule data provided', 400);
        }

        // If a single rule was provided, wrap it in an array
        if (!count($data) || !isset($data[0])) {
            $data = [$data];
        }

        $accessControl = $event->getAccessControl();

        // Perform rule validation
        foreach ($data as $rule) {
            $this->validateRule($event, $rule);
        }

        // Insert the rules
        foreach ($data as $rule) {
            $accessControl->addAccessRule($publicKey, $rule);
        }
    }
726144
public function makeSchemaValidator(EventInterface $event, $schema)
    {
        // we can't validate on an array, only an object
        // so we need to convert the event payload to an object
        $payload = $event->toMessage();
        $payload = json_encode($payload); // back to json
        $payload = json_decode($payload); // from json to an object

        return new Validator($payload, $schema);
    }
1360096
public function getKey(EventInterface $event) {
        $acl = $event->getAccessControl();

        $publicKey = $event->getRequest()->getRoute()->get('publickey');

        if (!$acl->publicKeyExists($publicKey)) {
            throw new RuntimeException('Public key not found', 404);
        }
    }
124728
public function httpPassword(Event $event)
    {
        $event['request']->setHeader('Authorization', sprintf('Basic %s', base64_encode($this->auth['username'] . ':' . $this->auth['password'])));
    }
998842
public function remove(EventInterface $event)
    {
        $index = $this->computeIndex($event);
        if (isset($this->events[$index])) {
            foreach ($this->events[$index] as $key => $internalEvent) {
                if ($event->getUid() == $internalEvent->getUid()) {
                    unset($this->events[$index][$key]);
                    --$this->count;
                }
            }
        }
    }
1320392
public function signRequest(Event $event) {
        $command = $event['command'];

        switch ($command->getName()) {
            case 'AddImage':
            case 'DeleteImage':
            case 'ReplaceMetadata':
            case 'EditMetadata':
            case 'DeleteMetadata':
            case 'GenerateShortUrl':
            case 'EditResourceGroup':
            case 'DeleteResourceGroup':
            case 'EditPublicKey':
            case 'DeletePublicKey':
            case 'AddAccessControlRules':
            case 'DeleteAccessControlRule':
                // Add the auth headers
                $this->addAuthenticationHeaders($command->getRequest());
                break;
        }
    }
1152172
public function setEvent(EventInterface $event)
    {
        $target = $this;

        if (!($event instanceof AuthenticationEvent)) {
            $eventParams = $event->getParams();
            $eventTarget = $event->getTarget();

            if ($eventTarget) {
                $target = $eventTarget;
            }

            $event = new AuthenticationEvent();

            $event->setParams($eventParams);
        }

        $event->setIdentity(null)->setTarget($target);

        $this->event = $event;

        return $this;
    }
721267
public function post(EventInterface $event) {
        $request = $event->getRequest();

        $event->getManager()->trigger('db.metadata.update', [
            'metadata' => json_decode($request->getContent(), true),
        ]);

        $model = new Model\Metadata();
        $model->setData($event->getDatabase()->getMetadata($request->getUser(), $request->getImageIdentifier()));

        $event->getResponse()->setModel($model);
    }
687354
public function handle(EventInterface $event)
    {

        try {
            // load the application server and system configuration instance
            /** @var \AppserverIo\Psr\ApplicationServer\ApplicationServerInterface $applicationServer */
            $applicationServer = $this->getApplicationServer();
            /** @var \AppserverIo\Psr\ApplicationServer\Configuration\SystemConfigurationInterface $systemConfiguration */
            $systemConfiguration = $applicationServer->getSystemConfiguration();

            // load the initial context configuration
            /** @var \AppserverIo\Psr\ApplicationServer\Configuration\InitialContextConfigurationInterface $initialContextNode */
            $initialContextNode = $systemConfiguration->getInitialContext();
            $reflectionClass = new \ReflectionClass($initialContextNode->getType());
            /** @var \AppserverIo\Psr\ApplicationServer\ContextInterface $initialContext */
            $initialContext = $reflectionClass->newInstanceArgs(array($systemConfiguration));

            // attach the registered loggers to the initial context
            $initialContext->setLoggers($applicationServer->getLoggers());
            $initialContext->setSystemLogger($applicationServer->getSystemLogger());

            // set the initial context and flush it initially
            $applicationServer->setInitialContext($initialContext);

        } catch (\Exception $e) {
            $applicationServer->getSystemLogger()->error($e->__toString());
        }
    }
843910
public function options(EventInterface $event) {
        $request = $event->getRequest();
        $response = $event->getResponse();
        $origin = $request->headers->get('Origin');

        // This is an OPTIONS request, send 204 since no more content will follow
        $response->setStatusCode(204);

        // Vary on Origin to prevent caching allowed/disallowed requests
        $event->getResponse()->setVary('Origin', false);

        // Fall back if the passed origin is not allowed
        if (!$origin || !$this->originIsAllowed($origin)) {
            return;
        }

        $resource = (string) $request->getRoute();

        $allowedMethods = ['OPTIONS'];

        if (isset($this->params['allowedMethods'][$resource])) {
            $allowedMethods = array_merge($allowedMethods, $this->params['allowedMethods'][$resource]);
        }

        $allowedHeaders = ['Content-Type', 'Accept'];

        $requestHeaders = $request->headers->get('Access-Control-Request-Headers', '');
        $requestHeaders = array_map('trim', explode(',', $requestHeaders));

        foreach ($requestHeaders as $header) {
            if (strpos($header, 'x-imbo') === 0) {
                $allowedHeaders[] = implode('-', array_map('ucfirst', explode('-', $header)));;
            }
        }

        $response->headers->add([
            'Access-Control-Allow-Origin' => $origin,
            'Access-Control-Allow-Methods' => implode(', ', $allowedMethods),
            'Access-Control-Allow-Headers' => implode(', ', $allowedHeaders),
            'Access-Control-Max-Age' => (int) $this->params['maxAge'],
        ]);

        // Since this is an OPTIONS-request, there is no need for further parsing
        $event->stopPropagation();
    }
775866
public function trigger(EventInterface $event, array $args = []){
        return call_user_func_array($this->callback, array_merge([$event], $args));
    }
1164474
protected function triggerHandlers(EventInterface $event)
    {
        foreach ($this->getHandlers($event->getName()) as $handler) {
            call_user_func($handler, $event);
            if ($event->isPropagationStopped()) {
                break;
            }
        }
    }
1147408
public function updateMetadata(EventInterface $event) {
        $request = $event->getRequest();

        $event->getDatabase()->updateMetadata(
            $request->getUser(),
            $request->getImageIdentifier(),
            $event->getArgument('metadata')
        );

        $event->getDatabase()->setLastModifiedNow(
            $request->getUser(),
            $request->getImageIdentifier()
        );
    }
524692
public function record(EventInterface $event)
    {
        $eventUuid = $event->uuid();
        $this->recordedEvents[(string) $eventUuid] = $event;
    }
913931
public function urlSecret(Event $event)
    {
        $query = $event['request']->getQuery();

        $query->set('client_id', $this->auth['client_id']);
        $query->set('client_secret', $this->auth['client_secret']);
    }
541077
public function setExposedHeaders(EventInterface $event) {
        // If this request was disallowed, don't expose any headers
        if (!$this->requestAllowed) {
            return;
        }

        $headers = [
            // The ResponseSender-listener will add this header and send the response,
            // so we have no way to pick it up - instead we'll always whitelist it
            'X-Imbo-ImageIdentifier'
        ];

        foreach ($event->getResponse()->headers as $header => $value) {
            if (strpos($header, 'x-imbo') === 0) {
                $headers[] = implode('-', array_map('ucfirst', explode('-', $header)));;
            }
        }

        $event->getResponse()->headers->add([
            'Access-Control-Expose-Headers' => implode(', ', $headers)
        ]);
    }
724543
public static function setPermissionsChmod(Event $event)
	{
		$http_user = self::getHttpdUser($event);
		foreach (self::getWritableDirs($event) as $path) {
			self::ChmodPermissionsSetter($event, $http_user, $path, 'dir');
		}
		foreach (self::getWritableFiles($event) as $path) {
			self::ChmodPermissionsSetter($event, $http_user, $path, 'file');
		}
	}