/** * Fetch a cookie value, using the Input library. * * @param string cookie name * @param mixed default value * @param boolean use XSS cleaning on the value * @return string */ public static function get($name = NULL, $default = NULL, $xss_clean = FALSE) { // Return an array of all the cookies if we don't have a name if ($name === NULL) { $cookies = array(); foreach ($_COOKIE as $key => $value) { $cookies[$key] = cookie::get($key, $default, $xss_clean); } return $cookies; } if (!isset($_COOKIE[$name])) { return $default; } // Get the cookie value $cookie = $_COOKIE[$name]; // Find the position of the split between salt and contents $split = strlen(cookie::salt($name, NULL)); if (isset($cookie[$split]) and $cookie[$split] === '~') { // Separate the salt and the value list($hash, $value) = explode('~', $cookie, 2); if (cookie::salt($name, $value) === $hash) { if ($xss_clean === TRUE and Kohana::config('core.global_xss_filtering') === FALSE) { return Input::instance()->xss_clean($value); } // Cookie signature is valid return $value; } // The cookie signature is invalid, delete it cookie::delete($name); } return $default; }
static function start($salt, $expire = null, $domain = null, $path = '/') { self::$salt = $salt; self::$expire = $expire; self::$domain = $domain; self::$path = $path; }
/** * Sets a signed cookie. * * @param string name of cookie * @param string contents of cookie * @param integer lifetime in seconds * @return boolean */ public static function set($key, $value, $expiration = NULL) { if ($expiration === NULL) { // Use the default expiration $expiration = cookie::$expiration; } if ($expiration !== 0) { // The expiration is expected to be a UNIX timestamp $expiration += time(); } // Add the salt to the cookie value $value = cookie::salt($key, $value) . '~' . $value; return setcookie($key, $value, $expiration, cookie::$path, cookie::$domain, cookie::$secure, cookie::$httponly); }
/** * Tests cookie::salt() * * @test * @dataProvider provider_salt * @covers cookie::salt * @param mixed $key key to use * @param mixed $value value to salt with * @param boolean $expected Output for cookie::delete() */ public function test_salt($key, $value, $expected) { $this->assertSame($expected, cookie::salt($key, $value)); }
/** * Test logged in from cookie */ public function testLoggedInFromCookie() { DB::insert('users', array('id', 'username', 'token'))->values(array(2, 'logged_in_cookie_user', 1234))->execute(); $_COOKIE['a1_a1_autologin'] = cookie::salt('a1_a1_autologin', '1234.2') . '~1234.2'; $this->assertType('string', cookie::get('a1_a1_autologin')); $result = A1::instance('a1')->logged_in(); $this->assertTrue($result); $session = Session::instance(Kohana::config('a1.session_type')); $user = $session->get('a1_a1'); $this->assertType('object', $user); $this->assertEquals('logged_in_cookie_user', $user->username); $this->assertEquals(2, $user->id); }