关闭Session

@return  bool|void
@throws  \ErrorException
551555
public static function close()
    {
        Base::checkOpen();
        if (Base::driver() == 'file') {
            if (session_status() == PHP_SESSION_ACTIVE) {
                session_write_close();
            }
            return true;
        }
        return Base::getSessionObject()->close();
    }
1320190
public function createSession()
    {
        if (!$this->getUser()) {
            throw new \Exceptions\InternalException('Will not create session where no user is set');
        }

        $this->destroySessions(); // Delete old sessions for user

        $app = App::getInstance();

        $sql = $app['safesql']->query(
            "INSERT INTO `login`
            (
                session_id,
                session_name,
                ip,
                browser,
                user,
                logged_in,
                deleted
            ) VALUES (
                '%s',
                '%s',
                '%s',
                '%s',
                '%s',
                1,
                0
            )",
            array(
                $app['env']['session']->getId(),
                SESSION_NAME,
                $app['env']['RemoteIP'],
                $app['env']['RemoteUA'],
                $this->getUser(),
            ));
        $app['db']->query($sql);

        $app['env']['session']['uname'] = $this->getUser();
        $app['env']['session']['loggedin'] = true;
    }
635291
public function logout()
    {
        try {
            SecurityUtils::getSecurityManager()->logout($this);
        } catch (\Exception $ex) {
            $this->_principals    = null;
            $this->_authenticated = false;
            $this->_session       = null;
        }

    }
705766
private function startSession() {

        if (session_id() == "" || session_id() == null) {
            if (isset ($_REQUEST ["HTTPSESSID"])) {
                session_id($_REQUEST ["HTTPSESSID"]);
            }
            else if (isset ($_REQUEST ["PHPSESSID"])) {
                session_id($_REQUEST ["PHPSESSID"]);
            }
        }

        $cookieDomain = Configuration::instance()->getParameter('session.cookie.domain');
        if ($cookieDomain) {

            if ($cookieDomain == "WILDCARD") {
                $host = isset($_SERVER["HTTP_HOST"]) ? $_SERVER["HTTP_HOST"] : "";
                if ($host) {
                    $splitHost = explode(".", $host);
                    $tld = array_pop($splitHost);
                    $domain = array_pop($splitHost);
                    $cookieDomain = ".$domain.$tld";
                } else {
                    return;
                }
            }



            ini_set("session.cookie_domain", $cookieDomain);
        }

        @session_start();

    }
1152789
public function login()
    {
        $pass = $this->doc->__get("password");
        if($pass && $this->request->param('pass') === $pass){
            session('pass', md5($pass));
            $data = ['status' => '200', 'message' => '登录成功'];
        }else if(!$pass){
            $data = ['status' => '200', 'message' => '登录成功'];
        }else{
            $data = ['status' => '300', 'message' => '密码错误'];
        }
        return response($data, 200, [], 'json');
    }
812315
final public function execute() {
		if (!is_array($this->controller->accessRules()))
			throw new \Exception('Authentication failed: Method "accessRules" in "' .
				$this->controller->getClass() . '" must return an array');
		foreach ($this->controller->accessRules() as $rule) {
			if (!is_array($rule))
				throw new \Exception('Authentication error: Each element of the array returned by accessRules() must be an array');

			if (!isset($rule[0]))
				throw new \Exception('Authentication error: Each element of the array returned by accessRules() must indicate permission as its first element');

			$permission = $rule[0];
			$rules = (isset($rule[1])) ? $rule[1] : array();

			if (!is_string($permission) || (is_string($permission) && !in_array($permission, array('allow', 'deny'))))
				throw new \Exception('Authentication error: First element of each rules array can only be either "allow" or "deny"');
			if (isset($rules) && !is_array($rules))
				throw new \Exception('Authentication error: The second element of each rules array must return an array');

			if (strtolower($permission) === 'allow') {
				if ($this->checkPermission($rules) === TRUE)
					return true;
			}
			elseif (strtolower($permission) === 'deny') {
				if ($this->checkPermission($rules) === TRUE)
					return false;
			}
		}

		return true;
	}
577451
public function restart()
	{
		$this->destroy();

		if ($this->getState() !== 'destroyed')
		{
			// @TODO :: generated error here
			return false;
		}

		// Re-register the session handler after a session has been destroyed, to avoid PHP bug
		$this->store->register();

		$this->setState('restart');

		// Regenerate session id
		session_regenerate_id(true);
		$this->_start();
		$this->setState('active');

		$this->_validate();
		$this->_setCounter();

		return true;
	}
904424
public function init()
    {
        try {
            $this->header('Content-Type: text/plain');
            //$this->header('Content-Type: application/x-json');
        } catch (\Exception $e) {
        }
        if (!$this->importCmdArgs()) {
            return;
        }
        $this->sleep(5, true); // setting timeout 5 seconds */
        $this->onSessionStart(function () {
            $this->wakeup();
            if ($this->cmd === 'LOGIN') {
                if (sizeof($this->args) !== 2) {
                    $this->result = ['$err' => 'You must pass exactly 2 arguments.'];
                    $this->wakeup();
                    return;
                }
                if ((hash_equals($this->appInstance->config->username->value,
                    $this->args[0]) + hash_equals($this->appInstance->config->password->value,
                        $this->args[1])) < 2) {
                    $this->result = ['$err' => 'Wrong username and/or password.'];
                    return;
                }
                $this->attrs->session['logged'] = $this->appInstance->config->credver;
                $this->result = ['$ok' => 1];
                $this->wakeup();
                return;
            } elseif ($this->cmd === 'LOGOUT') {
                unset($this->attrs->session['logged']);
                $this->result = ['$ok' => 1];
                $this->wakeup();
                return;
            }
            if (!isset($this->attrs->session['logged']) || $this->attrs->session['logged'] < $this->appInstance->config->credver) {
                $this->result = ['$err' => 'You must be authenticated.'];
                $this->wakeup();
                return;
            }
        });
    }
777858
protected function startSession()
    {
        if (session_status() === \PHP_SESSION_ACTIVE) {
            throw new \RuntimeException('Session already started by PHP.');
        }

        if (ini_get('session.use_cookies') && headers_sent($file, $line)) {
            throw new \RuntimeException(sprintf('Unable to start session, headers have already been sent by "%s" at line %d.', $file, $line));
        }

        if (!session_start()) {
            throw new \RuntimeException('Unable to start session');
        }
    }
765008
public function call() {
		if ( !isset( $_SESSION[self::PARAM] ) ) {
			$_SESSION[self::PARAM] = sha1( session_id() . microtime() );
		}

		$token = $_SESSION[self::PARAM];
		$method = $this->app->request()->getMethod();

		if ( in_array( $method, [ 'POST', 'PUT', 'DELETE' ] ) ) {
			$requestToken = $this->app->request()->post( self::PARAM );
			if ( $token !== $requestToken ) {
				$this->app->log->error( 'Missing or invalid CSRF token', [
					'got' => $requestToken,
					'expected' => $token,
				] );
				$this->app->render( 'csrf.html', [], 400 );
				return;
			}
		}

		$this->app->view()->replace( [
			'csrf_param' => self::PARAM,
			'csrf_token' => $token,
		] );

		$this->next->call();
	}
337267
public function Start() {
		if ($this->triedstart) {
			return $this->triedresult;
		}
		BLog::addToLog('[Users.Session]: Start()');
		$this->triedresult = false;
		$this->triedstart = true;
		$secret = explode(':', $_COOKIE['brillsecret']);
		if (count($secret) < 2) {
			$this->triedresult = false;
			return false;
		}
		$bCache = BFactory::getCache();
		if (!empty($bCache)) {
			$sess = $bCache->get('session:' . $secret[1]);
			if (($sess !== false) && ($sess !== NULL)) {
				$this->load($sess);
				$this->triedresult = true;
				return true;
			}
		}
		$db = BFactory::getDBO();
		if (empty($db)) {
			return false;
		}
		$qr = 'SELECT * from `sessions` WHERE (sessionid=' . $db->escapeString($secret[1]) . '&&userid=' . (int)$secret[0] . ')';
		$q = $db->Query($qr);
		if (empty($q)) {
			if (DEBUG_MODE) {
				BLog::addToLog('[Session]: Could not execute query! MySQL error: ' . $db->lasterror(), LL_ERROR);
			}
			return false;
		}
		$l = $db->fetch($q);
		if (empty($l)) {
			setcookie('brillsecret', '', time(), '/', BHOSTNAME);
			return false;
		}
		if (!empty($bCache)) {
			$bCache->set('session:' . $l['sessionid'], $l, 600);
		}
		$this->load($l, true);
		$this->triedstart = true;
		$this->triedresult = true;
		return true;
	}
264636
public static function check()
    {
        if (Session::has(self::ENVIRONMENT_NAME)) {
            return true;
        }

        Session::forget(self::ENVIRONMENT_NAME);
        return false;
    }
771738
private function sessionStart()
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            $request = new Request;
            session_set_cookie_params(
                0,
                $request->getBasePath(),
                null,
                $request->getUri()->getScheme() === 'https',
                true
            );
            session_start();
        }
    }
1288987
protected function session()
    {
        if (tao_helpers_Context::check('APP_MODE')) {
            // Set a specific ID to the session.
            $request = new \Request();
            if ($request->hasParameter('session_id')) {
                session_id($request->getParameter('session_id'));
            }
        }

        // set the session cookie to HTTP only.

        $this->configureSessionHandler();

        $sessionParams = session_get_cookie_params();
        $cookieDomain = ((true == tao_helpers_Uri::isValidAsCookieDomain(ROOT_URL)) ? tao_helpers_Uri::getDomain(ROOT_URL) : $sessionParams['domain']);
        $isSecureFlag = \common_http_Request::isHttps();
        session_set_cookie_params($sessionParams['lifetime'], tao_helpers_Uri::getPath(ROOT_URL), $cookieDomain, $isSecureFlag, TRUE);
        session_name(GENERIS_SESSION_NAME);

        if (isset($_COOKIE[GENERIS_SESSION_NAME])) {

            // Resume the session
            session_start();

            //cookie keep alive, if lifetime is not 0
            if ($sessionParams['lifetime'] !== 0) {
                $expiryTime = $sessionParams['lifetime'] + time();
                setcookie(session_name(), session_id(), $expiryTime, tao_helpers_Uri::getPath(ROOT_URL), $cookieDomain, $isSecureFlag, true);
            }
        }
    }
997771
public function check() {
        if (! self::$active) {
            return;
        }
        
        // Check sessions are enabled.
        if (session_id() === '') {
            throw new \Exception('Sessions are required to use the CSRF Guard middleware.');
        }
        
        if (isset($_SESSION["csrf_time"])) {
            $expired = (time() - $_SESSION["csrf_time"]) > 3600;
        } else {
            $expired = true;
        }
        
        if (isset($_GET["expire_token"])) {
            $_SESSION["csrf_time"] = time() - 10000;
        }
        
        if (! isset($_SESSION[$this->key]) || $expired) {
            $_SESSION[$this->key] = sha1(serialize($_SERVER) . rand(0, 0xffffffff));
            $_SESSION["csrf_time"] = time();
        }
        
        $token = $_SESSION[$this->key];
        // Validate the CSRF token.
        if (in_array($this->app->request()->getMethod(), array('POST', 'PUT', 'DELETE'))) {
            $userToken = $this->app->request()->post($this->key);
       
            if ($token !== $userToken) {
                $this->app->halt(400, 'Invalid or missing or expired CSRF token.');
            }
        }
        // Assign CSRF token key and value to view.
        self::$token = $token;
    }
252441
protected function init() {
		$errorMask = E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR |
		             E_PARSE | E_USER_ERROR | E_RECOVERABLE_ERROR;
		
		set_error_handler(function($type, $message, $file, $line) use($errorMask) {
			$this->errors[] = [
				'type'    => $type,
				'message' => $message,
				'file'    => $file,
				'line'    => $line
			];
			
			if ($errorMask & $type) {
				$this->hasError = true;
			}
			 
			return true;
		});
	}
1091394
public function start()
    {
        $result_session_check = (new Session())->check($this->dic['session_id']);
        if (isset($result_session_check['errors'])) {
            $this->response->setData($result_session_check);
        } else {
            $this->response->setData(Response::data([
                'id'   => $result_session_check['session'],
            ]));
        }

        $this->response->send();
    }