/** * Ensure we populate these fields before a save. */ public function onBeforeWrite() { // Run other beforewrites first. parent::onBeforeWrite(); if (!$this->isBrowser()) { return false; } // If this is the first save... if (!$this->ID) { // Ensure the session exists before querying it. if (!Session::request_contains_session_id()) { Session::start(); } // Store the sesion and has information in the database. $this->SessionID = SecurityToken::getSecurityID(); if (is_null($this->SessionID)) { return false; } $gen = new RandomGenerator(); $uniqueurl = substr($gen->randomToken(), 0, 32); while (ShortList::get()->filter('URL', $uniqueurl)->count() > 0) { $uniqueurl = substr($gen->randomToken(), 0, 32); } $this->URL = $uniqueurl; $this->UserAgent = Controller::curr()->getRequest()->getHeader('User-Agent'); } }
/** * Generate and store the authentication tokens required * * @TODO Rework this, it's not really any better than storing text passwords */ public function generateTokens() { $generator = new RandomGenerator(); $token = $generator->randomToken('sha1'); $this->owner->Token = $this->owner->encryptWithUserSettings($token); $this->authToken = $token; $authToken = $generator->randomToken('whirlpool'); $this->owner->AuthPrivateKey = $authToken; }
/** * Generates the One Time code that is passed to the redirect URL as GET param ott * Supports extension via extendGenerateOneTime, with a max token length of 255 */ public function generateOneTime() { $randomGen = new RandomGenerator(); $random = substr($randomGen->randomToken(), 0, 10); $this->extend('extendGenerateOneTime', $random); $this->OneTimeCode = $random; }
protected function onBeforeWrite() { if (!$this->isInDB()) { $generator = new RandomGenerator(); $this->Token = $generator->randomToken(); } parent::onBeforeWrite(); }
/** * @return string */ public function generateConfirmationToken() { $generator = new RandomGenerator(); $token = $generator->randomToken(); $hash = self::HashConfirmationToken($token); $this->setField('ConfirmationHash', $hash); return $token; }
/** * Generates an encrypted random token. * @param \Member $user * @throws \PasswordEncryptor_NotFoundException * @return string */ public static function generate_token($user) { $generator = new \RandomGenerator(); $tokenString = $generator->randomToken(); $e = \PasswordEncryptor::create_for_algorithm('blowfish'); $salt = $e->salt($tokenString); $token = sha1($e->encrypt($tokenString, $salt)) . substr(md5($user->Created . $user->LastEdited . $user->ID), 7); return $token; }
/** * @return string */ public function generateConfirmationToken() { $generator = new RandomGenerator(); $this->token = $generator->randomToken(); $hash = self::HashConfirmationToken($this->token); $this->setField('ConfirmationHash', $hash); Session::set(self::ConfirmationTokenParamName . '_' . $this->Speaker()->ID, $this->token); return $this->token; }
protected function genToken() { // Generate a new random token (as random as possible) require_once dirname(dirname(dirname(__FILE__))) . '/security/RandomGenerator.php'; $rg = new RandomGenerator(); $token = $rg->randomToken('md5'); // Store a file in the session save path (safer than /tmp, as open_basedir might limit that) file_put_contents($this->pathForToken($token), $token); return $token; }
protected function onBeforeWrite() { if (!$this->isInDB()) { $generator = new RandomGenerator(); $this->Token = $generator->randomToken(); if ($this->getManagerEmail()) { $this->sendEmail(); } } parent::onBeforeWrite(); }
function onBeforeWrite() { parent::onBeforeWrite(); if (!$this->ValidUntil) { $this->setValidInMinutesFromNow(); } if (!$this->RequestedFromIP) { $this->RequestedFromIP = $_SERVER['REMOTE_ADDR']; } if (!$this->UID) { $generator = new RandomGenerator(); $this->UID = $generator->randomToken('sha1'); } }
/** * @return string */ public function generateConfirmationToken() { $generator = new RandomGenerator(); $already_exists = false; $repository = new SapphireSpeakerRegistrationRequestRepository(); do { $this->token = $generator->randomToken(); $already_exists = $repository->existsConfirmationToken($this->token); } while ($already_exists); $hash = self::HashConfirmationToken($this->token); $this->setField('ConfirmationHash', $hash); Session::set(self::ConfirmationTokenParamName . '_' . $this->Speaker()->ID, $this->token); return $this->token; }
/** * Flags the current comment * * @return bool */ public function doFlag() { if (!$this->owner->canFlag()) { return false; } $this->owner->Flagged = true; $this->owner->FlaggedAndRemoved = false; $random = new RandomGenerator(); $this->owner->FlaggedSecurityToken = $random->randomToken(); try { $this->owner->write(); } catch (ValidationException $e) { SS_Log::log($e->getMessage(), SS_Log::WARN); return false; } $this->owner->extend('afterFlag'); return true; }
/** * Tests security ID check */ public function testSecurityID() { // Mock token $securityToken = SecurityToken::inst(); $generator = new RandomGenerator(); $token = $generator->randomToken('sha1'); $session = array($securityToken->getName() => $token); $tokenError = _t('SpellController.SecurityMissing', 'Your session has expired. Please refresh your browser to continue.'); // Test request sans token $response = $this->get('spellcheck', Injector::inst()->create('Session', $session)); $this->assertEquals(400, $response->getStatusCode()); $jsonBody = json_decode($response->getBody()); $this->assertEquals($tokenError, $jsonBody->error->errstr); // Test request with correct token (will fail with an unrelated error) $response = $this->get('spellcheck/?SecurityID=' . urlencode($token), Injector::inst()->create('Session', $session)); $jsonBody = json_decode($response->getBody()); $this->assertNotEquals($tokenError, $jsonBody->error->errstr); // Test request with check disabled Config::inst()->update('SpellController', 'enable_security_token', false); $response = $this->get('spellcheck', Injector::inst()->create('Session', $session)); $jsonBody = json_decode($response->getBody()); $this->assertNotEquals($tokenError, $jsonBody->error->errstr); }
/** * @uses RandomGenerator * * @return String */ protected function generate() { $generator = new RandomGenerator(); return $generator->randomToken('sha1'); }
/** * Generates an encrypted random token * and an expiry date * * @param boolean $expired Set to true to generate an outdated token * @return array token data array('token' => HASH, 'expire' => EXPIRY_DATE) */ private function generateToken($expired = false) { $life = $this->tokenConfig['life']; if (!$expired) { $expire = time() + $life; } else { $expire = time() - $life * 2; } $generator = new RandomGenerator(); $tokenString = $generator->randomToken(); $e = PasswordEncryptor::create_for_algorithm('blowfish'); //blowfish isn't URL safe and maybe too long? $salt = $e->salt($tokenString); $token = $e->encrypt($tokenString, $salt); return array('token' => substr($token, 7), 'expire' => $expire); }
/** * Returns a unique token to correlate an offline item (posted DVD) * with a specific archive placeholder. * * @return String */ public static function generate_upload_token($chars = 8) { $generator = new RandomGenerator(); return strtoupper(substr($generator->randomToken(), 0, $chars)); }
function testGenerateHashWithAlgorithm() { $r = new RandomGenerator(); $this->assertNotNull($r->randomToken('md5')); $this->assertNotEquals($r->randomToken(), $r->randomToken('md5')); }
/** * Passes a call through to the RPC client. * This handles all the login and session id shenanigans. */ public function RPC($method, $arguments = array()) { if ($method != 'system.connect' && $method != 'system.listMethods') { // If this is anything but a system.connect or system.listMethods, then we need to have a // valid session id and login. if (is_null($this->session_id)) { $this->login(); } // If this a v5 site then we need to fetch the sessid and pass in the API key, nonce, etc. if ($this->DrupalVersion == '5.x') { // Push them all to the front of the arguments array. if ($method == 'node.load') { $arguments = array_merge(array($this->session_id), $arguments); } else { // Timestamp and nonce $timestamp = (string) time(); $generator = new RandomGenerator(); $nonce = $generator->randomToken(); // Create new secure hash using your api key. $hash = hash_hmac('sha256', $timestamp . ';' . $this->APIKeyDomain . ';' . $nonce . ';' . $method, $this->APIKey); $arguments = array_merge(array($hash, $this->APIKeyDomain, $timestamp, $nonce, $this->session_id), $arguments); } } } $client = $this->getClient(); return $client->call($method, $arguments); }
/** * @return string */ protected function getNewToken() { $generator = new RandomGenerator(); return substr($generator->randomToken('sha256'), 0, 16); }
/** * Searches in the xpath and gets the images from the body. After that, the * method sorts the images after their size and returns the path of the * biggest image in the set. * * @param DOMXPath $xpathObject * @param string $url * @return string the src path of the image */ public static function find_content_image($xpathObject, $url) { $images = []; foreach ($xpathObject->query("(/html/body//img)[position() <= " . self::$count_of_images . "]") as $node) { $src = $node->getAttribute('src'); if (Director::is_relative_url($src)) { $parsedUrl = parse_url($url); $src = Controller::join_links("{$parsedUrl['scheme']}://{$parsedUrl['host']}", $src); } $generator = new RandomGenerator(); $imageObject = ImageFetcher::fetch_file_by_url($src, $generator->randomToken()); $image = ['src' => $src, 'size' => ['width' => $imageObject->getWidth(), 'height' => $imageObject->getHeight()]]; $image['pixels'] = $image['size']['width'] * $image['size']['height']; $images[] = $image; } usort($images, function ($a, $b) { if ($a['pixels'] != $b['pixels']) { return $a['pixels'] > $b['pixels'] ? -1 : 1; } else { return 0; } }); return isset($images[0]) ? $images[0]['src'] : false; }
public function generateEmailVerificationToken() { $generator = new RandomGenerator(); do { $token = $generator->randomToken(); $hash = self::HashConfirmationToken($token); } while (intval(Member::get()->filter('EmailVerifiedTokenHash', $hash)->count()) > 0); $this->owner->setField('EmailVerifiedTokenHash', $hash); return $token; }
/** * Creates a new random token and hashes it using the * member information * @param Member The logged in user * @return string The hash to be stored in the database */ public function getNewHash(Member $member) { $generator = new RandomGenerator(); $this->setToken($generator->randomToken('sha1')); return $member->encryptWithUserSettings($this->token); }
/** * Generates new random key * * @param integer $length * * @return string */ protected function generate($length = null) { $generator = new RandomGenerator(); $result = $generator->randomToken('sha256'); if ($length !== null) { return substr($result, 0, $length); } return $result; }
/** * Generate an auto login token which can be used to reset the password, * at the same time hashing it and storing in the database. * * @param int $lifetime The lifetime of the auto login hash in days (by default 2 days) * * @returns string Token that should be passed to the client (but NOT persisted). * * @todo Make it possible to handle database errors such as a "duplicate key" error */ public function generateValidateHashAndStore($lifetime = 2) { do { $generator = new RandomGenerator(); $hash = $generator->randomToken(); } while (DataObject::get_one('Recipient', "\"ValidateHash\" = '{$hash}'")); $this->ValidateHash = $hash; $this->ValidateHashExpired = date('Y-m-d H:i:s', time() + 86400 * $lifetime); $this->write(); return $hash; }
/** * Generate an auto login token which can be used to reset the password, * at the same time hashing it and storing in the database. * * @param int $lifetime The lifetime of the auto login hash in days (by default 2 days) * * @returns string Token that should be passed to the client (but NOT persisted). * * @todo Make it possible to handle database errors such as a "duplicate key" error */ public function generateAutologinTokenAndStoreHash($lifetime = 2) { do { $generator = new RandomGenerator(); $token = $generator->randomToken(); $hash = $this->encryptWithUserSettings($token); } while (DataObject::get_one('Member', "\"AutoLoginHash\" = '{$hash}'")); $this->AutoLoginHash = $hash; $this->AutoLoginExpired = date('Y-m-d', time() + 86400 * $lifetime); $this->write(); return $token; }
public function testDisableSecurityTokenAcceptsSubmissionWithoutToken() { SecurityToken::enable(); $expectedToken = SecurityToken::inst()->getValue(); $response = $this->get('FormTest_ControllerWithSecurityToken'); // can't use submitForm() as it'll automatically insert SecurityID into the POST data $response = $this->post('FormTest_ControllerWithSecurityToken/Form', array('Email' => '*****@*****.**', 'action_doSubmit' => 1)); $this->assertEquals(400, $response->getStatusCode(), 'Submission fails without security token'); // Generate a new token which doesn't match the current one $generator = new RandomGenerator(); $invalidToken = $generator->randomToken('sha1'); $this->assertNotEquals($invalidToken, $expectedToken); // Test token with request $response = $this->get('FormTest_ControllerWithSecurityToken'); $response = $this->post('FormTest_ControllerWithSecurityToken/Form', array('Email' => '*****@*****.**', 'action_doSubmit' => 1, 'SecurityID' => $invalidToken)); $this->assertEquals(200, $response->getStatusCode(), 'Submission reloads form if security token invalid'); $this->assertTrue(stripos($response->getBody(), 'name="SecurityID" value="' . $expectedToken . '"') !== false, 'Submission reloads with correct security token after failure'); $this->assertTrue(stripos($response->getBody(), 'name="SecurityID" value="' . $invalidToken . '"') === false, 'Submission reloads without incorrect security token after failure'); $matched = $this->cssParser()->getBySelector('#Form_Form_Email'); $attrs = $matched[0]->attributes(); $this->assertEquals('*****@*****.**', (string) $attrs['value'], 'Submitted data is preserved'); $response = $this->get('FormTest_ControllerWithSecurityToken'); $tokenEls = $this->cssParser()->getBySelector('#Form_Form_SecurityID'); $this->assertEquals(1, count($tokenEls), 'Token form field added for controller without disableSecurityToken()'); $token = (string) $tokenEls[0]; $response = $this->submitForm('Form_Form', null, array('Email' => '*****@*****.**', 'SecurityID' => $token)); $this->assertEquals(200, $response->getStatusCode(), 'Submission suceeds with security token'); }
/** * Return a string value stored in the {@link Member->Salt} property. * Note: Only used when {@link Security::$useSalt} is TRUE. * * @uses RandomGenerator * * @param String $password Cleartext password * @param Member $member (Optional) * @return String Maximum of 50 characters */ function salt($password, $member = null) { $generator = new RandomGenerator(); return substr($generator->randomToken('sha1'), 0, 50); }