Create a session identifier in memcache associated with ``ticket``.
550210
def create(self, ticket, payload=None, expires=None):
        '''
        
        '''
        if not payload:
            payload = True
        self._client.set(str(ticket), payload, expires)
63842
def _session_key(self):
        """"""

        if not hasattr(self, "_cached_session_key"):
            session_id_bytes = self.get_secure_cookie("session_id")
            session_id = None

            if session_id_bytes:
                try:
                    session_id = session_id_bytes.decode('utf-8')
                except:
                    pass

            if not session_id:
                session_id = oz.redis_sessions.random_hex(20)

            session_time = oz.settings["session_time"]
            kwargs = dict(
                name="session_id",
                value=session_id.encode('utf-8'),
                domain=oz.settings.get("cookie_domain"),
                httponly=True,
            )
            if session_time:
                kwargs["expires_days"] = round(session_time/60/60/24)

            self.set_secure_cookie(**kwargs)

            password_salt = oz.settings["session_salt"]
            self._cached_session_key = "session:%s:v4" % oz.redis_sessions.password_hash(session_id, password_salt=password_salt)

        return self._cached_session_key
1331058
def cli(env, identifier, count):
    """"""

    mgr = SoftLayer.TicketManager(env.client)

    ticket_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'ticket')
    env.fout(ticket.get_ticket_results(mgr, ticket_id, update_count=count))
478704
def attach_session(self):
        """"""
        proc = self.cmd('attach-session', '-t%s' % self.id)

        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.")
1282757
def create_ticket_str(self, prefix=None):
        
        if not prefix:
            prefix = self.model.TICKET_PREFIX
        return "%s-%d-%s" % (prefix, int(time.time()),
                             get_random_string(length=self.model.TICKET_RAND_LEN))
119753
def prepare_cache_id(self, combined_args_kw):
        ""
        cache_id = "".join(self.id(a) for a in combined_args_kw)
        return cache_id
968654
def verify_ticket(self, ticket):
        
        params = [('ticket', ticket), ('service', self.service_url)]
        if self.renew:
            params.append(('renew', 'true'))
        url = (urllib_parse.urljoin(self.server_url, 'validate') + '?' +
               urllib_parse.urlencode(params))
        page = urllib_request.urlopen(url)
        try:
            verified = page.readline().strip()
            if verified == b'yes':
                charset = self.get_page_charset(page, default="ascii")
                user = self.u(page.readline().strip(), charset)
                return user, None, None
            else:
                return None, None, None
        finally:
            page.close()
716027
def generate_session_id(self):
        """"""
        secret_key = self._config.secret_key
        while True:
            rand = os.urandom(16)
            now = time.time()
            session_id = sha1(utf8("%s%s%s%s" % (
                rand, now, self.handler.request.remote_ip, secret_key)))
            session_id = session_id.hexdigest()
            if session_id not in self.store:
                break

        return session_id
500398
def authenticate(self, request, ticket, service):
        

        User = get_user_model()
        username = _verify(ticket, service)

        if not username:
            return None

        try:
            user = User.objects.get(username__iexact=username)
        except User.DoesNotExist:
            # user will have an "unusable" password
            if settings.CAS_AUTO_CREATE_USER:
                user = User.objects.create_user(username, '')
                user.save()
            else:
                user = None
        return user
408094
def cli(env, title, subject_id, body, hardware_identifier, virtual_identifier, priority):
    """"""
    ticket_mgr = SoftLayer.TicketManager(env.client)

    if body is None:
        body = click.edit('\n\n' + ticket.TEMPLATE_MSG)
    created_ticket = ticket_mgr.create_ticket(
        title=title,
        body=body,
        subject=subject_id,
        priority=priority)

    if hardware_identifier:
        hardware_mgr = SoftLayer.HardwareManager(env.client)
        hardware_id = helpers.resolve_id(hardware_mgr.resolve_ids, hardware_identifier, 'hardware')
        ticket_mgr.attach_hardware(created_ticket['id'], hardware_id)

    if virtual_identifier:
        vs_mgr = SoftLayer.VSManager(env.client)
        vs_id = helpers.resolve_id(vs_mgr.resolve_ids, virtual_identifier, 'VS')
        ticket_mgr.attach_virtual_server(created_ticket['id'], vs_id)

    env.fout(ticket.get_ticket_results(ticket_mgr, created_ticket['id']))
455542
def authenticate(self, api_key):
        """"""
        self._api_key = api_key

        # Attach auth to session.
        self._session.auth = ('', self._api_key)

        return self._verify_api_key()
1238415
def _get_memcache_timeout(self, key, options=None):
    """"""
    timeout = ContextOptions.memcache_timeout(options)
    if timeout is None:
      timeout = self._memcache_timeout_policy(key)
    if timeout is None:
      timeout = ContextOptions.memcache_timeout(self._conn.config)
    if timeout is None:
      timeout = 0
    return timeout
1127264
def temporary_url(expires_at = Time.now + 3600)
      url = URI.escape("#{protocol}#{host(true)}/#{path_prefix}#{key}")
      signature = Signature.generate_temporary_url_signature(:bucket => name,
                                                             :resource => key,
                                                             :expires_at => expires_at,
                                                             :secret_access_key => secret_access_key)

      "#{url}?SNDAAccessKeyId=#{access_key_id}&Expires=#{expires_at.to_i.to_s}&Signature=#{signature}"
    end
269867
private function setTicket($type=false,$ticket,$appId)
	{
		$name = $this->_config['ticketName'];

		if($type){
			// add client info to old ticket
			if(!array_search($appId,$ticket['clients']))
				$ticket['clients'][] = $appId;
			$ticket['check_at'] = time();
			setcookie($name,$ticket);
			$_SESSION[$name] = $ticket;
		}else{
			// new ticket
			$expire_time = (int)$ticket['expire_time'];
			setcookie($name."['id']",$ticket['id'],time()+$expire_time);
			setcookie($name."['create_at']",$ticket['create_at'],time()+$expire_time);
			setcookie($name."['expire_time']",$ticket['expire_time'],time()+$expire_time);
			setcookie($name."['check_at']",$ticket['check_at'],time()+$expire_time);
			$i = 0;
			foreach($ticket['clients'] as $client){
				setcookie($name.'[\'clients\']['.$i.']',$client,time()+$expire_time);
				$i++;
			}
			setcookie($name."['user']",$ticket['user']); //debug
			$_SESSION[$name] = $ticket;
		}
	}
963350
def bind(self, ticket, device_id, user_id):
        
        return self._post(
            'bind',
            data={
                'ticket': ticket,
                'device_id': device_id,
                'openid': user_id
            }
        )
768219
protected function _write_memcached($session_id, $payload)
	{
		// write it to the memcached server
		if ($this->memcached->set($this->config['cookie_name'].'_'.$session_id, $payload, $this->config['expiration_time']) === false)
		{
			throw new \FuelException('Memcached returned error code "'.$this->memcached->getResultCode().'" on write. Check your configuration.');
		}
	}