public function testWriteSuccessfullyReturnsTrue() { $jar = $this->mock(JarContract::class); $jar->shouldReceive('queue')->once()->with('write.sess', json_encode(['data' => ['user_id' => 1], 'expires' => Chronos::now()->addMinutes(5)->getTimestamp()], \JSON_PRESERVE_ZERO_FRACTION), 5); $handler = new CookieSessionHandler($jar, 5); $this->assertTrue($handler->write('write.sess', ['user_id' => 1])); }
/** * {@inheritdoc} */ public function read($sessionId) { $path = $this->path . '/' . $sessionId; if ($this->files->has($path)) { if (strtotime($this->files->getTimestamp($path)) >= Chronos::now()->subMinutes($this->lifetime)->getTimestamp()) { return $this->files->read($path); } } return ''; }
public function testDelayedPushWithDateTimeProperlyPushesJobOntoSqs() { $now = Chronos::now(); $now->addSeconds(5); $queue = $this->getMockBuilder(SqsQueue::class)->setMethods(['createPayload', 'getSeconds', 'getQueue'])->setConstructorArgs([$this->sqs, $this->queueName, $this->account])->getMock(); $queue->expects($this->once())->method('createPayload')->with($this->mockedJob, $this->mockedData)->will($this->returnValue($this->mockedPayload)); $queue->expects($this->once())->method('getSeconds')->with($now)->will($this->returnValue(5)); $queue->expects($this->once())->method('getQueue')->with($this->queueName)->will($this->returnValue($this->queueUrl)); $this->sqs->shouldReceive('sendMessage')->once()->with(['QueueUrl' => $this->queueUrl, 'MessageBody' => $this->mockedPayload, 'DelaySeconds' => 5])->andReturn($this->mockedSendMessageResponseModel); $id = $queue->later($now, $this->mockedJob, $this->mockedData, $this->queueName); $this->assertEquals($this->mockedMessageId, $id); }
public function testDelayedPushWithDateTimeProperlyPushesJobOntoRedis() { $date = Chronos::now(); $encrypter = $this->mock(EncrypterContract::class); $encrypter->shouldReceive('encrypt'); $redis = $this->mock(Client::class); $redis->shouldReceive('zadd')->once()->with('queues:default:delayed', 2, json_encode(['job' => 'foo', 'data' => ['data'], 'id' => 'foo', 'attempts' => '1'])); $queue = $this->getMockBuilder(RedisQueue::class)->setMethods(['getSeconds', 'getTime', 'getRandomId'])->setConstructorArgs([$redis])->getMock(); $queue->setEncrypter($encrypter); $queue->expects($this->once())->method('getRandomId')->will($this->returnValue('foo')); $queue->expects($this->once())->method('getSeconds')->with($date)->will($this->returnValue(1)); $queue->expects($this->once())->method('getTime')->will($this->returnValue(1)); $queue->later($date, 'foo', ['data']); }
public function testCookiesAreCreatedWithProperOptions() { $cookie = $this->getCreator(); $cookie->setDefaultPathAndDomain('foo', 'bar'); $c = $cookie->create('color', 'blue', 10, '/path', '/domain', true, false); $this->assertEquals('blue', $c->getValue()); $this->assertFalse($c->isHttpOnly()); $this->assertTrue($c->isSecure()); $this->assertEquals('/domain', $c->getDomain()); $this->assertEquals('/path', $c->getPath()); $c2 = $cookie->forever('color', 'blue', '/path', '/domain', true, false); $this->assertEquals('blue', $c2->getValue()); $this->assertFalse($c2->isHttpOnly()); $this->assertTrue($c2->isSecure()); $this->assertEquals('/domain', $c2->getDomain()); $this->assertEquals('/path', $c2->getPath()); $c3 = $cookie->delete('color'); $this->assertNull($c3->getValue()); $this->assertNotEquals($c3->getExpiresTime()->getTimestamp(), Chronos::now()->getTimestamp()); }
/** * Get the cookie lifetime in seconds. * * @param \Viserio\Contracts\Config\Manager $config * * @return int */ protected function getCookieExpirationDate(ConfigContract $config) : int { return $config->get('expire_on_close', false) ? 0 : Chronos::now()->addMinutes($config->get('lifetime')); }
/** * Returns true this instance happened within the specified interval * * This overridden method provides backwards compatible behavior for integers, * or strings with trailing spaces. This behavior is *deprecated* and will be * removed in future versions of CakePHP. * * @param string|int $timeInterval the numeric value with space then time type. * Example of valid types: 6 hours, 2 days, 1 minute. * @return bool */ public function isWithinNext($timeInterval) { $tmp = trim($timeInterval); if (is_numeric($tmp)) { $timeInterval = $tmp . ' days'; } return parent::isWithinNext($timeInterval); }
/** * {@inheritdoc} */ public function write($sessionId, $data) { $this->cookie->queue($sessionId, json_encode(['data' => $data, 'expires' => Chronos::now()->addMinutes($this->lifetime)->getTimestamp()], \JSON_PRESERVE_ZERO_FRACTION), $this->lifetime); return true; }
public function newToken($scope, $scopeId, $type, $expire = null, array $value = []) { $entity = $this->newEntity(['id' => $this->uniqId(), 'scope' => $scope, 'scope_id' => $scopeId, 'type' => $type, 'content' => json_encode($value), 'expire' => is_null($expire) ? Chronos::now() : Chronos::parse($expire)]); $this->save($entity); return $entity->id; }
define('TEST_APP', CORE_TESTS . 'test_app' . DS); // Point app constants to the test app. define('APP', TEST_APP . 'TestApp' . DS); define('WWW_ROOT', TEST_APP . 'webroot' . DS); define('CONFIG', TEST_APP . 'config' . DS); //@codingStandardsIgnoreStart @mkdir(LOGS); @mkdir(SESSIONS); @mkdir(CACHE); @mkdir(CACHE . 'views'); @mkdir(CACHE . 'models'); //@codingStandardsIgnoreEnd require_once CORE_PATH . 'config/bootstrap.php'; date_default_timezone_set('UTC'); mb_internal_encoding('UTF-8'); Configure::write('debug', true); Configure::write('App', ['namespace' => 'App', 'encoding' => 'UTF-8', 'base' => false, 'baseUrl' => false, 'dir' => APP_DIR, 'webroot' => 'webroot', 'wwwRoot' => WWW_ROOT, 'fullBaseUrl' => 'http://localhost', 'imageBaseUrl' => 'img/', 'jsBaseUrl' => 'js/', 'cssBaseUrl' => 'css/', 'paths' => ['plugins' => [TEST_APP . 'Plugin' . DS], 'templates' => [APP . 'Template' . DS], 'locales' => [APP . 'Locale' . DS]]]); Cache::config(['_cake_core_' => ['engine' => 'File', 'prefix' => 'cake_core_', 'serialize' => true], '_cake_model_' => ['engine' => 'File', 'prefix' => 'cake_model_', 'serialize' => true]]); // Ensure default test connection is defined if (!getenv('db_dsn')) { putenv('db_dsn=sqlite:///:memory:'); } ConnectionManager::config('test', ['url' => getenv('db_dsn')]); ConnectionManager::config('test_custom_i18n_datasource', ['url' => getenv('db_dsn')]); Configure::write('Session', ['defaults' => 'php']); Log::config(['debug' => ['engine' => 'Cake\\Log\\Engine\\FileLog', 'levels' => ['notice', 'info', 'debug'], 'file' => 'debug'], 'error' => ['engine' => 'Cake\\Log\\Engine\\FileLog', 'levels' => ['warning', 'error', 'critical', 'alert', 'emergency'], 'file' => 'error']]); Chronos::setTestNow(Chronos::now()); MutableDateTime::setTestNow(MutableDateTime::now()); Date::setTestNow(Date::now()); MutableDate::setTestNow(MutableDate::now()); ini_set('intl.default_locale', 'en_US');
public function testStartMethodResetsIdRegenerationTrace() { $session = $this->encryptedSession(); $session->open(); $regenerationTrace = $session->getRegenerationTrace(); $session->start(); $this->assertNotEquals($regenerationTrace, $session->getRegenerationTrace()); $this->assertGreaterThanOrEqual(Chronos::now()->getTimestamp() - 1, $session->getRegenerationTrace()); }
/** * Get the current system time. * * @return int */ protected function getTime() : int { return Chronos::now()->getTimestamp(); }
/** * Create a new cookie instance. * * @param string $name * @param string|null $value * @param int $minutes * @param string|null $path * @param string|null $domain * @param bool $secure * @param bool $httpOnly * @param string|bool $sameSite * * @return Cookie */ public function create(string $name, $value, int $minutes = 0, $path = null, $domain = null, bool $secure = false, bool $httpOnly = true, $sameSite = false) : CookieContract { list($path, $domain, $secure) = $this->getPathAndDomain($path, $domain, $secure); $time = $minutes === 0 ? 0 : Chronos::now()->getTimestamp() + $minutes * 60; return new Cookie($name, $value, $time, $path, $domain, $secure, $httpOnly, $sameSite); }
public function testToString() { $time = new DateTime('Fri, 20-May-2011 15:25:52 GMT'); $cookie = new Cookie('foo', 'bar', $time, '/', '.myfoodomain.com', true, true, Cookie::SAMESITE_STRICT); $this->assertEquals('foo=bar; Expires=Fri, 20-May-2011 15:25:52 GMT; Path=/; Domain=myfoodomain.com; Secure; HttpOnly; SameSite=strict', $cookie->__toString(), '->__toString() returns string representation of the cookie'); $cookie = new Cookie('foo', null, 1, '/admin/', '.myfoodomain.com', false, true); $this->assertEquals('foo=deleted; Expires=' . gmdate('D, d-M-Y H:i:s T', Chronos::now()->getTimestamp() - 31536001) . '; Path=/admin; Domain=myfoodomain.com; Max-Age=1; HttpOnly', $cookie->__toString(), '->__toString() returns string representation of a cleared cookie if value is NULL'); $cookie = new Cookie('foo'); $this->assertEquals('foo=deleted; Expires=' . gmdate('D, d-M-Y H:i:s T', Chronos::now()->getTimestamp() - 31536001) . '; Path=/', $cookie->__toString()); }
/** * {@inheritDoc} */ public function getCurrentDatetime() { return Chronos::instance(new \DateTime($this->currentDatetime->format(\DateTime::ATOM))); }
/** * Create a new immutable instance from current mutable instance. * * @return Chronos */ public function toImmutable() { return Chronos::instance($this); }
/** * Add the CSRF token to the response cookies. * * @param \Psr\Http\Message\ResponseInterface $response * * @return \Psr\Http\Message\ResponseInterface */ protected function addCookieToResponse(ResponseInterface $response) : ResponseInterface { $config = $this->manager->getConfig(); $setCookie = new Cookie('XSRF-TOKEN', $this->tokenService->generate(), $config->get('session::csrf.livetime', Chronos::now()->getTimestamp() + 60 * 120), $config->get('path'), $config->get('domain'), $config->get('secure', false), false, $config->get('session::csrf.samesite', false)); return $response->withAddedHeader('Set-Cookie', (string) $setCookie); }
protected function appendFormattedNameAndValuePartIfSet(array $cookieStringParts) { $name = urlencode($this->name) . '='; if ((string) $this->getValue() === '') { $cookieStringParts[] .= $name . 'deleted; Expires=' . gmdate('D, d-M-Y H:i:s T', Chronos::now()->getTimestamp() - 31536001); } else { $cookieStringParts[] .= $name . urlencode($this->getValue()); if ($this->getExpiresTime()->format('s') !== 0) { $cookieStringParts[] .= 'Expires=' . $this->getExpiresTime()->format('D, d-M-Y H:i:s T'); } } return $cookieStringParts; }