/**
  * Connects to a Azure Blob Storage
  *
  * @param array $config Authentication configuration
  *
  * @throws InvalidArgumentException
  * @throws InternalServerErrorException
  * @throws \Exception
  */
 public function __construct($config)
 {
     $credentials = $config;
     $this->container = ArrayUtils::get($config, 'container');
     Session::replaceLookups($credentials, true);
     $connectionString = ArrayUtils::get($credentials, 'connection_string');
     if (empty($connectionString)) {
         $name = ArrayUtils::get($credentials, 'account_name', ArrayUtils::get($credentials, 'AccountName'));
         if (empty($name)) {
             throw new InvalidArgumentException('WindowsAzure account name can not be empty.');
         }
         $key = ArrayUtils::get($credentials, 'account_key', ArrayUtils::get($credentials, 'AccountKey'));
         if (empty($key)) {
             throw new InvalidArgumentException('WindowsAzure account key can not be empty.');
         }
         $protocol = ArrayUtils::get($credentials, 'protocol', 'https');
         $connectionString = "DefaultEndpointsProtocol={$protocol};AccountName={$name};AccountKey={$key}";
     }
     try {
         $this->blobConn = ServicesBuilder::getInstance()->createBlobService($connectionString);
         if (!$this->containerExists($this->container)) {
             $this->createContainer(['name' => $this->container]);
         }
     } catch (\Exception $ex) {
         throw new InternalServerErrorException("Windows Azure Blob Service Exception:\n{$ex->getMessage()}");
     }
 }
Example #2
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());
     }
 }
Example #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()}");
     }
 }
Example #4
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);
     }
 }
Example #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()}");
     }
 }
Example #6
0
 /**
  * @return string
  * @throws \DreamFactory\Core\Exceptions\UnauthorizedException
  */
 public static function refreshToken()
 {
     $token = Session::getSessionToken();
     try {
         $newToken = \JWTAuth::refresh($token);
         $payload = \JWTAuth::getPayload($newToken);
         $userId = $payload->get('user_id');
         $user = User::find($userId);
         $userInfo = $user->toArray();
         ArrayUtils::set($userInfo, 'is_sys_admin', $user->is_sys_admin);
         Session::setSessionToken($newToken);
         Session::setUserInfo($userInfo);
         static::setTokenMap($payload, $newToken);
     } catch (TokenExpiredException $e) {
         $payloadArray = \JWTAuth::manager()->getJWTProvider()->decode($token);
         $forever = boolval(ArrayUtils::get($payloadArray, 'forever'));
         if ($forever) {
             $userId = ArrayUtils::get($payloadArray, 'user_id');
             $user = User::find($userId);
             Session::setUserInfoWithJWT($user, $forever);
         } else {
             throw new UnauthorizedException($e->getMessage());
         }
     }
     return Session::getSessionToken();
 }
Example #7
0
 /**
  * Checks to see if there is a valid logged in user.
  * @throws \DreamFactory\Core\Exceptions\UnauthorizedException
  */
 private static function checkUser()
 {
     $userId = SessionUtility::getCurrentUserId();
     if (empty($userId)) {
         throw new UnauthorizedException('There is no valid session for the current request.');
     }
 }
Example #8
0
 /** @inheritdoc */
 protected function handlePOST()
 {
     if (!Session::isSysAdmin()) {
         throw new UnauthorizedException('You are not authorized to perform this action.');
     }
     return parent::handlePOST();
 }
Example #9
0
 public function testSystemLookupWithApiKey()
 {
     $app = App::find(1);
     $apiKey = $app->api_key;
     Lookup::create($this->systemLookup[0]);
     $this->call(Verbs::GET, '/api/v2/system/environment?api_key=' . $apiKey);
     $this->assertEquals(Arr::get($this->systemLookup, '0.value'), Session::get('lookup.host'));
 }
Example #10
0
 protected static function getApps()
 {
     if (SessionUtilities::isAuthenticated()) {
         $user = SessionUtilities::user();
         $defaultAppId = $user->default_app_id;
         if (SessionUtilities::isSysAdmin()) {
             $appGroups = AppGroupModel::with(['app_by_app_to_app_group' => function ($q) {
                 $q->whereIsActive(1)->whereNotIn('type', [AppTypes::NONE]);
             }])->get();
             $apps = AppModel::whereIsActive(1)->whereNotIn('type', [AppTypes::NONE])->get();
         } else {
             $userId = $user->id;
             $userAppRoles = UserAppRole::whereUserId($userId)->whereNotNull('role_id')->get(['app_id']);
             $appIds = [];
             foreach ($userAppRoles as $uar) {
                 $appIds[] = $uar->app_id;
             }
             $appIdsString = implode(',', $appIds);
             $appIdsString = empty($appIdsString) ? '-1' : $appIdsString;
             $typeString = implode(',', [AppTypes::NONE]);
             $typeString = empty($typeString) ? '-1' : $typeString;
             $appGroups = AppGroupModel::with(['app_by_app_to_app_group' => function ($q) use($appIdsString, $typeString) {
                 $q->whereRaw("(app.id IN ({$appIdsString}) OR role_id > 0) AND is_active = 1 AND type NOT IN ({$typeString})");
             }])->get();
             $apps = AppModel::whereRaw("(app.id IN ({$appIdsString}) OR role_id > 0) AND is_active = 1 AND type NOT IN ({$typeString})")->get();
         }
     } else {
         $appGroups = AppGroupModel::with(['app_by_app_to_app_group' => function ($q) {
             $q->where('role_id', '>', 0)->whereIsActive(1)->whereNotIn('type', [AppTypes::NONE]);
         }])->get();
         $apps = AppModel::whereIsActive(1)->where('role_id', '>', 0)->whereNotIn('type', [AppTypes::NONE])->get();
     }
     if (empty($defaultAppId)) {
         $systemConfig = SystemConfig::first(['default_app_id']);
         $defaultAppId = !empty($systemConfig) ? $systemConfig->default_app_id : null;
     }
     $inGroups = [];
     $groupedApps = [];
     $noGroupedApps = [];
     foreach ($appGroups as $appGroup) {
         $appArray = $appGroup->getRelation('app_by_app_to_app_group')->toArray();
         if (!empty($appArray)) {
             $appInfo = [];
             foreach ($appArray as $app) {
                 $inGroups[] = $app['id'];
                 $appInfo[] = static::makeAppInfo($app, $defaultAppId);
             }
             $groupedApps[] = ['id' => $appGroup->id, 'name' => $appGroup->name, 'description' => $appGroup->description, 'app' => $appInfo];
         }
     }
     /** @type AppModel $app */
     foreach ($apps as $app) {
         if (!in_array($app->id, $inGroups)) {
             $noGroupedApps[] = static::makeAppInfo($app->toArray(), $defaultAppId);
         }
     }
     return [$groupedApps, $noGroupedApps];
 }
Example #11
0
 /**
  * {@inheritdoc}
  */
 protected function handleGET()
 {
     if (!SessionUtility::isAuthenticated()) {
         throw new NotFoundException('No user session found.');
     }
     if (!SessionUtility::isSysAdmin()) {
         throw new UnauthorizedException('You are not authorized to perform this action.');
     }
     return parent::handleGET();
 }
Example #12
0
 public function testPATCHPassword()
 {
     $user = $this->createUser(1);
     Arr::set($user, 'password', '1234');
     $payload = json_encode($user, JSON_UNESCAPED_SLASHES);
     $rs = $this->makeRequest(Verbs::PATCH, static::RESOURCE . '/' . $user['id'], [], $payload);
     $content = $rs->getContent();
     $this->assertFalse(Session::authenticate(['email' => $user['email'], 'password' => '1234']));
     $this->assertTrue($this->adminCheck([$content]));
 }
Example #13
0
 public function handleOAuthCallback()
 {
     /** @var Provider $driver */
     $driver = $this->getDriver();
     /** @var User $user */
     $user = $driver->user();
     $dfUser = $this->createShadowOAuthUser($user);
     $dfUser->last_login_date = Carbon::now()->toDateTimeString();
     $dfUser->confirm_code = null;
     $dfUser->save();
     Session::setUserInfoWithJWT($dfUser);
     return Session::getPublicInfo();
 }
Example #14
0
 /**
  * Create a new Script Service
  *
  * @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);
     if (null === ($this->content = ArrayUtils::get($config, 'content', null, true))) {
         throw new \InvalidArgumentException('Script content can not be empty.');
     }
     if (null === ($this->engineConfig = ArrayUtils::get($config, 'engine', null, true))) {
         throw new \InvalidArgumentException('Script engine configuration can not be empty.');
     }
     $this->scriptConfig = ArrayUtils::clean(ArrayUtils::get($config, 'config', [], true));
 }
Example #15
0
 /**
  * Create a new MongoDbSvc
  *
  * @param array $settings
  *
  * @throws \InvalidArgumentException
  * @throws \Exception
  */
 public function __construct($settings = [])
 {
     parent::__construct($settings);
     static::checkExtensions(['mongo']);
     $config = ArrayUtils::clean(ArrayUtils::get($settings, 'config'));
     Session::replaceLookups($config, true);
     $dsn = strval(ArrayUtils::get($config, 'dsn'));
     if (!empty($dsn)) {
         if (0 != substr_compare($dsn, static::DSN_PREFIX, 0, static::DSN_PREFIX_LENGTH, true)) {
             $dsn = static::DSN_PREFIX . $dsn;
         }
     }
     $options = ArrayUtils::get($config, 'options', []);
     if (empty($options)) {
         $options = [];
     }
     $user = ArrayUtils::get($config, 'username');
     $password = ArrayUtils::get($config, 'password');
     // support old configuration options of user, pwd, and db in credentials directly
     if (!isset($options['username']) && isset($user)) {
         $options['username'] = $user;
     }
     if (!isset($options['password']) && isset($password)) {
         $options['password'] = $password;
     }
     if (!isset($options['db']) && null !== ($db = ArrayUtils::get($config, 'db', null, true))) {
         $options['db'] = $db;
     }
     if (!isset($db) && null === ($db = ArrayUtils::get($options, 'db', null, true))) {
         //  Attempt to find db in connection string
         $db = strstr(substr($dsn, static::DSN_PREFIX_LENGTH), '/');
         if (false !== ($pos = strpos($db, '?'))) {
             $db = substr($db, 0, $pos);
         }
         $db = trim($db, '/');
     }
     if (empty($db)) {
         throw new InternalServerErrorException("No MongoDb database selected in configuration.");
     }
     $driverOptions = ArrayUtils::clean(ArrayUtils::get($config, 'driver_options'));
     if (null !== ($context = ArrayUtils::get($driverOptions, 'context'))) {
         //  Automatically creates a stream from context
         $driverOptions['context'] = stream_context_create($context);
     }
     try {
         $client = @new \MongoClient($dsn, $options, $driverOptions);
         $this->dbConn = $client->selectDB($db);
     } catch (\Exception $ex) {
         throw new InternalServerErrorException("Unexpected MongoDb Service Exception:\n{$ex->getMessage()}");
     }
 }
Example #16
0
 public function testLogout()
 {
     Session::set('role.name', 'test');
     Session::set('role.id', 1);
     $user = $this->createUser(1);
     $payload = ['email' => $user['email'], 'password' => $this->user1['password']];
     $rs = $this->makeRequest(Verbs::POST, static::RESOURCE, [], $payload);
     $content = $rs->getContent();
     $this->assertTrue(!empty($content['session_id']));
     $rs = $this->makeRequest(Verbs::DELETE, static::RESOURCE);
     $content = $rs->getContent();
     $this->assertTrue($content['success']);
     $this->setExpectedException('\\DreamFactory\\Core\\Exceptions\\UnauthorizedException');
     $this->makeRequest(Verbs::GET, static::RESOURCE);
 }
Example #17
0
 public function testPOSTRegister()
 {
     $u = $this->user1;
     $password = Arr::get($u, 'password');
     $payload = ['first_name' => Arr::get($u, 'first_name'), 'last_name' => Arr::get($u, 'last_name'), 'name' => Arr::get($u, 'name'), 'email' => Arr::get($u, 'email'), 'phone' => Arr::get($u, 'phone'), 'security_question' => Arr::get($u, 'security_question'), 'security_answer' => Arr::get($u, 'security_answer'), 'password' => $password, 'password_confirmation' => Arr::get($u, 'password_confirmation', $password)];
     Session::setUserInfoWithJWT(User::find(1));
     $r = $this->makeRequest(Verbs::POST, static::RESOURCE, [], $payload);
     $c = $r->getContent();
     $this->assertTrue(Arr::get($c, 'success'));
     Session::set('role.name', 'test');
     Session::set('role.id', 1);
     $this->service = ServiceHandler::getService('user');
     $r = $this->makeRequest(Verbs::POST, 'session', [], ['email' => Arr::get($u, 'email'), 'password' => Arr::get($u, 'password')]);
     $c = $r->getContent();
     $this->assertTrue(!empty(Arr::get($c, 'session_id')));
 }
Example #18
0
 /**
  * Registers new user.
  *
  * @return array
  * @throws \DreamFactory\Core\Exceptions\BadRequestException
  * @throws \DreamFactory\Core\Exceptions\ForbiddenException
  */
 protected function handlePOST()
 {
     $payload = $this->getPayloadData();
     $login = $this->request->getParameterAsBool('login');
     $registrar = new Registrar();
     $password = ArrayUtils::get($payload, 'new_password', ArrayUtils::get($payload, 'password'));
     $data = ['first_name' => ArrayUtils::get($payload, 'first_name'), 'last_name' => ArrayUtils::get($payload, 'last_name'), 'name' => ArrayUtils::get($payload, 'name'), 'email' => ArrayUtils::get($payload, 'email'), 'phone' => ArrayUtils::get($payload, 'phone'), 'security_question' => ArrayUtils::get($payload, 'security_question'), 'security_answer' => ArrayUtils::get($payload, 'security_answer'), 'password' => $password, 'password_confirmation' => ArrayUtils::get($payload, 'password_confirmation', $password)];
     if (empty($data['first_name'])) {
         list($username, $domain) = explode('@', $data['email']);
         $data['first_name'] = $username;
     }
     if (empty($data['last_name'])) {
         $names = explode('.', $data['first_name']);
         if (isset($names[1])) {
             $data['last_name'] = $names[1];
             $data['first_name'] = $names[0];
         } else {
             $data['last_name'] = $names[0];
         }
     }
     if (empty($data['name'])) {
         $data['name'] = $data['first_name'] . ' ' . $data['last_name'];
     }
     ArrayUtils::removeNull($data);
     /** @var \Illuminate\Validation\Validator $validator */
     $validator = $registrar->validator($data);
     if ($validator->fails()) {
         $messages = $validator->errors()->getMessages();
         throw new BadRequestException('Validation failed', null, null, $messages);
     } else {
         $user = $registrar->create($data);
         if ($login) {
             if ($user->confirm_code !== 'y' && !is_null($user->confirm_code)) {
                 return ['success' => true, 'confirmation_required' => true];
             } else {
                 Session::setUserInfoWithJWT($user);
                 return ['success' => true, 'session_token' => Session::getSessionToken()];
             }
         } else {
             return ['success' => true];
         }
     }
 }
 /**
  * Send a copy of each incoming request out to the cluster logging system
  *
  * @param  \Illuminate\Http\Request $request
  * @param  \Closure                 $next
  *
  * @return mixed
  */
 public function handle($request, Closure $next)
 {
     try {
         try {
             $_session = Session::getPublicInfo();
         } catch (\Exception $_ex) {
             $_session = Session::all();
         }
         //  Register the auditing service
         app()->register(AuditServiceProvider::class);
         //  We use provider's service() method because Facades aren't loaded yet
         AuditServiceProvider::service()->logRequest($request, $_session);
     } catch (\Exception $_ex) {
         //  Completely ignored...
         /** @noinspection PhpUndefinedMethodInspection */
         Log::error('Exception during auditing: ' . $_ex->getMessage());
     }
     return $next($request);
 }
Example #20
0
 /**
  * Create a new AwsSnsSvc
  *
  * @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 the our supported version
     $config['version'] = '2010-03-31';
     if (isset($config['key'])) {
         $config['credentials']['key'] = $config['key'];
     }
     if (isset($config['secret'])) {
         $config['credentials']['secret'] = $config['secret'];
     }
     try {
         $this->conn = new SnsClient($config);
     } catch (\Exception $ex) {
         throw new InternalServerErrorException("AWS SNS Service Exception:\n{$ex->getMessage()}", $ex->getCode());
     }
     $this->region = ArrayUtils::get($config, 'region');
 }
Example #21
0
 /**
  * Updates user profile.
  *
  * @return array
  * @throws NotFoundException
  * @throws \Exception
  */
 protected function handlePOST()
 {
     $payload = $this->getPayloadData();
     $data = ['first_name' => ArrayUtils::get($payload, 'first_name'), 'last_name' => ArrayUtils::get($payload, 'last_name'), 'name' => ArrayUtils::get($payload, 'name'), 'email' => ArrayUtils::get($payload, 'email'), 'phone' => ArrayUtils::get($payload, 'phone'), 'security_question' => ArrayUtils::get($payload, 'security_question'), 'security_answer' => ArrayUtils::get($payload, 'security_answer'), 'default_app_id' => ArrayUtils::get($payload, 'default_app_id')];
     ArrayUtils::removeNull($data);
     $user = Session::user();
     if (empty($user)) {
         throw new NotFoundException('No user session found.');
     }
     $oldToken = Session::getSessionToken();
     $email = $user->email;
     $user->update($data);
     if (!empty($oldToken) && $email !== ArrayUtils::get($data, 'email', $email)) {
         // Email change invalidates token. Need to create a new token.
         $forever = JWTUtilities::isForever($oldToken);
         Session::setUserInfoWithJWT($user, $forever);
         $newToken = Session::getSessionToken();
         return ['success' => true, 'session_token' => $newToken];
     }
     return ['success' => true];
 }
Example #22
0
 /**
  * @param array $config
  *
  * @throws InternalServerErrorException
  */
 public function __construct($config)
 {
     //  Replace any private lookups
     Session::replaceLookups($config, true);
     // statically assign the our supported version
     $config['version'] = '2006-03-01';
     if (isset($config['key'])) {
         $config['credentials']['key'] = $config['key'];
     }
     if (isset($config['secret'])) {
         $config['credentials']['secret'] = $config['secret'];
     }
     try {
         $this->blobConn = new S3Client($config);
     } catch (\Exception $ex) {
         throw new InternalServerErrorException("AWS DynamoDb Service Exception:\n{$ex->getMessage()}", $ex->getCode());
     }
     $this->container = ArrayUtils::get($config, 'container');
     if (!$this->containerExists($this->container)) {
         $this->createContainer(['name' => $this->container]);
     }
 }
 public function testApiKeyUserRole()
 {
     $user = ['name' => 'John Doe', 'first_name' => 'John', 'last_name' => 'Doe', 'email' => '*****@*****.**', 'password' => 'test1234', 'security_question' => 'Make of your first car?', 'security_answer' => 'mazda', 'is_active' => true];
     $role = ['name' => 'test_role', 'is_active' => true, 'role_service_access_by_role_id' => [['service_id' => 1, 'component' => 'config', 'verb_mask' => 1, 'requestor_mask' => 1]]];
     $this->service = ServiceHandler::getService('system');
     $rs = $this->makeRequest(Verbs::POST, 'user', [], [$user]);
     $data = $rs->getContent();
     $userId = Arr::get($data, static::$wrapper . '.0.id');
     $this->service = ServiceHandler::getService('system');
     $rs = $this->makeRequest(Verbs::POST, 'role', [], [$role]);
     $data = $rs->getContent();
     $roleId = Arr::get($data, static::$wrapper . '.0.id');
     \DreamFactory\Core\Models\UserAppRole::create(['user_id' => $userId, 'app_id' => 1, 'role_id' => $roleId]);
     $app = App::find(1);
     $apiKey = $app->api_key;
     $myUser = User::find($userId);
     $token = JWTUtilities::makeJWTByUser($myUser->id, $myUser->email);
     $this->call(Verbs::GET, '/api/v2/system', [], [], [], ['HTTP_X_DREAMFACTORY_API_KEY' => $apiKey, 'HTTP_X_DREAMFACTORY_SESSION_TOKEN' => $token]);
     $this->assertFalse(Session::isSysAdmin());
     $this->assertEquals($roleId, Session::get('role.id'));
     $rsa = Session::get('role.services');
     $this->assertTrue(!empty($rsa));
 }
Example #24
0
 public function testPOSTProfile()
 {
     $user = $this->createUser(1);
     $userModel = User::find($user['id']);
     Session::setUserInfoWithJWT($userModel);
     $fName = 'Jack';
     $lName = 'Smith';
     $name = 'Jack';
     $email = '*****@*****.**';
     $this->user1['email'] = $email;
     $phone = '123-475-7383';
     $sQuestion = 'Foo?';
     $sAnswer = 'bar';
     $payload = ['first_name' => $fName, 'last_name' => $lName, 'name' => $name, 'email' => $email, 'phone' => $phone, 'security_question' => $sQuestion, 'security_answer' => $sAnswer];
     $r = $this->makeRequest(Verbs::POST, static::RESOURCE, [], $payload);
     $c = $r->getContent();
     $this->assertTrue(Arr::get($c, 'success'));
     $userModel = User::find($user['id']);
     $r = $this->makeRequest(Verbs::GET, static::RESOURCE);
     $c = $r->getContent();
     $this->assertTrue(Hash::check($sAnswer, $userModel->security_answer));
     unset($payload['security_answer']);
     $this->assertEquals($payload, $c);
 }
Example #25
0
 protected function check($service, $component = null, $requestor = ServiceRequestorTypes::API)
 {
     return Session::getServicePermissions($service, $component, $requestor);
 }
Example #26
0
 public static function forget($key)
 {
     \Session::forget($key);
 }
Example #27
0
 public static function buildPlatformAccess($identifier)
 {
     return ['api' => static::getExposedApi(), 'config' => \Config::all(), 'session' => Session::all(), 'store' => new ScriptSession(\Config::get("script.{$identifier}.store"), app('cache'))];
 }
Example #28
0
 /**
  * {@inheritdoc}
  */
 public static function deleteInternal($id, $record, $params = [])
 {
     if (empty($record)) {
         throw new BadRequestException('There are no fields in the record to create . ');
     }
     if (empty($id)) {
         //Todo:perform logging below
         //Log::error( 'Update request with no id supplied: ' . print_r( $record, true ) );
         throw new BadRequestException('Identifying field "id" can not be empty for update request . ');
     }
     /** @type User $model */
     $model = static::find($id);
     if (!$model instanceof Model) {
         throw new NotFoundException('No resource found for ' . $id);
     }
     try {
         if ($model->is_sys_admin && !ArrayUtils::getBool($params, 'admin')) {
             throw new ForbiddenException('Not allowed to delete an admin user.');
         } elseif (ArrayUtils::getBool($params, 'admin') && !$model->is_sys_admin) {
             throw new BadRequestException('Cannot delete a non-admin user.');
         } elseif (Session::getCurrentUserId() === $model->id) {
             throw new ForbiddenException('Cannot delete your account.');
         }
         $result = static::buildResult($model, $params);
         $model->delete();
         return $result;
     } catch (\Exception $ex) {
         if (!$ex instanceof ForbiddenException && !$ex instanceof BadRequestException) {
             throw new InternalServerErrorException('Failed to delete resource: ' . $ex->getMessage());
         } else {
             throw $ex;
         }
     }
 }
Example #29
0
 /**
  * @param       $id
  * @param       $record
  * @param array $params
  *
  * @return array
  * @throws \DreamFactory\Core\Exceptions\BadRequestException
  * @throws \DreamFactory\Core\Exceptions\InternalServerErrorException
  * @throws \DreamFactory\Core\Exceptions\NotFoundException
  */
 public static function deleteInternal($id, $record, $params = [])
 {
     if (empty($record)) {
         throw new BadRequestException('There are no fields in the record to create . ');
     }
     if (empty($id)) {
         //Todo:perform logging below
         //Log::error( 'Update request with no id supplied: ' . print_r( $record, true ) );
         throw new BadRequestException('Identifying field "id" can not be empty for update request . ');
     }
     $userId = SessionUtility::getCurrentUserId();
     $model = static::whereUserId($userId)->whereName($id)->first();
     if (!$model instanceof Model) {
         throw new NotFoundException('No resource found for ' . $id);
     }
     try {
         $result = static::buildResult($model, $params);
         $model->delete();
         return $result;
     } catch (\Exception $ex) {
         throw new InternalServerErrorException('Failed to delete resource: ' . $ex->getMessage());
     }
 }
Example #30
0
 /**
  * Performs login.
  *
  * @param array $credentials
  * @param bool  $remember
  *
  * @return array
  * @throws BadRequestException
  * @throws NotFoundException
  * @throws UnauthorizedException
  * @throws \Exception
  */
 protected function handleLogin(array $credentials = [], $remember = false)
 {
     $email = ArrayUtils::get($credentials, 'email');
     if (empty($email)) {
         throw new BadRequestException('Login request is missing required email.');
     }
     $password = ArrayUtils::get($credentials, 'password');
     if (empty($password)) {
         throw new BadRequestException('Login request is missing required password.');
     }
     $credentials['is_active'] = 1;
     // if user management not available then only system admins can login.
     if (!class_exists('\\DreamFactory\\Core\\User\\Resources\\System\\User')) {
         $credentials['is_sys_admin'] = 1;
     }
     if (Session::authenticate($credentials, $remember, true, static::getAppId())) {
         return Session::getPublicInfo();
     } else {
         throw new UnauthorizedException('Invalid credentials supplied.');
     }
 }