Setup session machine
760701
protected function setupDefaultMachine(array $config)
	{

		// State function
		if ($this->state_select === null) {
			$this->state_select = '"Authenticated"'; // TODO
		}

		// Exists state only
		$this->states = [
			'Authenticated' => [
				'description' => _('User is authenticated and active.'),
				'color' => '#ddffcc',
			],
			'Prepared' => [
				'description' => _('Session token is waiting for user (i.e. to click login link sent via e-mail).'),
				'color' => '#ffffcc',
			],
			'Expired' => [
				'description' => _('Session has expired. Awaiting clean up.'),
				'color' => '#ffddcc',
			],
		];

		$this->access_policies = [
			'admin' => [
				'type' => 'nobody',
				'arrow_tail' => 'nonetee',
			],
			'owner' => [
				'type' => 'owner',
				'owner_property' => 'user_id',
				'arrow_tail' => 'dot',
			],
			'anonymous' => [
				'type' => 'anonymous',
				'arrow_tail' => 'odot',
			],
		];

		// Actions
		$this->actions = [
			'login' => [
				'description' => _('Login user using password.'),
				'color' => '#44aa00',
				'returns' => self::RETURNS_NEW_ID,
				'transitions' => [
					'' => [
						'targets' => [ '', 'Authenticated' ],
						'access_policy' => 'anonymous',
					],
				],
			],
			'useToken' => [
				'description' => _('Login user using prepared token'),
				'transitions' => [
					'Prepared' => [
						'targets' => [ 'Authenticated' ],
						'access_policy' => 'anonymous',
					],
				],
			],
			'logout' => [
				'description' => _('Logout user.'),
				'color' => '#aa4400',
				'transitions' => [
					'Authenticated' => [
						'targets' => [ '' ],
						'access_policy' => 'owner',
					],
					'Prepared' => [
						'targets' => [ '' ],
						'access_policy' => 'admin',
					],
					'Expired' => [
						'targets' => [ '' ],
						'access_policy' => 'owner',
					],
				],
			],
			'checkSession' => [
				'description' => _('Check whether the session is valid.'),
				'color' => '#aa88ff',
				'transitions' => [
					'' => [
						'targets' => [ '', 'Authenticated' ],
						'access_policy' => 'anonymous',
					],
				],
			],
			'prepare' => [
				'description' => _('Prepare session token for later use.'),
				'returns' => self::RETURNS_NEW_ID,
				'transitions' => [
					'' => [
						'targets' => [ 'Prepared' ],
					],
				],
			],
			'expire' => [
				'description' => _('Expire session. Timed transition.'),
				'color' => '#aaaaaa',
				'transitions' => [
					'Authenticated' => [
						'targets' => [ 'Expired' ],
					],
					'Prepared' => [
						'targets' => [ 'Expired' ],
					],
				],
			],
		];

		// Merge with config
		if (isset($config['actions'])) {
			$this->actions = array_replace_recursive($this->actions, $config['actions']);
		}
		if (isset($config['states'])) {
			$this->states = array_replace_recursive($this->states, $config['states']);
		}
		if (isset($config['access_policies'])) {
			$this->access_policies = array_replace_recursive($this->access_policies, $config['access_policies']);
		}
	}
999599
protected function setUpSession () {
		if ($this->session === NULL) {
			$sessionClass = $this->application->GetSessionClass();
			$selfClass = version_compare(PHP_VERSION, '5.5', '>') ? self::class : __CLASS__;
			$this->session = $sessionClass::GetNamespace($selfClass);
			$this->session->SetExpirationSeconds($this->sessionExpirationSeconds);
		}
	}
1061532
def attach_session(self, target_session=None):
        
        session_check_name(target_session)

        tmux_args = tuple()
        if target_session:
            tmux_args += ('-t%s' % target_session,)

        proc = self.cmd('attach-session', *tmux_args)

        if proc.stderr:
            raise exc.LibTmuxException(proc.stderr)
789709
def sessions(status, access_key, id_only, all):
    '''
    
    '''
    fields = [
        ('Session ID', 'sess_id'),
    ]
    with Session() as session:
        if is_admin(session):
            fields.append(('Owner', 'access_key'))
    if not id_only:
        fields.extend([
            ('Image', 'image'),
            ('Tag', 'tag'),
            ('Created At', 'created_at',),
            ('Terminated At', 'terminated_at'),
            ('Status', 'status'),
            ('Occupied Resource', 'occupied_slots'),
            ('Used Memory (MiB)', 'mem_cur_bytes'),
            ('Max Used Memory (MiB)', 'mem_max_bytes'),
            ('CPU Using (%)', 'cpu_using'),
        ])
        if is_legacy_server():
            del fields[2]

    def execute_paginated_query(limit, offset):
        q = '''
        query($limit:Int!, $offset:Int!, $ak:String, $status:String) {
          compute_session_list(
              limit:$limit, offset:$offset, access_key:$ak, status:$status) {
            items { $fields }
            total_count
          }
        }'''
        q = textwrap.dedent(q).strip()
        q = q.replace('$fields', ' '.join(item[1] for item in fields))
        v = {
            'limit': limit,
            'offset': offset,
            'status': status if status != 'ALL' else None,
            'ak': access_key,
        }
        try:
            resp = session.Admin.query(q, v)
        except Exception as e:
            print_error(e)
            sys.exit(1)
        return resp['compute_session_list']

    def round_mem(items):
        for item in items:
            if 'mem_cur_bytes' in item:
                item['mem_cur_bytes'] = round(item['mem_cur_bytes'] / 2 ** 20, 1)
            if 'mem_max_bytes' in item:
                item['mem_max_bytes'] = round(item['mem_max_bytes'] / 2 ** 20, 1)
        return items

    def _generate_paginated_results(interval):
        offset = 0
        is_first = True
        total_count = -1
        while True:
            limit = (interval if is_first else
                    min(interval, total_count - offset))
            try:
                result = execute_paginated_query(limit, offset)
            except Exception as e:
                print_error(e)
                sys.exit(1)
            offset += interval
            total_count = result['total_count']
            items = result['items']
            items = round_mem(items)

            if id_only:
                yield '\n'.join([item['sess_id'] for item in items]) + '\n'
            else:
                table = tabulate([item.values() for item in items],
                                    headers=(item[0] for item in fields))
                if not is_first:
                    table_rows = table.split('\n')
                    table = '\n'.join(table_rows[2:])
                yield table + '\n'

            if is_first:
                is_first = False
            if not offset < total_count:
                break

    with Session() as session:
        paginating_interval = 10
        if all:
            click.echo_via_pager(_generate_paginated_results(paginating_interval))
        else:
            result = execute_paginated_query(paginating_interval, offset=0)
            total_count = result['total_count']
            if total_count == 0:
                print('There are no compute sessions currently {0}.'
                      .format(status.lower()))
                return
            items = result['items']
            items = round_mem(items)
            if id_only:
                for item in items:
                    print(item['sess_id'])
            else:
                print(tabulate([item.values() for item in items],
                                headers=(item[0] for item in fields)))
            if total_count > paginating_interval:
                print("More sessions can be displayed by using --all option.")
187256
def setup(self, environ):
        '''
        '''
        request = wsgi_request(environ)
        cfg = request.cache.cfg
        loop = request.cache._loop
        self.store = create_store(cfg.data_store, loop=loop)
        pubsub = self.store.pubsub(protocol=Protocol())
        channel = '%s_webchat' % self.name
        ensure_future(pubsub.subscribe(channel), loop=loop)
        return WsgiHandler([Router('/', get=self.home_page),
                            WebSocket('/message', Chat(pubsub, channel)),
                            Router('/rpc', post=Rpc(pubsub, channel),
                                   response_content_types=JSON_CONTENT_TYPES)],
                           [AsyncResponseMiddleware,
                            GZipMiddleware(min_length=20)])
1258357
def setup_session(endpoint_context, areq, uid, client_id='', acr='', salt='salt',
                  authn_event=None):
    
    if authn_event is None and acr:
        authn_event = AuthnEvent(uid=uid, salt=salt, authn_info=acr,
                                 authn_time=time.time())

    if not client_id:
        client_id = areq['client_id']

    sid = endpoint_context.sdb.create_authz_session(authn_event, areq,
                                                    client_id=client_id,
                                                    uid=uid)
    endpoint_context.sdb.do_sub(sid, uid, '')
    return sid
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();

    }
440792
def _init_session(self):
        
        session = requests.Session()
        session.headers = {'User-Agent': self.user_agent,
                           'Accept': 'application/json'}
        if self.systemid is not None:
            session.headers.update({'systemid': self.systemid})
        if self.authmethod == "BASIC":
            session.auth = (self.username, self.password)
        elif self.authmethod == "CERT":
            cert = rhsmCertificate.certpath()
            key = rhsmCertificate.keypath()
            if rhsmCertificate.exists():
                session.cert = (cert, key)
            else:
                logger.error('ERROR: Certificates not found.')
        session.verify = self.cert_verify
        session.proxies = self.proxies
        session.trust_env = False
        if self.proxy_auth:
            # HACKY
            try:
                # Need to make a request that will fail to get proxies set up
                net_logger.info("GET %s", self.base_url)
                session.request(
                    "GET", self.base_url, timeout=self.config.http_timeout)
            except requests.ConnectionError:
                pass
            # Major hack, requests/urllib3 does not make access to
            # proxy_headers easy
            proxy_mgr = session.adapters['https://'].proxy_manager[self.proxies['https']]
            auth_map = {'Proxy-Authorization': self.proxy_auth}
            proxy_mgr.proxy_headers = auth_map
            proxy_mgr.connection_pool_kw['_proxy_headers'] = auth_map
            conns = proxy_mgr.pools._container
            for conn in conns:
                connection = conns[conn]
                connection.proxy_headers = auth_map
        return session
718158
def __create_session(username=None, password=None):
        """"""
        config = Config()

        if not username or not password:
            username = config.username
            password = config.password

        payload = {
            "username": username,
            "password": password,
        }

        session_resp = requests.post("https://users.{}/sessions/".format(config.host), json=payload)
        if session_resp.status_code == 403:
            raise errors.ResourceError("bad user credentials")

        return session_resp.cookies["session"]
163838
def create_session(self, server_host, server_port, honeypot_id):
        
        protocol = self.__class__.__name__.lower()
        session = BaitSession(protocol, server_host, server_port, honeypot_id)
        self.sessions[session.id] = session
        return session
55617
public static function setupSession($needed=self::ALL, $session_object=null, $request_data=false) {
        global $CFG, $TSUGI_LAUNCH, $TSUGI_SESSION_OBJECT;
        global $PDOX;
        $TSUGI_SESSION_OBJECT = $session_object;

        $needed = self::patchNeeded($needed);

        // Check if we are an LTI 1.1 or LTI 1.3 launch
        $LTI11 = false;
        $LTI13 = false;
        $lti13_request_data = $request_data;
        if ( $lti13_request_data === false ) $lti11_request_data = $_POST;
        $detail = LTI13::isRequestDetail($request_data);
        if ( $detail === true ) {
            $LTI13 = true;
            $request_data = $lti13_request_data;
        } else {
            $lti11_request_data = $request_data;
            if ( $lti11_request_data === false ) $lti11_request_data = self::oauth_parameters();
            $LTI11 = LTI::isRequestCheck($lti11_request_data);
            if ( is_string($LTI11) ) {
                self::abort_with_error_log($LTI11, $request_data);
            }
            $request_data = $lti11_request_data;
        }
        if ( $LTI11 === false && $LTI13 === false ) return $detail;

        // Pull LTI data out of the incoming $request_data and map into the same
        // keys that we use in our database (i.e. like $row)
        $post = false;
        if ( $LTI11 ) {
            $post = self::extractPost($needed, $request_data);
        } else if ( $LTI13 ) {
            $post = self::extractJWT($needed, $request_data);
            // echo("<pre>\n");var_dump($post);echo("\n</pre>\n");
        }

        if ( ! is_array($post) ) {
            $msg = '';
            if ( is_string($post) ) $msg = $post . ' ';
            self::abort_with_error_log($msg, $request_data);
        }

        // We make up a Session ID Key because we don't want a new one
        // each time the same user launches the same link.
        if ( $session_object === null ) {
            if ( !defined('COOKIE_SESSION') ) {
                $session_id = self::getCompositeKey($post, $CFG->sessionsalt);
                session_id($session_id);
                session_start();
            // if we're using a cookie session, the session may already have been started; if not, start it now
            // (if we call session_start() and the session has already been started, php will generate a notice, which we don't want)
            } else if (empty($_SESSION)) {
                session_start();
            }
            $session_id = session_id();

            // TODO: Why was this here?
            // header('Content-Type: text/html; charset=utf-8');

            // Since we might reuse session IDs, clean everything out except permanent stuff
            if ( !defined('COOKIE_SESSION') ) {
                $save_sess = self::wrapped_session_all($session_object);
                self::wrapped_session_flush($session_object);
                foreach($save_sess as $key => $v ) {
                    if ( strpos($key, 'tsugi_permanent_') !== 0 ) continue;
                    self::wrapped_session_put($session_object, $key, $v);
                }
            }
        }

        self::wrapped_session_put($session_object,'LAST_ACTIVITY', time());

        // Copy the tsugi_nav into the session
        $sess_key = 'tsugi_top_nav_'.$CFG->wwwroot;
        if ( isset($request_data['ext_tsugi_top_nav']) ) {
            self::wrapped_session_put($session_object,$sess_key, $request_data['ext_tsugi_top_nav']);
        } else {
            self::wrapped_session_forget($session_object,$sess_key);
        }

        // Read all of the data from the database with a very long
        // LEFT JOIN and get all the data we have back in the $row variable
        // $row = loadAllData($CFG->dbprefix, false, $post);
        $row = self::loadAllData($CFG->dbprefix, $CFG->dbprefix.'profile', $post);

        // TODO: LTI13 Timestamp
        $delta = 0;
        if ( isset($request_data['oauth_timestamp']) ) {
            $server_time = $request_data['oauth_timestamp']+0;
            $delta = abs(time() -  $server_time);
            if ( $delta > 480 ) { // More than four minutes is getting close
                error_log('Warning: Time skew, delta='.$delta.' sever_time='.$server_time.' our_time='.time());
            }
        }

        // Check the nonce to make sure there is no reuse
        if ( $row['nonce'] !== null) {
            self::abort_with_error_log('OAuth nonce error key='.$post['key'].' nonce='.$row['nonce']);
        }

        // Use returned data to check the validity of the incoming request
        $raw_jwt = false;
        $jwt = false;
        if ( $LTI11 ) {
            $valid = LTI::verifyKeyAndSecret($post['key'],$row['secret'],self::curPageUrl(), $request_data);

            // If there is a new_secret it means an LTI2 re-registration is in progress and we
            // need to check both the current and new secret until the re-registration is committed
            if ( $valid !== true && strlen($row['new_secret']) > 0 && $row['new_secret'] != $row['secret']) {
                $valid = LTI::verifyKeyAndSecret($post['key'],$row['new_secret'],self::curPageUrl(), $request_data);
                if ( $valid ) {
                    $row['secret'] = $row['new_secret'];
                }
                $row['new_secret'] = null;
            }

            if ( isset($TSUGI_LAUNCH) ) $TSUGI_LAUNCH->base_string = LTI::getLastOAuthBodyBaseString();

            // TODO: Might want to add more flows here...
            if ( $valid !== true ) {
                if ( isset($TSUGI_LAUNCH) ) $TSUGI_LAUNCH->error_message = $valid;
                self::abort_with_error_log('OAuth validation fail key='.$post['key'].' delta='.$delta.' error='.$valid[0],$valid[1]);
            }

        } else { // LTI 1.3
            $raw_jwt = LTI13::raw_jwt($request_data);
            $jwt = LTI13::parse_jwt($raw_jwt);
            $consumer_pk = $post['key'];
            $consumer_sha256 = U::lti_sha256($consumer_pk);
            error_log("consumer_pk=$consumer_pk consumer_sha256=$consumer_sha256");
            $pub_row = $PDOX->rowDie("SELECT lti13_kid, lti13_keyset_url, lti13_keyset,
                lti13_platform_pubkey, lti13_token_url, lti13_privkey
                FROM {$CFG->dbprefix}lti_key WHERE key_sha256 = :SHA",
                    array(':SHA' => $consumer_sha256) );

            if ( ! $pub_row ) {
                error_log("Did not find key for consumer_sha256");
                return false;
            }

            $request_kid = isset($jwt->header->kid) ? $jwt->header->kid : null;
            $our_kid = $pub_row['lti13_kid'];
            $our_keyset = $pub_row['lti13_keyset'];
            $our_keyset_url = $pub_row['lti13_keyset_url'];
            $public_key = $pub_row['lti13_platform_pubkey'];

            $private_key = $pub_row['lti13_privkey'];
            $token_url = $pub_row['lti13_token_url'];

            // Sanity check
            if ( strlen($public_key) < 1 && strlen($our_keyset_url) < 1 ) {
                 self::abort_with_error_log("For LTI 1.3, $consumer_pk either must have a public_key or keyset_url\n$consumer_sha256");
            }

            // Make sure we have or update to the latest keyset if we have a keyset_url
            if ( strlen($our_keyset_url) > 0 &&
                    (strlen($our_keyset) < 1 || $our_kid != $request_kid ) ) {
                $our_keyset = file_get_contents($our_keyset_url);
                $decoded = json_decode($our_keyset);
                if ( $decoded && isset($decoded->keys) && is_array($decoded->keys) ) {
                    $PDOX->queryDie("UPDATE {$CFG->dbprefix}lti_key
                        SET lti13_keyset=:KS, updated_at=NOW() WHERE key_sha256 = :SHA",
                    array(':SHA' => $consumer_sha256, ':KS' => $our_keyset) );
                    error_log("Updated keyset $consumer_sha256 from $our_keyset_url\n");
                } else {
                    self::abort_with_error_log("Failure loading keyset from ".$our_keyset_url,
                                substr($our_keyset,0,1000));
                }
            }

            // If we have a keyset and a kid mismatch, lets grab that new key
            if ( strlen($our_keyset) > 0 &&
                ($our_kid != $request_kid || strlen($public_key) < 1) ) {
                $key_set = json_decode($our_keyset, true);
                $new_public_key = false;

                foreach ($key_set['keys'] as $key) {
                    if ($key['kid'] == $request_kid) {
                        $details = openssl_pkey_get_details(JWK::parseKey($key));
                        if ( $details && is_array($details) && isset($details['key']) ) {
                            $new_public_key = $details['key'];
                        }
                        break;
                    }
                }

                if ( $new_public_key ) {
                    $PDOX->queryDie("UPDATE {$CFG->dbprefix}lti_key
                        SET lti13_platform_pubkey=:PK, lti13_kid=:KID, updated_at=NOW() WHERE key_sha256 = :SHA",
                        array(':SHA' => $consumer_sha256, ':PK' => $new_public_key,
                            ':KID' => $request_kid )
                    );
                    error_log("New public key $consumer_sha256\n$new_public_key");
                    $public_key = $new_public_key;
                } else {
                    // TODO: Understand if we should kill the old key here
                    $PDOX->queryDie("UPDATE {$CFG->dbprefix}lti_key
                        SET lti13_platform_pubkey=NULL, updated_at=NOW() WHERE key_sha256 = :SHA",
                    array(':SHA' => $consumer_sha256) );
                    if ( strlen($public_key) > 0 ) {
                        error_log("Cleared public key $consumer_sha256 invalid kid");
                        self::abort_with_error_log("Invalid Key Id (header.kid), public key cleared");
                    } else {
                        error_log("Could not find public key $consumer_sha256 invalid kid");
                        self::abort_with_error_log("Invalid Key Id (header.kid), could not find public key");
                    }
                }
            }

            $e = LTI13::verifyPublicKey($raw_jwt, $public_key, array($jwt->header->alg));
            if ( $e !== true ) {
                error_log('public_key');
                error_log($public_key);
                self::abort_with_error_log('JWT validation fail key='.$post['key'].' error='.$e->getMessage());
            }

            // TODO: Encrypt private key
            $row['lti13_privkey'] = $private_key;
            $row['lti13_token_url'] = $token_url;

            // Just copy across
            if ( U::get($post,'lti13_deeplink') ) $row['lti13_deeplink'] = $post['lti13_deeplink'];

            self::wrapped_session_put($session_object, 'tsugi_jwt', $jwt);
            // self::wrapped_session_put($session_object, 'tsugi_raw_jwt', $raw_jwt);
        }

        // Store the launch path
        // TODO: Make sure we like this
        $post['link_path'] = self::curPageUrl();
        $actions = self::adjustData($CFG->dbprefix, $row, $post, $needed);

        $PDOX = self::getConnection();
        // Record the nonce but first probabilistically check if we will clean out
        if ( $CFG->noncecheck > 0 ) {
            if ( (time() % $CFG->noncecheck) == 0 ) {
                $PDOX->queryDie("DELETE FROM {$CFG->dbprefix}lti_nonce WHERE
                    created_at < DATE_ADD(CURRENT_TIMESTAMP(), INTERVAL -{$CFG->noncetime} SECOND)");
                // error_log("Nonce table cleanup done.");
            }
            $PDOX->queryDie("INSERT INTO {$CFG->dbprefix}lti_nonce
                (key_id, nonce) VALUES ( :key_id, :nonce)",
                array( ':nonce' => $post['nonce'], ':key_id' => $row['key_id'])
            );
        }

        // If there is an appropriate role override variable, we use that role
        if ( isset($row['role_override']) && isset($row['role']) &&
            $row['role_override'] > $row['role'] ) {
            $row['role'] = $row['role_override'];
        }

        // Update the login_at data and do analytics if requested
        // There are a lot of queryReturnError() calls because we don't want to
        // fail on "nice to have" analytics data.
        $start_time = self::wrapped_session_get($session_object, 'tsugi_permanent_start_time', false);

        if ( isset($row['user_id']) && $start_time === false ) {
            self::noteLoggedIn($row);

            // Only learner launches are logged
            if ( $CFG->launchactivity && isset($row['link_id']) && $row['link_id'] && $row['role'] == 0 ) {
                $link_activity = isset($row['link_activity']) ? $row['link_activity'] : null;
                $link_count = isset($row['link_count']) ? $row['link_count'] : 0;

                if ( $link_activity == null || $link_count == 0 ) {

                    $sql = "INSERT INTO {$CFG->dbprefix}lti_link_activity
                                (link_id, event, link_count, updated_at) VALUES
                                (:link_id, 0, 0, NOW())";

                    $stmt = $PDOX->queryReturnError($sql, array(
                        ':link_id' => $row['link_id']
                    ));

                    if ( ! $stmt->success ) {
                        error_log("Unable to create activity record link=".$row['link_id']);
                    }
                }

                $ent = new \Tsugi\Event\Entry();
                if ( $link_activity ) $ent->deSerialize($link_activity);
                $ent->total = $link_count;
                $ent->click();
                $activity = $ent->serialize(self::MAX_ACTIVITY);
                $sql = "UPDATE {$CFG->dbprefix}lti_link_activity
                        SET activity=:activity, updated_at=NOW(), link_count=link_count+1
                        WHERE link_id = :link_id AND event = 0";
                $stmt = $PDOX->queryReturnError($sql, array(
                  ':link_id' => $row['link_id'],
                  ':activity' => $activity
                ));

                if ( ! $stmt->success ) {
                    error_log("Unable to update activity record link=".$row['link_id']);
                }

                // Now user activity
                $link_activity = isset($row['link_user_activity']) ? $row['link_user_activity'] : null;
                $link_count = isset($row['link_user_count']) ? $row['link_user_count'] : 0;

                if ( isset($row['user_id']) && $row['user_id'] ) {
                    if ( $link_activity == null || $link_count == 0 ) {

                        $sql = "INSERT INTO {$CFG->dbprefix}lti_link_user_activity
                                (link_id, user_id, event, link_user_count, updated_at) VALUES
                                (:link_id, :user_id, 0, 0, NOW())";
                        $stmt = $PDOX->queryReturnError($sql, array(
                            ':link_id' => $row['link_id'],
                            ':user_id' => $row['user_id']
                        ));

                        if ( ! $stmt->success ) {
                            error_log("Unable to create user activity record link=".$row['user_id']);
                        }
                    }

                    $ent = new \Tsugi\Event\Entry();
                    if ( $link_activity ) $ent->deSerialize($link_activity);
                    $ent->total = $link_count;
                    $ent->click();
                    $activity = $ent->serialize(self::MAX_ACTIVITY);
                    $sql = "UPDATE {$CFG->dbprefix}lti_link_user_activity
                        SET activity=:activity, updated_at=NOW(), link_user_count=link_user_count+1
                        WHERE link_id = :link_id AND user_id = :user_id AND event = 0";
                    $stmt = $PDOX->queryReturnError($sql, array(
                        ':link_id' => $row['link_id'],
                        ':user_id' => $row['user_id'],
                        ':activity' => $activity
                    ));

                    if ( ! $stmt->success ) {
                        error_log("Unable to update user activity record link=".$row['user_id']);
                    }
                }
            }

            // Now the place the event into the circular buffer
            if ( $CFG->eventcheck !== false ) {
                // https://stackoverflow.com/questions/3554296/how-to-store-hashes-in-mysql-databases-without-using-text-fields
                $event_nonce = $row['nonce'].':'.$row['key_key'];
                $event_launch = null;
                $canvasUrl = U::get($request_data,'custom_sub_canvas_caliper_url');
                if ( $canvasUrl ) {
                    $event_launch = 'canvas::'.$canvasUrl;
                }

                $sql = "INSERT INTO {$CFG->dbprefix}cal_event
                        (event, key_id, context_id, link_id, user_id, nonce, launch, updated_at) VALUES
                        (0, :key_id, :context_id, :link_id, :user_id, UNHEX(MD5(:nonce)), :launch, NOW())";
                $stmt = $PDOX->queryReturnError($sql, array(
                    ':key_id' => U::get($row, 'key_id'),
                    ':context_id' => U::get($row, 'context_id'),
                    ':link_id' => U::get($row, 'link_id'),
                    ':user_id' => U::get($row, 'user_id'),
                    ':nonce' => $event_nonce,
                    ':launch' => $event_launch
                ));

                if ( ! $stmt->success ) {
                    error_log("Unable to insert event record");
                }
                $row['event_nonce'] = $event_nonce;
                $row['event_launch'] = $event_launch;
            }
        }

        // Make sure we debounce really fast relaunches
        self::wrapped_session_put($session_object, 'tsugi_permanent_start_time', time());

        // Encrypt the secret before placing in the session
        $row['secret'] = self::encrypt_secret($row['secret']);

        // Put the information into the row variable and put row into session
        self::wrapped_session_put($session_object, 'lti', $row);
        self::wrapped_session_put($session_object, 'lti_post', $request_data);

        if ( isset($_SERVER['HTTP_USER_AGENT']) ) {
            self::wrapped_session_put($session_object, 'HTTP_USER_AGENT', $_SERVER['HTTP_USER_AGENT']);
        }
        $ipaddr = Net::getIP();
        if ( $ipaddr ) {
            self::wrapped_session_put($session_object, 'REMOTE_ADDR', $ipaddr);
        }
        self::wrapped_session_put($session_object, 'CSRF_TOKEN', uniqid());

        // Save this to make sure the user does not wander unless we launched from the root
        $scp = $CFG->getScriptPath();
        if ( strlen($scp) > 0 ) {
            self::wrapped_session_put($session_object, 'script_path', $CFG->getScriptPath());
        }

        // Check if we can auto-login the system user
        if ( Settings::linkGet('dologin', false) && isset($PDOX) && $PDOX !== false ) self::loginSecureCookie();

        $breadcrumb = 'Launch,';
        $breadcrumb .= isset($row['key_id']) ? $row['key_id'] : '';
        $breadcrumb .= ',';
        $breadcrumb .= isset($row['user_id']) ? $row['user_id'] : '';
        $breadcrumb .= ',';
        $breadcrumb .= isset($request_data['user_id']) ? str_replace(',',';', $request_data['user_id']) : '';
        $breadcrumb .= ',';
        if ( $session_object === null ) {
            $breadcrumb .= $session_id;
        }
        $breadcrumb .= ',';
        $breadcrumb .= self::curPageUrl();
        $breadcrumb .= ',';
        $breadcrumb .= self::wrapped_session_get($session_object, 'email',' ');
        error_log($breadcrumb);

        if ( $session_object === null ) {
            return $session_id;
        }
    }
1270420
def setup_db(session, botconfig, confdir):
    """"""
    Base.metadata.create_all(session.connection())
    # If we're creating a fresh db, we don't need to worry about migrations.
    if not session.get_bind().has_table('alembic_version'):
        conf_obj = config.Config()
        conf_obj.set_main_option('bot_config_path', confdir)
        with resources.path('cslbot', botconfig['alembic']['script_location']) as script_location:
            conf_obj.set_main_option('script_location', str(script_location))
            command.stamp(conf_obj, 'head')

    # Populate permissions table with owner.
    owner_nick = botconfig['auth']['owner']
    if not session.query(Permissions).filter(Permissions.nick == owner_nick).count():
        session.add(Permissions(nick=owner_nick, role='owner'))
1219691
function setup() {
        global $SESSION;

        if (empty($this->columns) || empty($this->uniqueid)) {
            return false;
        }

        // Load any existing user preferences.
        if ($this->persistent) {
            $this->prefs = json_decode(get_user_preferences('flextable_' . $this->uniqueid), true);
            $oldprefs = $this->prefs;
        } else if (isset($SESSION->flextable[$this->uniqueid])) {
            $this->prefs = $SESSION->flextable[$this->uniqueid];
            $oldprefs = $this->prefs;
        }

        // Set up default preferences if needed.
        if (!$this->prefs or optional_param($this->request[TABLE_VAR_RESET], false, PARAM_BOOL)) {
            $this->prefs = array(
                'collapse' => array(),
                'sortby'   => array(),
                'i_first'  => '',
                'i_last'   => '',
                'textsort' => $this->column_textsort,
            );
        }

        if (!isset($oldprefs)) {
            $oldprefs = $this->prefs;
        }

        if (($showcol = optional_param($this->request[TABLE_VAR_SHOW], '', PARAM_ALPHANUMEXT)) &&
                isset($this->columns[$showcol])) {
            $this->prefs['collapse'][$showcol] = false;

        } else if (($hidecol = optional_param($this->request[TABLE_VAR_HIDE], '', PARAM_ALPHANUMEXT)) &&
                isset($this->columns[$hidecol])) {
            $this->prefs['collapse'][$hidecol] = true;
            if (array_key_exists($hidecol, $this->prefs['sortby'])) {
                unset($this->prefs['sortby'][$hidecol]);
            }
        }

        // Now, update the column attributes for collapsed columns
        foreach (array_keys($this->columns) as $column) {
            if (!empty($this->prefs['collapse'][$column])) {
                $this->column_style[$column]['width'] = '10px';
            }
        }

        if (($sortcol = optional_param($this->request[TABLE_VAR_SORT], '', PARAM_ALPHANUMEXT)) &&
                $this->is_sortable($sortcol) && empty($this->prefs['collapse'][$sortcol]) &&
                (isset($this->columns[$sortcol]) || in_array($sortcol, get_all_user_name_fields())
                && isset($this->columns['fullname']))) {

            if (array_key_exists($sortcol, $this->prefs['sortby'])) {
                // This key already exists somewhere. Change its sortorder and bring it to the top.
                $sortorder = $this->prefs['sortby'][$sortcol] == SORT_ASC ? SORT_DESC : SORT_ASC;
                unset($this->prefs['sortby'][$sortcol]);
                $this->prefs['sortby'] = array_merge(array($sortcol => $sortorder), $this->prefs['sortby']);
            } else {
                // Key doesn't exist, so just add it to the beginning of the array, ascending order
                $this->prefs['sortby'] = array_merge(array($sortcol => SORT_ASC), $this->prefs['sortby']);
            }

            // Finally, make sure that no more than $this->maxsortkeys are present into the array
            $this->prefs['sortby'] = array_slice($this->prefs['sortby'], 0, $this->maxsortkeys);
        }

        // MDL-35375 - If a default order is defined and it is not in the current list of order by columns, add it at the end.
        // This prevents results from being returned in a random order if the only order by column contains equal values.
        if (!empty($this->sort_default_column))  {
            if (!array_key_exists($this->sort_default_column, $this->prefs['sortby'])) {
                $defaultsort = array($this->sort_default_column => $this->sort_default_order);
                $this->prefs['sortby'] = array_merge($this->prefs['sortby'], $defaultsort);
            }
        }

        $ilast = optional_param($this->request[TABLE_VAR_ILAST], null, PARAM_RAW);
        if (!is_null($ilast) && ($ilast ==='' || strpos(get_string('alphabet', 'langconfig'), $ilast) !== false)) {
            $this->prefs['i_last'] = $ilast;
        }

        $ifirst = optional_param($this->request[TABLE_VAR_IFIRST], null, PARAM_RAW);
        if (!is_null($ifirst) && ($ifirst === '' || strpos(get_string('alphabet', 'langconfig'), $ifirst) !== false)) {
            $this->prefs['i_first'] = $ifirst;
        }

        // Save user preferences if they have changed.
        if ($this->prefs != $oldprefs) {
            if ($this->persistent) {
                set_user_preference('flextable_' . $this->uniqueid, json_encode($this->prefs));
            } else {
                $SESSION->flextable[$this->uniqueid] = $this->prefs;
            }
        }
        unset($oldprefs);

        if (empty($this->baseurl)) {
            debugging('You should set baseurl when using flexible_table.');
            global $PAGE;
            $this->baseurl = $PAGE->url;
        }

        $this->currpage = optional_param($this->request[TABLE_VAR_PAGE], 0, PARAM_INT);
        $this->setup = true;

        // Always introduce the "flexible" class for the table if not specified
        if (empty($this->attributes)) {
            $this->attributes['class'] = 'flexible';
        } else if (!isset($this->attributes['class'])) {
            $this->attributes['class'] = 'flexible';
        } else if (!in_array('flexible', explode(' ', $this->attributes['class']))) {
            $this->attributes['class'] = trim('flexible ' . $this->attributes['class']);
        }
    }
398562
protected function setup()
    {
        // Check if a valid access token exists.
        if (!$this->accessToken || $this->accessToken->expired()) {
            // Refresh is successful unless explicitly set to false.
            $refreshSuccess = true;

            // Check if a valid refresh token exists.
            if ($this->refreshToken && $this->refreshToken->getToken()) {
                // Attempt to use the refresh token.
                try {
                    $this->refresh();
                } catch (RequestException $e) {
                    // Check if the exception is due to an HTTP 403.
                    if ($e->getCode() == 403) {
                        $response = $e->getResponse();
                        $json = json_decode($response->getBody());
                        $body = $json->{'nl.divide.iq'};

                        // Check if the error is indeed a "TokenExpired" error,
                        // as expected.
                        if ($body->answer == 'TokenExpired') {
                            // Token is expired; refreshing unsuccessful.
                            $refreshSuccess = false;
                        } else {
                            // Unexpected error. Pass it up the stack. This
                            // might be a "TokenEmpty" error, but that would
                            // still be unexpected, because the token value was
                            // checked beforehand.
                            throw $e;
                        }
                    } else {
                        // Unexpected error. Pass it up the stack.
                        throw $e;
                    }
                }
            } else {
                // There is no refresh token to use; refreshing unsuccessful.
                $refreshSuccess = false;
            }

            // If refreshing failed, login from scratch and then authenticate.
            if (!$refreshSuccess) {
                $this->login()->authenticate();
            }
        }

        // Request the settings if needed.
        if (!$this->settings) {
            $response = $this->client->get('settings', [
                'headers' => ['Authentication' => $this->accessToken->getToken()],
            ]);

            $json = json_decode($response->getBody());
            $body = $json->{'nl.divide.iq'};
            $services = [];
            foreach ($body->services as $service) {
                $services[] = $service->code;
            }

            // Create new settings object.
            $this->settings = new Settings($services, $body->settings_updated);
        }
    }
887015
def setup(self, app):
        """"""
        super().setup(app)

        if self.cfg.secret == 'InsecureSecret':
            app.logger.warning(
                'Use insecure secret key. Change SESSION_SECRET option in configuration.')

        self._user_loader = asyncio.coroutine(lambda id_: id_)  # noqa

        app.on_response_prepare.append(self.save)

        if self.cfg.auto_load:
            app.middlewares.append(self._middleware)
1266158
def ssh_session(key_filename,
                username,
                ip_address,
                *cli):
    
    local('ssh -t -i %s %s@%s %s' % (key_filename,
                                     username,
                                     ip_address,
                                     "".join(chain.from_iterable(cli))))
627023
def main(global_settings, **settings):
    """"""
    my_session_factory = SignedCookieSessionFactory('itsaseekreet')
    # Add session engine
    config = Configurator(
        settings=settings,
        session_factory=my_session_factory
    )
    # Add static and templates
    config.add_static_view(name='static', path='static')
    config.include('pyramid_jinja2')
    config.add_jinja2_search_path('templates')
    config.include('ps_crud')

    # Setting up pyramid_sacrud
    config.include('pyramid_sacrud', route_prefix='admin')
    settings = config.get_settings()
    settings['pyramid_sacrud.models'] = (
        ('Docker', [Image(), ]),
    )

    # Make app
    config.scan('views')
    return config.make_wsgi_app()