Пример #1
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'));
 }
Пример #2
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];
 }
Пример #3
0
 /**
  * Assigns a role to a user for all apps in the system.
  *
  * @param $user
  * @param $defaultRole
  *
  * @return bool
  * @throws \Exception
  */
 public static function applyDefaultUserAppRole($user, $defaultRole)
 {
     $apps = App::all();
     if (count($apps) === 0) {
         return false;
     }
     foreach ($apps as $app) {
         if (!UserAppRole::whereUserId($user->id)->whereAppId($app->id)->exists()) {
             $userAppRoleData = ['user_id' => $user->id, 'app_id' => $app->id, 'role_id' => $defaultRole];
             UserAppRole::create($userAppRoleData);
         }
     }
     return true;
 }
 public function index()
 {
     $uri = static::getURI($_SERVER);
     $dist = env('DF_INSTALL', '');
     if (empty($dist) && false !== stripos(env('DB_DATABASE', ''), 'bitnami')) {
         $dist = 'Bitnami';
     }
     $appCount = App::all()->count();
     $adminCount = User::whereIsSysAdmin(1)->count();
     $userCount = User::whereIsSysAdmin(0)->count();
     $serviceCount = Service::all()->count();
     $roleCount = Role::all()->count();
     $status = ["uri" => $uri, "managed" => env('DF_MANAGED', false), "dist" => $dist, "demo" => Environment::isDemoApplication(), "version" => \Config::get('df.version'), "host_os" => PHP_OS, "resources" => ["app" => $appCount, "admin" => $adminCount, "user" => $userCount, "service" => $serviceCount, "role" => $roleCount]];
     return ResponseFactory::sendResponse(ResponseFactory::create($status));
 }
Пример #5
0
 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));
 }
Пример #6
0
 public static function setSessionData($appId = null, $userId = null)
 {
     $appInfo = $appId ? App::getCachedInfo($appId) : null;
     $userInfo = $userId ? User::getCachedInfo($userId) : null;
     $roleId = null;
     if (!empty($userId) && !empty($appId)) {
         $roleId = static::getRoleIdByAppIdAndUserId($appId, $userId);
     }
     if (empty($roleId) && !empty($appInfo)) {
         $roleId = ArrayUtils::get($appInfo, 'role_id');
     }
     Session::setUserInfo($userInfo);
     Session::put('app.id', $appId);
     $roleInfo = $roleId ? Role::getCachedInfo($roleId) : null;
     if (!empty($roleInfo)) {
         Session::put('role.id', $roleId);
         Session::put('role.name', $roleInfo['name']);
         Session::put('role.services', $roleInfo['role_service_access_by_role_id']);
     }
     $systemLookup = Lookup::getCachedLookups();
     $systemLookup = !empty($systemLookup) ? $systemLookup : [];
     $appLookup = !empty($appInfo['app_lookup_by_app_id']) ? $appInfo['app_lookup_by_app_id'] : [];
     $roleLookup = !empty($roleInfo['role_lookup_by_role_id']) ? $roleInfo['role_lookup_by_role_id'] : [];
     $userLookup = !empty($userInfo['user_lookup_by_user_id']) ? $userInfo['user_lookup_by_user_id'] : [];
     $combinedLookup = LookupKey::combineLookups($systemLookup, $appLookup, $roleLookup, $userLookup);
     Session::put('lookup', ArrayUtils::get($combinedLookup, 'lookup'));
     Session::put('lookup_secret', ArrayUtils::get($combinedLookup, 'lookup_secret'));
 }
Пример #7
0
 /**
  * @return int|null
  */
 protected function getAppId()
 {
     $apiKey = AuthCheck::getApiKey($this->request->getDriver());
     if (!empty($apiKey)) {
         return App::getAppIdByApiKey($apiKey);
     }
     return null;
 }
Пример #8
0
 /**
  * Use this primarily in middle-ware or where no session is established yet.
  *
  * @param string $api_key
  *
  * @return int The app id
  */
 public static function getAppIdByApiKey($api_key)
 {
     $cacheKey = 'apikey2appid:' . $api_key;
     try {
         return \Cache::remember($cacheKey, \Config::get('df.default_cache_ttl'), function () use($api_key) {
             return App::whereApiKey($api_key)->firstOrFail()->id;
         });
     } catch (ModelNotFoundException $ex) {
         return null;
     }
 }
Пример #9
0
 /**
  * @param Request $request
  * @param Closure $next
  *
  * @return array|mixed|string
  */
 public function handle($request, Closure $next)
 {
     try {
         static::setExceptions();
         //Get the api key.
         $apiKey = static::getApiKey($request);
         Session::setApiKey($apiKey);
         $appId = App::getAppIdByApiKey($apiKey);
         //Get the JWT.
         $token = static::getJwt($request);
         Session::setSessionToken($token);
         //Get the Console API Key
         $consoleApiKey = static::getConsoleApiKey($request);
         //Check for basic auth attempt.
         $basicAuthUser = $request->getUser();
         $basicAuthPassword = $request->getPassword();
         if (config('df.managed') && !empty($consoleApiKey) && $consoleApiKey === Managed::getConsoleKey()) {
             //DFE Console request
             return $next($request);
         } elseif (!empty($basicAuthUser) && !empty($basicAuthPassword)) {
             //Attempting to login using basic auth.
             Auth::onceBasic();
             /** @var User $authenticatedUser */
             $authenticatedUser = Auth::user();
             if (!empty($authenticatedUser)) {
                 $userId = $authenticatedUser->id;
                 Session::setSessionData($appId, $userId);
             } else {
                 throw new UnauthorizedException('Unauthorized. User credentials did not match.');
             }
         } elseif (!empty($token)) {
             //JWT supplied meaning an authenticated user session/token.
             try {
                 JWTAuth::setToken($token);
                 /** @type Payload $payload */
                 $payload = JWTAuth::getPayload();
                 JWTUtilities::verifyUser($payload);
                 $userId = $payload->get('user_id');
                 Session::setSessionData($appId, $userId);
             } catch (TokenExpiredException $e) {
                 JWTUtilities::clearAllExpiredTokenMaps();
                 if (!static::isException($request)) {
                     throw new UnauthorizedException($e->getMessage());
                 }
             } catch (TokenBlacklistedException $e) {
                 throw new ForbiddenException($e->getMessage());
             } catch (TokenInvalidException $e) {
                 throw new BadRequestException('Invalid token: ' . $e->getMessage(), 401);
             }
         } elseif (!empty($apiKey)) {
             //Just Api Key is supplied. No authenticated session
             Session::setSessionData($appId);
         } elseif (static::isException($request)) {
             //Path exception.
             return $next($request);
         } else {
             throw new BadRequestException('Bad request. No token or api key provided.');
         }
         if (static::isAccessAllowed()) {
             return $next($request);
         } elseif (static::isException($request)) {
             //API key and/or (non-admin) user logged in, but if access is still not allowed then check for exception case.
             return $next($request);
         } else {
             if (!Session::isAuthenticated()) {
                 throw new UnauthorizedException('Unauthorized.');
             } else {
                 throw new ForbiddenException('Access Forbidden.');
             }
         }
     } catch (\Exception $e) {
         return ResponseFactory::getException($e, $request);
     }
 }
Пример #10
0
 /**
  * Deletes hosted app files from storage.
  *
  * @param $id
  * @param $storageServiceId
  * @param $storageFolder
  */
 protected static function deleteHostedAppStorage($id, $storageServiceId, $storageFolder)
 {
     $app = AppModel::whereId($id)->first();
     if (empty($app) && !empty($storageServiceId) && !empty($storageFolder)) {
         /** @type BaseFileService $storageService */
         $storageService = ServiceHandler::getServiceById($storageServiceId);
         if ($storageService->driver()->folderExists(null, $storageFolder)) {
             $storageService->driver()->deleteFolder(null, $storageFolder, true);
         }
     }
 }
Пример #11
0
 /**
  * @param Request  $request
  * @param \Closure $next
  *
  * @return array|mixed|string
  */
 public function handle(Request $request, \Closure $next)
 {
     if (!in_array($route = $request->getPathInfo(), ['/setup', '/setup_db'])) {
         try {
             $apiKey = static::getApiKey($request);
             Session::setApiKey($apiKey);
             $appId = App::getAppIdByApiKey($apiKey);
             //Get the JWT.
             $token = static::getJwt($request);
             Session::setSessionToken($token);
             //Check for basic auth attempt.
             $basicAuthUser = $request->getUser();
             $basicAuthPassword = $request->getPassword();
             if (!empty($basicAuthUser) && !empty($basicAuthPassword)) {
                 //Attempting to login using basic auth.
                 Auth::onceBasic();
                 /** @var User $authenticatedUser */
                 $authenticatedUser = Auth::user();
                 if (!empty($authenticatedUser)) {
                     $userId = $authenticatedUser->id;
                     Session::setSessionData($appId, $userId);
                 } else {
                     throw new UnauthorizedException('Unauthorized. User credentials did not match.');
                 }
             } elseif (!empty($token)) {
                 //JWT supplied meaning an authenticated user session/token.
                 /**
                  * Note: All caught exception from JWT are stored in session variables.
                  * These are later checked and handled appropriately in the AccessCheck middleware.
                  *
                  * This is to allow processing API calls that do not require any valid
                  * authenticated session. For example POST user/session to login,
                  * PUT user/session to refresh old JWT, GET system/environment etc.
                  *
                  * This also allows for auditing API calls that are called by not permitted/processed.
                  * It also allows counting unauthorized API calls against Enterprise Console limits.
                  */
                 try {
                     JWTAuth::setToken($token);
                     /** @type Payload $payload */
                     $payload = JWTAuth::getPayload();
                     JWTUtilities::verifyUser($payload);
                     $userId = $payload->get('user_id');
                     Session::setSessionData($appId, $userId);
                 } catch (TokenExpiredException $e) {
                     JWTUtilities::clearAllExpiredTokenMaps();
                     Session::set('token_expired', true);
                     Session::set('token_expired_msg', $e->getMessage());
                 } catch (TokenBlacklistedException $e) {
                     Session::set('token_blacklisted', true);
                     Session::set('token_blacklisted_msg', $e->getMessage());
                 } catch (TokenInvalidException $e) {
                     Session::set('token_invalid', true);
                     Session::set('token_invalid_msg', 'Invalid token: ' . $e->getMessage());
                 }
             } elseif (!empty($apiKey)) {
                 //Just Api Key is supplied. No authenticated session
                 Session::setSessionData($appId);
             }
             return $next($request);
         } catch (\Exception $e) {
             return ResponseFactory::getException($e, $request);
         }
     }
     return $next($request);
 }
Пример #12
0
 /**
  * @param bool|true  $includeFiles
  * @param bool|false $includeData
  *
  * @return null
  * @throws \DreamFactory\Core\Exceptions\NotFoundException
  * @throws \Exception
  */
 public function exportAppAsPackage($includeFiles = true, $includeData = false)
 {
     /** @type App $app */
     $app = App::find($this->exportAppId);
     if (empty($app)) {
         throw new NotFoundException('App not found in database with app id - ' . $this->exportAppId);
     }
     $appName = $app->name;
     try {
         $this->initExportZipFile($appName);
         $this->packageAppDescription($app);
         $this->packageServices();
         $this->packageSchemas();
         if ($includeData) {
             $this->packageData();
         }
         if ($app->type === AppTypes::STORAGE_SERVICE && $includeFiles) {
             $this->packageAppFiles($app);
         }
         $this->zip->close();
         FileUtilities::sendFile($this->zipFilePath, true);
         return null;
     } catch (\Exception $e) {
         //Do necessary things here.
         throw $e;
     }
 }
Пример #13
0
 /**
  * @param Request  $request
  * @param \Closure $next
  *
  * @return array|mixed|string
  */
 public function handle(Request $request, \Closure $next)
 {
     if (!in_array($route = $request->getPathInfo(), ['/setup', '/setup_db'])) {
         try {
             $apiKey = static::getApiKey($request);
             Session::setApiKey($apiKey);
             $appId = App::getAppIdByApiKey($apiKey);
             //Get the JWT.
             $token = static::getJwt($request);
             Session::setSessionToken($token);
             //Check for basic auth attempt.
             $basicAuthUser = $request->getUser();
             $basicAuthPassword = $request->getPassword();
             if (!empty($basicAuthUser) && !empty($basicAuthPassword)) {
                 //Attempting to login using basic auth.
                 Auth::onceBasic();
                 /** @var User $authenticatedUser */
                 $authenticatedUser = Auth::user();
                 if (!empty($authenticatedUser)) {
                     $userId = $authenticatedUser->id;
                     Session::setSessionData($appId, $userId);
                 } else {
                     throw new UnauthorizedException('Unauthorized. User credentials did not match.');
                 }
             } elseif (!empty($token)) {
                 //JWT supplied meaning an authenticated user session/token.
                 try {
                     JWTAuth::setToken($token);
                     /** @type Payload $payload */
                     $payload = JWTAuth::getPayload();
                     JWTUtilities::verifyUser($payload);
                     $userId = $payload->get('user_id');
                     Session::setSessionData($appId, $userId);
                 } catch (TokenExpiredException $e) {
                     JWTUtilities::clearAllExpiredTokenMaps();
                     Session::set('token_expired', true);
                     Session::set('token_expired_msg', $e->getMessage());
                 } catch (TokenBlacklistedException $e) {
                     throw new ForbiddenException($e->getMessage());
                 } catch (TokenInvalidException $e) {
                     throw new BadRequestException('Invalid token: ' . $e->getMessage(), 401);
                 }
             } elseif (!empty($apiKey)) {
                 //Just Api Key is supplied. No authenticated session
                 Session::setSessionData($appId);
             }
             return $next($request);
         } catch (\Exception $e) {
             return ResponseFactory::getException($e, $request);
         }
     }
     return $next($request);
 }