Beispiel #1
0
 /**
  * Sets the Active Directory Driver.
  */
 protected function setDriver()
 {
     $host = $this->getHost();
     $baseDn = $this->getBaseDn();
     $accountSuffix = ArrayUtils::get($this->config, 'account_suffix');
     $this->driver = new \DreamFactory\Core\ADLdap\Components\ADLdap($host, $baseDn, $accountSuffix);
 }
Beispiel #2
0
 /**
  * Returns role info cached, or reads from db if not present.
  * Pass in a key to return a portion/index of the cached data.
  *
  * @param int         $id
  * @param null|string $key
  * @param null        $default
  *
  * @return mixed|null
  */
 public static function getCachedInfo($id, $key = null, $default = null)
 {
     $cacheKey = 'role:' . $id;
     try {
         $result = \Cache::remember($cacheKey, \Config::get('df.default_cache_ttl'), function () use($id) {
             $role = Role::with(['role_lookup_by_role_id', 'role_service_access_by_role_id', 'service_by_role_service_access'])->whereId($id)->first();
             if (empty($role)) {
                 throw new NotFoundException("Role not found.");
             }
             $roleInfo = $role->toArray();
             $services = ArrayUtils::get($roleInfo, 'service_by_role_service_access');
             unset($roleInfo['service_by_role_service_access']);
             foreach ($roleInfo['role_service_access_by_role_id'] as $key => $value) {
                 $serviceName = ArrayUtils::findByKeyValue($services, 'id', ArrayUtils::get($value, 'service_id'), 'name');
                 $component = ArrayUtils::get($value, 'component');
                 $roleInfo['role_service_access_by_role_id'][$key]['service'] = $serviceName;
                 $roleInfo['role_service_access_by_role_id'][$key]['component'] = trim($component, '/');
             }
             return $roleInfo;
         });
         if (is_null($result)) {
             return $default;
         }
     } catch (ModelNotFoundException $ex) {
         return $default;
     }
     if (is_null($key)) {
         return $result;
     }
     return isset($result[$key]) ? $result[$key] : $default;
 }
Beispiel #3
0
 /**
  * Create a new CouchDbSvc
  *
  * @param array $settings
  *
  * @throws \InvalidArgumentException
  * @throws \Exception
  */
 public function __construct($settings = [])
 {
     parent::__construct($settings);
     $config = ArrayUtils::clean(ArrayUtils::get($settings, 'config'));
     Session::replaceLookups($config, true);
     $dsn = strval(ArrayUtils::get($config, 'dsn'));
     if (empty($dsn)) {
         $dsn = 'http://localhost:5984';
     }
     $options = [];
     if (isset($config['options'])) {
         $options = $config['options'];
     }
     $db = isset($options['db']) ? $options['db'] : null;
     if (!isset($db)) {
         //  Attempt to find db in connection string
         $temp = trim(strstr($dsn, '//'), '/');
         $db = strstr($temp, '/');
         $db = trim($db, '/');
     }
     if (empty($db)) {
         $db = 'default';
     }
     try {
         $this->dbConn = @new \couchClient($dsn, $db, $options);
     } catch (\Exception $ex) {
         throw new InternalServerErrorException("CouchDb Service Exception:\n{$ex->getMessage()}");
     }
 }
Beispiel #4
0
 /**
  * Gets the token from Authorization header.
  *
  * @return string
  */
 protected static function getJWTFromAuthHeader()
 {
     if ('testing' === env('APP_ENV')) {
         //getallheaders method is not available in unit test mode.
         return [];
     }
     if (!function_exists('getallheaders')) {
         function getallheaders()
         {
             if (!is_array($_SERVER)) {
                 return [];
             }
             $headers = [];
             foreach ($_SERVER as $name => $value) {
                 if (substr($name, 0, 5) == 'HTTP_') {
                     $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
                 }
             }
             return $headers;
         }
     }
     $token = null;
     $headers = getallheaders();
     $authHeader = ArrayUtils::get($headers, 'Authorization');
     if (strpos($authHeader, 'Bearer') !== false) {
         $token = substr($authHeader, 7);
     }
     return $token;
 }
Beispiel #5
0
 /**
  * Create a new AzureTablesSvc
  *
  * @param array $settings
  *
  * @throws \InvalidArgumentException
  * @throws \Exception
  */
 public function __construct($settings = array())
 {
     parent::__construct($settings);
     $config = ArrayUtils::clean(ArrayUtils::get($settings, 'config'));
     Session::replaceLookups($config, true);
     $dsn = strval(ArrayUtils::get($config, 'connection_string'));
     if (empty($dsn)) {
         $name = ArrayUtils::get($config, 'account_name', ArrayUtils::get($config, 'AccountName'));
         if (empty($name)) {
             throw new \InvalidArgumentException('WindowsAzure account name can not be empty.');
         }
         $key = ArrayUtils::get($config, 'account_key', ArrayUtils::get($config, 'AccountKey'));
         if (empty($key)) {
             throw new \InvalidArgumentException('WindowsAzure account key can not be empty.');
         }
         $protocol = ArrayUtils::get($config, 'protocol', 'https');
         $dsn = "DefaultEndpointsProtocol={$protocol};AccountName={$name};AccountKey={$key}";
     }
     // set up a default partition key
     $partitionKey = ArrayUtils::get($config, static::PARTITION_KEY);
     if (!empty($partitionKey)) {
         $this->defaultPartitionKey = $partitionKey;
     }
     try {
         $this->dbConn = ServicesBuilder::getInstance()->createTableService($dsn);
     } catch (\Exception $ex) {
         throw new InternalServerErrorException("Windows Azure Table Service Exception:\n{$ex->getMessage()}");
     }
 }
Beispiel #6
0
 /**
  * {@inheritdoc}
  */
 protected function setTransport($config)
 {
     $key = ArrayUtils::get($config, 'key');
     $secret = ArrayUtils::get($config, 'secret');
     $region = ArrayUtils::get($config, 'region', 'us-east-1');
     $this->transport = static::getTransport($key, $secret, $region);
 }
 /**
  * {@inheritdoc}
  */
 public static function setConfig($id, $config)
 {
     $rosConfig = OpenStackConfig::find($id);
     $pathConfig = FilePublicPath::find($id);
     $configPath = ['public_path' => ArrayUtils::get($config, 'public_path'), 'container' => ArrayUtils::get($config, 'container')];
     $configRos = ['service_id' => ArrayUtils::get($config, 'service_id'), 'username' => ArrayUtils::get($config, 'username'), 'password' => ArrayUtils::get($config, 'password'), 'tenant_name' => ArrayUtils::get($config, 'tenant_name'), 'api_key' => ArrayUtils::get($config, 'api_key'), 'url' => ArrayUtils::get($config, 'url'), 'region' => ArrayUtils::get($config, 'region'), 'storage_type' => ArrayUtils::get($config, 'storage_type')];
     ArrayUtils::removeNull($configRos);
     ArrayUtils::removeNull($configPath);
     if (!empty($rosConfig)) {
         $rosConfig->update($configRos);
     } else {
         //Making sure service_id is the first item in the config.
         //This way service_id will be set first and is available
         //for use right away. This helps setting an auto-generated
         //field that may depend on parent data. See OAuthConfig->setAttribute.
         $configRos = array_reverse($configRos, true);
         $configRos['service_id'] = $id;
         $configRos = array_reverse($configRos, true);
         OpenStackConfig::create($configRos);
     }
     if (!empty($pathConfig)) {
         $pathConfig->update($configPath);
     } else {
         //Making sure service_id is the first item in the config.
         //This way service_id will be set first and is available
         //for use right away. This helps setting an auto-generated
         //field that may depend on parent data. See OAuthConfig->setAttribute.
         $configPath = array_reverse($configPath, true);
         $configPath['service_id'] = $id;
         $configPath = array_reverse($configPath, true);
         FilePublicPath::create($configPath);
     }
 }
Beispiel #8
0
 /**
  * {@inheritdoc}
  */
 protected function setDriver($config)
 {
     $clientId = ArrayUtils::get($config, 'client_id');
     $clientSecret = ArrayUtils::get($config, 'client_secret');
     $redirectUrl = ArrayUtils::get($config, 'redirect_url');
     $this->driver = new TwitterProvider($clientId, $clientSecret, $redirectUrl);
 }
 public static function validateConfig($config, $create = true)
 {
     if (null === ArrayUtils::get($config, 'username', null, true) || null === ArrayUtils::get($config, 'password', null, true)) {
         throw new BadRequestException('Both Username and Password are required');
     }
     return true;
 }
Beispiel #10
0
 /**
  * Create a new DynamoDb
  *
  * @param array $settings
  *
  * @throws \InvalidArgumentException
  * @throws \Exception
  */
 public function __construct($settings = [])
 {
     parent::__construct($settings);
     $config = ArrayUtils::clean(ArrayUtils::get($settings, 'config'));
     //  Replace any private lookups
     Session::replaceLookups($config, true);
     // statically assign our supported version
     $config['version'] = '2012-08-10';
     if (isset($config['key'])) {
         $config['credentials']['key'] = $config['key'];
     }
     if (isset($config['secret'])) {
         $config['credentials']['secret'] = $config['secret'];
     }
     // set up a default table schema
     $parameters = ArrayUtils::clean(ArrayUtils::get($config, 'parameters'));
     Session::replaceLookups($parameters);
     if (null !== ($table = ArrayUtils::get($parameters, 'default_create_table'))) {
         $this->defaultCreateTable = $table;
     }
     try {
         $this->dbConn = new DynamoDbClient($config);
     } catch (\Exception $ex) {
         throw new InternalServerErrorException("AWS DynamoDb Service Exception:\n{$ex->getMessage()}", $ex->getCode());
     }
 }
 /**
  * {@inheritdoc}
  */
 public static function setConfig($id, $config)
 {
     $azureConfig = AzureConfig::find($id);
     $pathConfig = FilePublicPath::find($id);
     $configPath = ['public_path' => ArrayUtils::get($config, 'public_path'), 'container' => ArrayUtils::get($config, 'container')];
     $configAzure = ['service_id' => ArrayUtils::get($config, 'service_id'), 'account_name' => ArrayUtils::get($config, 'account_name'), 'account_key' => ArrayUtils::get($config, 'account_key'), 'protocol' => ArrayUtils::get($config, 'protocol')];
     ArrayUtils::removeNull($configAzure);
     ArrayUtils::removeNull($configPath);
     if (!empty($azureConfig)) {
         $azureConfig->update($configAzure);
     } else {
         //Making sure service_id is the first item in the config.
         //This way service_id will be set first and is available
         //for use right away. This helps setting an auto-generated
         //field that may depend on parent data. See OAuthConfig->setAttribute.
         $configAzure = array_reverse($configAzure, true);
         $configAzure['service_id'] = $id;
         $configAzure = array_reverse($configAzure, true);
         AzureConfig::create($configAzure);
     }
     if (!empty($pathConfig)) {
         $pathConfig->update($configPath);
     } else {
         //Making sure service_id is the first item in the config.
         //This way service_id will be set first and is available
         //for use right away. This helps setting an auto-generated
         //field that may depend on parent data. See OAuthConfig->setAttribute.
         $configPath = array_reverse($configPath, true);
         $configPath['service_id'] = $id;
         $configPath = array_reverse($configPath, true);
         FilePublicPath::create($configPath);
     }
 }
Beispiel #12
0
 public function __construct($settings = [])
 {
     $verbAliases = [Verbs::PUT => Verbs::POST, Verbs::MERGE => Verbs::POST, Verbs::PATCH => Verbs::POST];
     ArrayUtils::set($settings, "verbAliases", $verbAliases);
     parent::__construct($settings);
     $this->model = \DreamFactory\Core\Models\Config::class;
 }
Beispiel #13
0
 /**
  * Create a new SqlDbSvc
  *
  * @param array $settings
  *
  * @throws \InvalidArgumentException
  * @throws \Exception
  */
 public function __construct($settings = [])
 {
     parent::__construct($settings);
     $config = ArrayUtils::clean(ArrayUtils::get($settings, 'config'));
     Session::replaceLookups($config, true);
     $driver = isset($config['driver']) ? $config['driver'] : null;
     $this->dbConn = ConnectionFactory::createConnection($driver, $config);
     $this->dbConn->setCache($this);
     $this->dbConn->setExtraStore($this);
     $defaultSchemaOnly = ArrayUtils::getBool($config, 'default_schema_only');
     $this->dbConn->setDefaultSchemaOnly($defaultSchemaOnly);
     switch ($this->dbConn->getDBName()) {
         case SqlDbDriverTypes::MYSQL:
         case SqlDbDriverTypes::MYSQLI:
             $this->dbConn->setAttribute(\PDO::ATTR_EMULATE_PREPARES, true);
             break;
         case SqlDbDriverTypes::DBLIB:
             $this->dbConn->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
             break;
     }
     $attributes = ArrayUtils::clean(ArrayUtils::get($settings, 'attributes'));
     if (!empty($attributes)) {
         $this->dbConn->setAttributes($attributes);
     }
 }
Beispiel #14
0
 /**
  * {@inheritdoc}
  */
 public function getApiDocInfo()
 {
     $base = parent::getApiDocInfo();
     $apis = [];
     $models = [];
     foreach ($this->getResources(true) as $resourceInfo) {
         $className = ArrayUtils::get($resourceInfo, 'class_name');
         if (!class_exists($className)) {
             throw new InternalServerErrorException('Service configuration class name lookup failed for resource ' . $this->resourcePath);
         }
         /** @var BaseRestResource $resource */
         $resource = $this->instantiateResource($className, $resourceInfo);
         $name = ArrayUtils::get($resourceInfo, 'name', '') . '/';
         $access = $this->getPermissions($name);
         if (!empty($access)) {
             $results = $resource->getApiDocInfo();
             if (isset($results, $results['apis'])) {
                 $apis = array_merge($apis, $results['apis']);
             }
             if (isset($results, $results['models'])) {
                 $models = array_merge($models, $results['models']);
             }
         }
     }
     $base['apis'] = array_merge($base['apis'], $apis);
     $base['models'] = array_merge($base['models'], $models);
     return $base;
 }
Beispiel #15
0
 /**
  *
  * @return array The array of cache keys associated with this service
  */
 protected function getCacheKeys()
 {
     if (empty($this->cacheKeys)) {
         $this->cacheKeys = Cache::get($this->cachePrefix . 'cache_keys', []);
     }
     return ArrayUtils::clean($this->cacheKeys);
 }
Beispiel #16
0
 /**
  * {@inheritdoc}
  */
 protected function setDriver($config)
 {
     $this->container = ArrayUtils::get($config, 'container');
     if (empty($this->container)) {
         throw new InternalServerErrorException('S3 file service bucket not specified. Please check configuration for file service - ' . $this->name);
     }
     $this->driver = new S3FileSystem($config);
 }
Beispiel #17
0
 /**
  * {@inheritdoc}
  */
 public function setDriver($config)
 {
     $this->container = ArrayUtils::get($config, 'container');
     if (empty($this->container)) {
         throw new InternalServerErrorException('Azure blob container not specified. Please check configuration for file service - ' . $this->name);
     }
     $this->driver = new AzureBlobFileSystem($config);
 }
Beispiel #18
0
 /**
  * Create a new SqlDbSvc
  *
  * @param array $settings
  *
  * @throws \InvalidArgumentException
  * @throws \Exception
  */
 public function __construct($settings = [])
 {
     parent::__construct($settings);
     $config = ArrayUtils::clean(ArrayUtils::get($settings, 'config'));
     $this->cacheEnabled = ArrayUtils::getBool($config, 'cache_enabled');
     $this->cacheTTL = intval(ArrayUtils::get($config, 'cache_ttl', \Config::get('df.default_cache_ttl')));
     $this->cachePrefix = 'service_' . $this->id . ':';
 }
Beispiel #19
0
 /**
  * Convert the model instance to an array.
  *
  * @return array
  */
 public function toArray()
 {
     $attributes = $this->attributesToArray();
     if (ArrayUtils::getBool($attributes, 'private')) {
         $attributes['value'] = self::PRIVATE_MASK;
     }
     return array_merge($attributes, $this->relationsToArray());
 }
Beispiel #20
0
 /**
  * @param array $settings
  */
 public function __construct($settings = [])
 {
     $verbAliases = [Verbs::PUT => Verbs::POST, Verbs::MERGE => Verbs::PATCH];
     ArrayUtils::set($settings, "verbAliases", $verbAliases);
     parent::__construct($settings);
     $config = ArrayUtils::get($settings, 'config');
     $this->defaultRole = ArrayUtils::get($config, 'default_role');
     $this->setDriver($config);
 }
 /**
  * Retrieves records by id.
  *
  * @param integer $id
  * @param array   $related
  *
  * @return array
  */
 protected function retrieveById($id, array $related = [])
 {
     /** @var BaseSystemModel $modelClass */
     $modelClass = $this->model;
     $criteria = $this->getSelectionCriteria();
     $fields = ArrayUtils::get($criteria, 'select');
     $data = $modelClass::selectById($id, $related, $fields);
     return $data;
 }
Beispiel #22
0
 protected function setTransport($config)
 {
     $host = ArrayUtils::get($config, 'host');
     $port = ArrayUtils::get($config, 'port');
     $encryption = ArrayUtils::get($config, 'encryption');
     $username = ArrayUtils::get($config, 'username');
     $password = ArrayUtils::get($config, 'password');
     $this->transport = static::getTransport($host, $port, $encryption, $username, $password);
 }
 public static function validateConfig($config, $create = true)
 {
     if (null === ArrayUtils::get($config, 'dsn', null, true)) {
         if (null === ArrayUtils::getDeep($config, 'options', 'db', null, true)) {
             throw new BadRequestException('Database name must be included in the \'dsn\' or as an \'option\' attribute.');
         }
     }
     return true;
 }
 /**
  * Retrieves records by id.
  *
  * @param integer $id
  * @param array   $related
  *
  * @return array
  * @throws \DreamFactory\Core\Exceptions\NotFoundException
  */
 protected function retrieveById($id, array $related = [])
 {
     /** @var BaseSystemModel $modelClass */
     $modelClass = $this->model;
     $criteria = $this->getSelectionCriteria();
     $fields = ArrayUtils::get($criteria, 'select');
     if (empty($data = $modelClass::selectById($id, $related, $fields))) {
         throw new NotFoundException('Record not found');
     }
     return $data;
 }
Beispiel #25
0
 /**
  * Registers various available extensions to the v8 instance...
  *
  * @param array $engine_config
  * @param array $script_config
  *
  * @return ScriptingEngineInterface
  * @throws ServiceUnavailableException
  */
 public static function create(array $engine_config, $script_config = null)
 {
     $engineClass = ArrayUtils::get($engine_config, 'class_name');
     if (empty($engineClass) || !class_exists($engineClass)) {
         throw new ServiceUnavailableException("Failed to find script engine class '{$engineClass}'.");
     }
     $engine = new $engineClass($script_config);
     //  Stuff it in our instances array
     static::$instances[spl_object_hash($engine)] = $engine;
     return $engine;
 }
Beispiel #26
0
 /**
  * {@inheritdoc}
  */
 public function describeField($table, $field, $refresh = false)
 {
     $result = $this->describeTable($table);
     $fields = ArrayUtils::get($result, 'fields');
     if (empty($fields)) {
         foreach ($fields as $item) {
             if (ArrayUtils::get($item, 'name') == $field) {
                 return $item;
             }
         }
     }
     throw new NotFoundException("Field '{$field}' not found.");
 }
Beispiel #27
0
 /**
  * {@inheritdoc}
  */
 public function deleteTable($table, $check_empty = false)
 {
     $name = is_array($table) ? ArrayUtils::get($table, 'name') : $table;
     if (empty($name)) {
         throw new BadRequestException('Table name can not be empty.');
     }
     try {
         $this->parent->getConnection()->deleteTable($name);
         $this->refreshCachedTables();
         return array('name' => $name);
     } catch (\Exception $ex) {
         throw new InternalServerErrorException("Failed to delete table '{$name}'.\n{$ex->getMessage()}");
     }
 }
Beispiel #28
0
 /**
  * Checks to see if it is an admin user login call.
  *
  * @param  \Illuminate\Http\Request $request
  *
  * @return bool
  * @throws \DreamFactory\Core\Exceptions\NotImplementedException
  */
 protected static function isException($request)
 {
     /** @var Router $router */
     $router = app('router');
     $service = strtolower($router->input('service'));
     $resource = strtolower($router->input('resource'));
     $action = VerbsMask::toNumeric($request->getMethod());
     foreach (static::$exceptions as $exception) {
         if ($action & ArrayUtils::get($exception, 'verb_mask') && $service === ArrayUtils::get($exception, 'service') && $resource === ArrayUtils::get($exception, 'resource')) {
             return true;
         }
     }
     return false;
 }
Beispiel #29
0
 /** @inheritdoc */
 public function validate(array $data = [], $throwException = true)
 {
     if (empty($data)) {
         $data = $this->attributes;
     }
     if (parent::validate($data)) {
         $userId = ArrayUtils::get($data, 'user_id');
         $appId = ArrayUtils::get($data, 'app_id');
         if ($userId && $appId) {
             $model = $this->whereAppId($appId)->whereUserId($userId)->first();
             if (!empty($model) && $model->id !== ArrayUtils::get($data, 'id')) {
                 throw new BadRequestException('Multiple user-to-app-to-role assignment. You can only have a single user-to-app-to-role assignment.');
             }
         }
         return true;
     }
     return false;
 }
Beispiel #30
0
 /**
  * Run the database seeds.
  *
  * @throws \Exception
  */
 public function run()
 {
     BaseModel::unguard();
     if (empty($this->modelClass)) {
         throw new \Exception("Invalid seeder model. No value for {$this->modelClass}.");
     }
     /** @var BaseModel $modelName */
     $modelName = $this->modelClass;
     $created = [];
     $updated = [];
     $extras = $this->getRecordExtras();
     foreach ($this->records as $record) {
         $record = array_merge($record, $extras);
         /** @type \Illuminate\Database\Eloquent\Builder $builder */
         $builder = null;
         $name = '';
         if (!is_array($this->recordIdentifier)) {
             $name = ArrayUtils::get($record, $this->recordIdentifier);
             if (empty($name)) {
                 throw new \Exception("Invalid seeder record. No value for {$this->recordIdentifier}.");
             }
             $builder = $modelName::where($this->recordIdentifier, $name);
         } else {
             foreach ($this->recordIdentifier as $identifier) {
                 $id = ArrayUtils::get($record, $identifier);
                 if (empty($id)) {
                     throw new \Exception("Invalid seeder record. No value for {$identifier}.");
                 }
                 $builder = !$builder ? $modelName::where($identifier, $id) : $builder->where($identifier, $id);
                 $name .= empty($name) ? $id : ':' . $id;
             }
         }
         if (!$builder->exists()) {
             // seed the record
             $modelName::create($record);
             $created[] = $name;
         } elseif ($this->allowUpdate) {
             // update an existing record
             $builder->first()->update($record);
             $updated[] = $name;
         }
     }
     $this->outputMessage($created, $updated);
 }