Example #1
2
 public static function upload(UploadedFile $file, $user, $contest = null)
 {
     $entry = new static();
     DB::transaction(function () use($entry, $file, $user, $contest) {
         $entry->save();
         // get id
         $entry->user()->associate($user);
         $entry->contest()->associate($contest);
         $entry->filesize = $file->getClientSize();
         $entry->original_filename = $file->getClientOriginalName();
         $entry->storeFile($file->getRealPath(), $file->getClientOriginalExtension());
         $entry->save();
     });
     return $entry;
 }
Example #2
0
 /**
  * Unauthorizes current user.
  *
  * @return void
  */
 public static function unauthorize()
 {
     Session::forget('auth.authorized');
     Session::forget('auth.user');
     static::$authorized = false;
     static::$user = null;
 }
 public static function configure(array $db_config)
 {
     static::$dsn = "mysql:host=" . $db_config['host'] . ";dbname=" . $db_config['name'];
     static::$user = $db_config['user'];
     static::$pass = $db_config['pass'];
     static::$configured = true;
 }
Example #4
0
 /** 
  * Main function for initialize this class.
  * @param \Slim\Slim
  */
 public static function init()
 {
     date_default_timezone_set(static::config()->timezone);
     static::$db = static::config()->db;
     static::$user = new \ptejada\uFlex\User();
     static::$app = new \Slim\Slim();
     static::$mail = new \PHPMailer();
     static::$assets = new \Assets();
     static::$user->config->database->host = static::config()->db['server'];
     static::$user->config->database->user = static::config()->db['username'];
     static::$user->config->database->password = static::config()->db['password'];
     static::$user->config->database->name = static::config()->db['database_name'];
     static::$user->start();
     require 'app/config/mail.php';
     static::$mail->isSMTP();
     static::$mail->Host = $mail['Host'];
     static::$mail->SMTPAuth = $mail['SMTPAuth'];
     static::$mail->Username = $mail['Username'];
     static::$mail->Password = $mail['Password'];
     static::$mail->SMTPSecure = $mail['SMTPSecure'];
     static::$mail->Port = $mail['Port'];
     static::$mail->From = $mail['From'];
     static::$mail->FromName = $mail['FromName'];
     static::$mail->isHTML(true);
 }
Example #5
0
 /**
  * @return string
  */
 public static function getUser()
 {
     if (static::$user) {
         return static::$user;
     }
     static::notLoadException();
     return static::$user = posix_getlogin();
 }
Example #6
0
 public static function set()
 {
     if (Request::getStorage('user')) {
         return static::$user = Request::getStorage('user');
     } else {
         Debug::output(new Exception("不存在Request Storage内的user"));
     }
 }
Example #7
0
 function _init()
 {
     require_once dirname(__FILE__) . '/base_facebook.php';
     require_once dirname(__FILE__) . '/facebook.php';
     \Config::load('facebook::facebook', 'facebook');
     static::$instance = new Facebook(array('appId' => \Config::get('facebook.app_id'), 'secret' => \Config::get('facebook.secret')));
     static::$user = static::$instance->getUser();
 }
Example #8
0
 /**
  * Get user object
  *
  * @return object
  */
 public static function user()
 {
     if (!static::$user and static::$factory) {
         $id = static::provider()->get('id');
         static::$user = call_user_func(static::$factory, $id);
     }
     return static::$user;
 }
Example #9
0
File: User.php Project: arhone/cmf
 public function __construct(Cookie $Cookie, \PDO $PDO, array $config = [])
 {
     $this->Cookie = $Cookie;
     $this->DB = $PDO;
     $this->mergeConfig($config);
     if (empty(static::$user)) {
         static::$user = array_merge($this->guest, $this->authByKey($this->Cookie->get('arh.user.key')));
     }
 }
Example #10
0
 public static function login($user, $password)
 {
     $users = (require Path::getConfigDir() . '/passwd.php');
     if (!isset($users[$user])) {
         throw new AuthenticationError('Incorrect user credentials');
     }
     if (!password_verify($users[$user]['password'], $password)) {
         throw new AuthenticationError('Incorrect user credentials');
     }
     static::$user = new User($user, $users[$user]['groups']);
 }
Example #11
0
 /**
  * Resets all the mock variables to their default value
  */
 public function reset()
 {
     static::$isCli = false;
     static::$isAdmin = false;
     static::$template = null;
     static::$templateSuffixes = null;
     static::$baseDirs = null;
     static::$user = null;
     static::$uriBase = null;
     static::$authorise = null;
     static::$runPlugins = null;
     static::$getUserStateFromRequest = null;
 }
Example #12
0
 public static function upload($filePath, $user, $forum = null)
 {
     $cover = new static();
     DB::transaction(function () use($cover, $filePath, $user, $forum) {
         $cover->save();
         // get id
         $cover->user()->associate($user);
         $cover->forum()->associate($forum);
         $cover->storeFile($filePath);
         $cover->save();
     });
     return $cover;
 }
Example #13
0
 public function setUp()
 {
     parent::setUp();
     if (!is_object(static::$sm)) {
         static::$sm = $this->serviceLocator;
     }
     if (!is_object(static::$user)) {
         $this->loginAsUser();
         static::$user = $this->activeUser;
     } else {
         $this->activeUser = static::$user;
     }
 }
Example #14
0
 /**
  * {@inheritdoc}
  */
 public static function doSetUpBeforeClass()
 {
     static::$schemaTool = new SchemaTool(static::$em);
     static::$schemaTool->dropSchema(static::getTablesMetadata());
     static::$schemaTool->createSchema(static::getTablesMetadata());
     static::$encoder = static::$container->get('security.encoder_factory');
     static::$user = new User();
     static::$user->setEmail('*****@*****.**');
     static::$user->setPassword(static::$encoder->getEncoder(static::$user)->encodePassword('1234', static::$user->getSalt()));
     static::$user->setUsername('testUser');
     $entityPermissionCategory = new PermissionCategory();
     $entityPermissionCategory->setName('backend_user');
     $entityPermissionCategory->setTechnicalName('backend_user');
     static::$em->persist($entityPermissionCategory);
     $entityPermission = new Permission();
     $entityPermission->setRoleName('IS_AUTHENTICATED_FULLY');
     $entityPermission->setDescription('IS_AUTHENTICATED_FULLY');
     $entityPermission->setName('IS_AUTHENTICATED_FULLY');
     $entityPermission->setCategory($entityPermissionCategory);
     $entityPermission2 = new Permission();
     $entityPermission2->setRoleName('ROLE_MANAGE_PERMISSIONS');
     $entityPermission2->setDescription('ROLE_MANAGE_PERMISSIONS');
     $entityPermission2->setName('ROLE_MANAGE_PERMISSIONS');
     $entityPermission2->setCategory($entityPermissionCategory);
     $entityPermission3 = new Permission();
     $entityPermission3->setRoleName('ROLE_ACCESS_BACKEND_TOOLS_SECURITY_SECTION');
     $entityPermission3->setDescription('ROLE_ACCESS_BACKEND_TOOLS_SECURITY_SECTION');
     $entityPermission3->setName('ROLE_ACCESS_BACKEND_TOOLS_SECURITY_SECTION');
     $entityPermission3->setCategory($entityPermissionCategory);
     $entityPermission4 = new Permission();
     $entityPermission4->setRoleName('ROLE_MANAGE_USER_PROFILES');
     $entityPermission4->setDescription('ROLE_MANAGE_USER_PROFILES');
     $entityPermission4->setName('ROLE_MANAGE_USER_PROFILES');
     $entityPermission4->setCategory($entityPermissionCategory);
     static::$em->persist($entityPermission);
     static::$em->persist($entityPermission2);
     static::$em->persist($entityPermission3);
     static::$em->persist($entityPermission4);
     static::$em->flush();
     $group = new Group();
     $group->setRefName('BACKEND-USER');
     $group->setName('backend-user');
     $group->addPermission($entityPermission);
     $group->addPermission($entityPermission2);
     $group->addPermission($entityPermission3);
     $group->addPermission($entityPermission4);
     static::$user->addToGroup($group);
     static::$em->persist($group);
     static::$em->persist(static::$user);
     static::$em->flush();
 }
 /**
  * Check access
  *
  * @return bool
  * @throws RestException
  */
 public function __isAllowed()
 {
     global $db;
     $stored_key = '';
     $userClass = Defaults::$userIdentifierClass;
     if (isset($_GET['api_key'])) {
         $sql = "SELECT u.login, u.datec, u.api_key, ";
         $sql .= " u.tms as date_modification, u.entity";
         $sql .= " FROM " . MAIN_DB_PREFIX . "user as u";
         $sql .= " WHERE u.api_key = '" . $db->escape($_GET['api_key']) . "'";
         $result = $db->query($sql);
         if ($result) {
             if ($db->num_rows($result)) {
                 $obj = $db->fetch_object($result);
                 $login = $obj->login;
                 $stored_key = $obj->api_key;
             }
         } else {
             throw new RestException(503, 'Error when fetching user api_key :' . $db->error_msg);
         }
         if ($stored_key != $_GET['api_key']) {
             $userClass::setCacheIdentifier($_GET['api_key']);
             return false;
         }
         $fuser = new User($db);
         if (!$fuser->fetch('', $login)) {
             throw new RestException(503, 'Error when fetching user :'******'external';
         }
         if ($fuser->admin) {
             static::$role = 'admin';
         }
     } else {
         return false;
     }
     $userClass::setCacheIdentifier(static::$role);
     Resources::$accessControlFunction = 'DolibarrApiAccess::verifyAccess';
     return in_array(static::$role, (array) static::$requires) || static::$role == 'admin';
 }
 public static function setUpBeforeClass()
 {
     parent::setUpBeforeClass();
     SecurityTestHelper::createSuperAdmin();
     static::$user = User::getByUsername('super');
     Yii::app()->user->userModel = static::$user;
     $contact = ContactTestHelper::createContactByNameForOwner('contact 01', static::$user);
     $marketingList = MarketingListTestHelper::createMarketingListByName('marketingList 01', 'description 01', 'fromName 01', '*****@*****.**');
     $autoresponder = AutoresponderTestHelper::createAutoresponder('subject 01', 'textContent 01', 'htmlContent 01', 10, Autoresponder::OPERATION_SUBSCRIBE, 1, $marketingList);
     $processed = 0;
     $processDateTime = DateTimeUtil::convertTimestampToDbFormatDateTime(time() - 100);
     $autoresponderItem = AutoresponderItemTestHelper::createAutoresponderItem($processed, $processDateTime, $autoresponder, $contact);
     static::$personId = $contact->getClassId('Person');
     static::$autoresponderItemId = $autoresponderItem->id;
     $campaign = CampaignTestHelper::createCampaign('campaign 01', 'subject 01', 'text Content 01', 'html Content 01', 'fromName 01', '*****@*****.**', null, Campaign::STATUS_ACTIVE, null, null, $marketingList);
     $processed = 0;
     $campaignItem = CampaignItemTestHelper::createCampaignItem($processed, $campaign, $contact);
     static::$campaignItemId = $campaignItem->id;
     AllPermissionsOptimizationUtil::rebuild();
 }
Example #17
0
 /**
  * Generate data for ApiTestCaseV2
  *
  * @param string $fixtures patch to fixtures directory
  * @return array
  * @throws \Scalr\System\Config\Exception\YamlException
  */
 public static function dataFixtures($fixtures)
 {
     // set config
     static::$testUserId = \Scalr::config('scalr.phpunit.userid');
     static::$user = User::findPk(static::$testUserId);
     static::$testEnvId = \Scalr::config('scalr.phpunit.envid');
     static::$env = Environment::findPk(static::$testEnvId);
     $data = [];
     foreach (new DirectoryIterator($fixtures) as $fileInfo) {
         if ($fileInfo->isFile()) {
             $class = __NAMESPACE__ . '\\' . ucfirst($fileInfo->getBasename('.yaml'));
             if (class_exists($class)) {
                 /* @var $object TestDataFixtures */
                 $object = new $class(Yaml::load($fileInfo->getPathname())->toArray());
                 $object->prepareTestData();
                 $data = array_merge($data, $object->preparePathInfo());
             }
         }
     }
     return $data;
 }
Example #18
0
 public static function run($config)
 {
     if (isset($config['db'])) {
         if (isset($config['db']['username'])) {
             static::$db = new DB($config['db']['dsn'], $config['db']['username'], $config['db']['password']);
         } else {
             static::$db = new DB($config['db']['dsn']);
         }
     }
     static::$assets = new Assets(isset($config['assets']) ? $config['assets'] : []);
     static::$user = new User();
     static::$url = new Url();
     static::$request = new Request();
     static::$session = new Session();
     static::$helper = new Helper();
     static::$params = $config['params'];
     $url = str_replace(static::$url->path(), '', $_SERVER['REQUEST_URI']);
     $options = isset($config['route']) ? $config['route'] : [];
     static::$route = new Route($url, $options);
     static::$route->run();
 }
Example #19
0
 /**
  *  Settings Connection Data
  * 
  * @param  array $args
  * @return void
  */
 public static function setting($args)
 {
     static::$host = $args['host'];
     static::$user = $args['user'];
     static::$pass = $args['pass'];
     static::$name = $args['name'];
 }
Example #20
0
 /**
  * Function to fetch the user JSON and render it
  *
  * @return  void
  *
  * @since   1.5
  */
 protected function prepareUser()
 {
     $scheme = $this->scheme . '://';
     // Load the parameters
     $uname = $this->params->get('twitterName', '');
     $list = $this->params->get('twitterList', '');
     $feed = $this->params->get('twitterFeedType', 'user');
     // Initialize object containers
     $this->twitter['header'] = new stdClass();
     $this->twitter['footer'] = new stdClass();
     $this->twitter['tweets'] = new stdClass();
     // Convert the list name to a usable string for the URL
     if ($list) {
         $flist = static::toAscii($list);
     }
     // Retrieve data from Twitter if the header is enabled
     if ($this->params->get('headerDisplay', 1) == 1) {
         // Sanity check on user file cache
         $cacheFile = JPATH_CACHE . '/tweetdisplayback_user-' . $this->moduleId . '.json';
         $cacheTime = $this->params->get('cache_time', 15);
         $cacheTime = $cacheTime * 60;
         // Get the data
         if ($this->isCached && (!file_exists($cacheFile) || time() - @filemtime($cacheFile) > $cacheTime)) {
             // Fetch from cache
             $obj = file_get_contents(JPATH_CACHE . '/tweetdisplayback_user-' . $this->moduleId . '.json');
             $obj = json_decode($obj);
         } else {
             $req = 'https://api.twitter.com/1.1/users/show.json?screen_name=' . $uname;
             try {
                 $obj = $this->getJSON($req);
             } catch (RuntimeException $e) {
                 $this->twitter['error'] = '';
                 return;
             }
             // Check if we've reached an error
             if (isset($obj->errors)) {
                 $this->twitter['error'] = array();
                 $this->twitter['error']['messages'] = array();
                 foreach ($obj->errors as $error) {
                     $this->twitter['error']['messages'][] = $error->message;
                 }
                 return;
             } elseif (!$obj) {
                 $this->twitter['error'] = '';
                 return;
             }
             // Store the user profile response object so it can be accessed (for advanced use)
             static::$user = $obj;
             // If caching is enabled and we aren't using cached data, json_encode the object and write it to file
             if ($this->params->get('cache') == 1 && !$this->isCached) {
                 $data = json_encode($obj);
                 file_put_contents(JPATH_CACHE . '/tweetdisplayback_user-' . $this->moduleId . '.json', $data);
             }
         }
         /*
          * Header info
          */
         if ($this->params->get('headerUser', 1) == 1) {
             // Check if the Intents action is bypassed
             if ($this->params->get('bypassIntent', '0') == 1) {
                 $this->twitter['header']->user = '******' . $scheme . 'twitter.com/' . $uname . '" rel="nofollow" target="_blank">';
             } else {
                 $this->twitter['header']->user = '******' . $scheme . 'twitter.com/intent/user?screen_name=' . $uname . '" rel="nofollow">';
             }
             // Show the real name or the username
             if ($this->params->get('headerName', 1) == 1) {
                 $this->twitter['header']->user .= $obj->name . '</a>';
             } else {
                 $this->twitter['header']->user .= $uname . '</a>';
             }
             // Append the list name if being pulled
             if ($feed == 'list') {
                 $this->twitter['header']->user .= ' - <a href="' . $scheme . 'twitter.com/' . $uname . '/' . $flist . '" rel="nofollow">' . $list . ' list</a>';
             }
         }
         // Show the bio
         if ($this->params->get('headerBio', 1) == 1) {
             $this->twitter['header']->bio = $obj->description;
         }
         // Show the location
         if ($this->params->get('headerLocation', 1) == 1) {
             $this->twitter['header']->location = $obj->location;
         }
         // Show the user's URL
         if ($this->params->get('headerWeb', 1) == 1) {
             $this->twitter['header']->web = '<a href="' . $obj->url . '" rel="nofollow" target="_blank">' . $obj->url . '</a>';
         }
         // Get the profile image URL from the object
         $avatar = $this->scheme == 'https' ? $obj->profile_image_url_https : $obj->profile_image_url;
         // Switch from the normal size avatar (48px) to the large one (73px)
         $avatar = str_replace('normal.jpg', 'bigger.jpg', $avatar);
         $this->twitter['header']->avatar = '<img src="' . $avatar . '" alt="' . $uname . '" />';
     }
     /*
      * Footer info
      */
     // Display the Follow button
     if ($this->params->get('footerFollowLink', 1) == 1) {
         // Don't display for a list feed
         if ($feed != 'list') {
             $followParams = 'screen_name=' . $uname;
             $followParams .= '&amp;lang=' . substr(JFactory::getLanguage()->getTag(), 0, 2);
             if ($this->params->get('footerFollowCount', '1') == '1') {
                 $followParams .= '&amp;show_count=true';
             } else {
                 $followParams .= '&amp;show_count=false';
             }
             $followParams .= '&amp;show_screen_name=' . (bool) $this->params->get('footerFollowUser', 1);
             $iframe = '<iframe allowtransparency="true" frameborder="0" scrolling="no" src="' . $scheme . 'platform.twitter.com/widgets/follow_button.html?' . $followParams . '" style="width: 300px; height: 20px;"></iframe>';
             $this->twitter['footer']->follow_me = '<div class="TDB-footer-follow-link">' . $iframe . '</div>';
         }
     }
     if ($this->params->get('footerPoweredBy', 1) == 1) {
         $site = '<a href="https://www.babdev.com/extensions/tweet-display-back" rel="nofollow" target="_blank">' . JText::_('MOD_TWEETDISPLAYBACK') . '</a>';
         $this->twitter['footer']->powered_by = '<hr /><div class="TDB-footer-powered-text">' . JText::sprintf('MOD_TWEETDISPLAYBACK_POWERED_BY', $site) . '</div>';
     }
 }
Example #21
0
 /**
  * User login process by user id
  *
  * @param int $userId
  *
  * @return bool
  */
 public static function loginByUserId($userId, $remember = false)
 {
     static::resetCheckVariables();
     if (static::check() === true || $userId == null) {
         return static::getInstance();
     }
     $result = static::$model->getIdentityWithId($userId);
     if (count($result) > 0) {
         static::$user = static::resolveDbResult($result);
         if (isset(static::$user) && is_array(static::$user)) {
             static::$rememberMe = $remember;
             static::$processResult = true;
             static::status();
         }
     }
     return static::getInstance();
 }
Example #22
0
 public static function load($user)
 {
     static::$user = $user;
     static::rebuild($user);
 }
Example #23
0
 /**
  * Get current authenticated user
  * 
  * @return User
  */
 public static function user()
 {
     if (!isset(static::$user)) {
         $uid = static::getCurrentUserId();
         if ($uid) {
             static::$user = static::fetchUserById($uid);
         }
     }
     return static::$user;
 }
Example #24
0
 public function testRegister()
 {
     $this->init();
     $this->clean();
     $formToken = self::$security->getToken(RegisterType::token);
     // Empty data without token
     $response = self::$service->register([]);
     $this->assertFalse($response['valid']);
     $this->assertEmpty($response['errors']);
     // Empty data with token
     $response = self::$service->register(['_token' => $formToken]);
     $this->assertFalse($response['valid']);
     $this->assertArrayHasKey('username', $response['errors']);
     $this->assertArrayHasKey('email', $response['errors']);
     $this->assertArrayHasKey('plainPassword', $response['errors']);
     // Username too short (< 3)
     $response = self::$service->register(['username' => 'pi', '_token' => $formToken]);
     $this->assertFalse($response['valid']);
     $this->assertArrayHasKey('username', $response['errors']);
     // Username too long (> 16)
     $response = self::$service->register(['username' => 'pixocode_pixocode', '_token' => $formToken]);
     $this->assertFalse($response['valid']);
     $this->assertArrayHasKey('username', $response['errors']);
     // Username with special characters
     foreach (['@', 'é', '%', '=', '+', '\\', '"'] as $character) {
         $response = self::$service->register(['username' => self::$data['username'] . $character, 'email' => self::$data['email'], 'plainPassword' => self::$data['password'], '_token' => $formToken]);
         $this->assertFalse($response['valid']);
         $this->assertArrayHasKey('username', $response['errors']);
     }
     // Incorrect email
     $response = self::$service->register(['username' => self::$data['username'], 'email' => 'pixocode', 'plainPassword' => self::$data['password'], '_token' => $formToken]);
     $this->assertFalse($response['valid']);
     $this->assertArrayHasKey('email', $response['errors']);
     // Not exist email domain
     $response = self::$service->register(['username' => self::$data['username'], 'email' => '*****@*****.**', 'plainPassword' => self::$data['password'], '_token' => $formToken]);
     $this->assertFalse($response['valid']);
     $this->assertArrayHasKey('email', $response['errors']);
     // Too much field
     $response = self::$service->register(['username' => self::$data['username'], 'email' => self::$data['email'], 'plainPassword' => self::$data['password'], 'toto' => 'toto', '_token' => $formToken]);
     $this->assertFalse($response['valid']);
     $this->assertArrayHasKey('#', $response['errors']);
     // Bad token
     $response = self::$service->register(['username' => self::$data['username'], 'email' => self::$data['email'], 'plainPassword' => self::$data['password'], 'locale' => 'fr', '_token' => 'test']);
     $this->assertFalse($response['valid']);
     $this->assertArrayHasKey('#', $response['errors']);
     // Success registration
     $response = self::$service->register(['username' => self::$data['username'], 'email' => self::$data['email'], 'plainPassword' => self::$data['password'], 'locale' => 'fr', '_token' => $formToken]);
     $this->assertTrue($response['valid']);
     $this->assertArraySubset(['username' => self::$data['username']], $response['embedded']['user']);
     // Another user
     $response = self::$service->register(['username' => 'toto', 'email' => '*****@*****.**', 'plainPassword' => self::$data['password'], 'locale' => 'fr', '_token' => $formToken]);
     $this->assertTrue($response['valid']);
     static::$user = self::$doctrine->getRepository('CoreUserBundle:User')->findOneByUsername(self::$data['username']);
 }
Example #25
0
 public static function connect($database = false)
 {
     if (!static::$server && !static::$db) {
         if (!!$database) {
             $_mysql = $database;
         } else {
             $config = Config::get('mysql');
         }
         static::$server = $config->server;
         static::$db = $config->dbname;
         static::$user = $config->username;
         static::$pass = $config->password;
     }
     if (!static::$connection) {
         $c = @mysql_connect(static::$server, static::$user, static::$pass);
         if (!$c) {
             static::showError('Error : Connection failed : ' . mysql_error());
         }
         if (!mysql_select_db(static::$db, $c)) {
             static::showError('Error : Selection database failed : ' . mysql_error());
         }
         static::$connection = $c;
     }
 }
Example #26
0
 /**
  * Log the current user out of the application.
  *
  * The "logout" closure in the authenciation configuration file will be
  * called. All authentication cookies will be deleted and the user ID
  * will be removed from the session.
  *
  * @return void
  */
 public static function logout()
 {
     call_user_func(Config::get('auth.logout'), static::user());
     static::$user = null;
     Cookie::forget(Auth::user_key);
     Cookie::forget(Auth::remember_key);
     IoC::core('session')->forget(Auth::user_key);
 }
Example #27
0
 /**
  * Setups test user, environment and API key
  *
  * @throws \Scalr\Exception\ModelException
  */
 public static function setUpBeforeClass()
 {
     static::$testUserId = \Scalr::config('scalr.phpunit.userid');
     static::$user = User::findPk(static::$testUserId);
     static::$testEnvId = \Scalr::config('scalr.phpunit.envid');
     static::$env = Environment::findPk(static::$testEnvId);
     if (empty(static::$user) || empty(static::$env)) {
         static::markTestIncomplete('Either test environment or user is invalid.');
     }
     $apiKeyName = static::getTestName();
     $apiKeyEntity = ApiKeyEntity::findOne([['name' => $apiKeyName], ['userId' => static::$testUserId]]);
     if (empty($apiKeyEntity)) {
         $apiKeyEntity = new ApiKeyEntity(static::$testUserId);
         $apiKeyEntity->name = $apiKeyName;
         $apiKeyEntity->save();
     }
     static::$apiKeyEntity = $apiKeyEntity;
     static::changeLoggerConfiguration();
 }
Example #28
0
 /**
  * Sets database connection settings as properties.
  */
 public static function init($dbName, $dbHost, $dbUser, $dbPass, $tablePrefix = '', $dbDriver = 'mysql')
 {
     static::$name = $dbName;
     static::$host = $dbHost;
     static::$user = $dbUser;
     static::$pass = $dbPass;
     static::$prefix = $tablePrefix;
     // Skip driver check if reinitializing with same driver.
     if (isset(static::$driver) && $dbDriver == static::$driver) {
         return;
     }
     $drivers = PDO::getAvailableDrivers();
     if (!in_array($dbDriver, $drivers, true)) {
         throw new OutOfBoundsException("Invalid database driver {$dbDriver}.");
     }
     static::setDriver($dbDriver);
 }
Example #29
0
 /**
  * Log the current user out of the application.
  *
  * @return void
  */
 public static function logout()
 {
     // We will call the "logout" closure first, which gives the developer
     // the chance to do any clean-up or before the user is logged out of
     // the application. No action is taken by default.
     call_user_func(Config::get('auth.logout'), static::user());
     static::$user = null;
     $config = Config::get('session');
     extract($config, EXTR_SKIP);
     // When forgetting the cookie, we need to also pass in the path and
     // domain that would have been used when the cookie was originally
     // set by the framework, otherwise it will not be deleted.
     $cookie = Config::get('auth.cookie');
     Cookie::forget($cookie, $path, $domain, $secure);
     Session::forget(Auth::user_key);
 }
Example #30
0
 /**
  * Add test environment, test Acl, setups test user, environment and API key
  */
 public static function setUpBeforeClass()
 {
     if (!Scalr::getContainer()->config->defined('scalr.phpunit.apiv2')) {
         static::markTestIncomplete('phpunit apiv2 configurations is invalid');
     }
     if (Scalr::getContainer()->config->defined('scalr.phpunit.apiv2.params.max_results')) {
         static::$maxResults = Scalr::config('scalr.phpunit.apiv2.params.max_results');
     }
     static::$testUserId = Scalr::config('scalr.phpunit.apiv2.userid');
     static::$user = User::findPk(static::$testUserId);
     static::$testUserType = static::$user->type;
     static::$testEnvId = Scalr::config('scalr.phpunit.apiv2.envid');
     static::$env = Environment::findPk(static::$testEnvId);
     if (empty(static::$user) || empty(static::$env)) {
         static::markTestIncomplete('Either test environment or user is invalid.');
     }
     $apiKeyName = static::getTestName();
     $apiKeyEntity = ApiKeyEntity::findOne([['name' => $apiKeyName], ['userId' => static::$testUserId]]);
     if (empty($apiKeyEntity)) {
         $apiKeyEntity = new ApiKeyEntity(static::$testUserId);
         $apiKeyEntity->name = $apiKeyName;
         $apiKeyEntity->save();
     }
     static::$apiKeyEntity = $apiKeyEntity;
     static::$defaultAcl = Scalr::getContainer()->acl;
     static::$data = [static::$testEnvId => []];
     if (empty(static::$fullAccessAcl)) {
         static::$fullAccessAcl = new ApiTestAcl();
         static::$fullAccessAcl->setDb(Scalr::getContainer()->adodb);
         static::$fullAccessAcl->createTestAccountRole(static::$user->getAccountId(), static::getTestName(ApiFixture::ACL_FULL_ACCESS), ApiTestAcl::ROLE_ID_FULL_ACCESS);
         static::$fullAccessAcl->aclType = ApiFixture::ACL_FULL_ACCESS;
     }
     if (empty(static::$readOnlyAccessAcl)) {
         static::$readOnlyAccessAcl = new ApiTestAcl();
         static::$readOnlyAccessAcl->setDb(Scalr::getContainer()->adodb);
         static::$readOnlyAccessAcl->createTestAccountRole(static::$user->getAccountId(), static::getTestName(ApiFixture::ACL_READ_ONLY_ACCESS), ApiTestAcl::ROLE_ID_READ_ONLY_ACCESS);
         static::$readOnlyAccessAcl->aclType = ApiFixture::ACL_READ_ONLY_ACCESS;
     }
 }