Parse token and secret from raw token response.
188407
def parse_raw_token(self, raw_token):
        """"""
        if raw_token is None:
            return (None, None, None)
        # Load as json first then parse as query string
        try:
            token_data = json.loads(raw_token)
        except ValueError:
            qs = parse_qs(raw_token)
            token = qs.get('access_token', [None])[0]
            refresh_token = qs.get('refresh_token', [None])[0]
            expires_at = qs.get(self.expires_in_key, [None])[0]
        else:
            token = token_data.get('access_token', None)
            refresh_token = token_data.get('refresh_token', None)
            expires_at = token_data.get(self.expires_in_key, None)

        if expires_at:
            expires_at = timezone.now() + timedelta(seconds=int(expires_at))

        return (token, refresh_token, expires_at)
1237949
def get_token(self, payload):
        """"""

        auth = None
        if self.get_settings('OIDC_TOKEN_USE_BASIC_AUTH', False):
            # When Basic auth is defined, create the Auth Header and remove secret from payload.
            user = payload.get('client_id')
            pw = payload.get('client_secret')

            auth = HTTPBasicAuth(user, pw)
            del payload['client_secret']

        response = requests.post(
            self.OIDC_OP_TOKEN_ENDPOINT,
            data=payload,
            auth=auth,
            verify=self.get_settings('OIDC_VERIFY_SSL', True))
        response.raise_for_status()
        return response.json()
919321
def parse_header(cls, value='*/*'):
        """"""
        yield from sorted((
            cls.from_string(token.strip())
            for token in value.split(',')
            if token.strip()
        ), reverse=True)
341096
def tokhex(length=10, urlsafe=False):
    
    if urlsafe is True:
        return secrets.token_urlsafe(length)
    return secrets.token_hex(length)
814967
def parse_response(response):
    
    if isinstance(response, tuple):
        if len(response) > 2:
            return response[0], response[1], response[2]
        elif len(response) > 1:
            return response[0], response[1], {}
    try:
        return response.data, response.status_code, response.headers
    except AttributeError:
        return response, 200, {}
474215
def parse_auth_token(self, auth_token):
        
        # remove the random security key value from the front of the auth_token
        auth_token_cleaned = auth_token.split('-', 1)[1]
        # URL Decode the Auth Token
        auth_token_decoded = self.url_decode(auth_token_cleaned)
        # Create a new dict to hold the response.
        auth_dict = {}

        # Parse the token
        for key_value in auth_token_decoded.split("&"):
            key_value_list = key_value.split("=")
            # check for valid token parts
            if len(key_value_list) == 2 and type(key_value_list[0]) in [text_type, binary_type]:
                auth_dict[key_value_list[0]] = key_value_list[1]

        # Return the dict of key/values in the token.
        return auth_dict
728491
def _get_token(url, email, secret_key):
    '''
    
    '''
    url = urlparse.urljoin(url, 'authenticate')
    data_dict = {"email": email, "secret_key": secret_key}
    query = salt.utils.http.query(url, data=data_dict, method='POST',
                                  decode=True)
    error = query.get('error')
    if error:
        log.error('Cannot obtain NSoT authentication token due to: %s.', error)
        log.debug('Please verify NSoT URL %s is reachable and email %s is valid', url, email)
        return False
    else:
        log.debug('successfully obtained token from nsot!')
        return query['dict'].get('auth_token')
940834
def parse(cls, backend, ik, spk, spk_signature, otpks):
        

        ik = backend.decodePublicKey(ik)[0]

        spk["key"] = backend.decodePublicKey(spk["key"])[0]

        otpks = list(map(lambda otpk: {
            "key" : backend.decodePublicKey(otpk["key"])[0],
            "id"  : otpk["id"]
        }, otpks))

        return cls(ik, spk, spk_signature, otpks)
1200916
def decode_sid(cls, secret, cookie_value):
        """"""
        if len(cookie_value) > SIG_LENGTH + SID_LENGTH:
            logging.warn("cookie value is incorrect length")
            return None

        cookie_sig = cookie_value[:SIG_LENGTH]
        cookie_sid = cookie_value[SIG_LENGTH:]

        secret_bytes = secret.encode("utf-8")
        cookie_sid_bytes = cookie_sid.encode("utf-8")

        actual_sig = hmac.new(secret_bytes, cookie_sid_bytes, hashlib.sha512).hexdigest()

        if not Session.is_signature_equal(cookie_sig, actual_sig):
            return None

        return cookie_sid
590549
function Parse ( token ) {
  if ( typeof token != 'string' )
      throw new Error('JWT must be a string object')

  var parts = token.split('.')

  if (!parts.every(b64url.valid))
      throw new Error('JWT contains invalid URL safe Base64 chars')
  try {
    this.header = JSON.parse( b64url.decode( parts[0] ) )
  }
  catch (e) {
      return e
  }
  if (!this.header.typ)
      throw new Error('No "typ" in JWT header')

  if (this.header.typ == 'JWS') {
    try {
      this.payload = JSON.parse( b64url.decode( parts[1] ) )
    }
    catch (e) {
        return e
    }
    this._input = parts[0] +'.'+ parts[1]
    this.signature = parts[2]
    return this

  } else if (this.header.typ == 'JWE') {
    if (parts.length != 5)
      throw new Error('Invalid JWE token, does not have 5 components')
    this._input = parts[0] +'.'+ parts[1] +'.'+ parts[2] +'.'+ parts[3]
    this._cmk = parts[1]
    this._iv = parts[2]
    this._ciphertext = parts[3]
    this.signature = parts[4]
    return this

  } else
    throw new Error('Uknownn JWT header "typ":"'+this.header.typ+'"')
}
471177
def from_text(textring):
    """"""

    keyring = {}
    for keytext in textring:
        keyname = dns.name.from_text(keytext)
        secret = base64.decodestring(textring[keytext])
        keyring[keyname] = secret
    return keyring
73126
def parse(tokens):
    """"""
    d = collections.OrderedDict()
    prev_line = 0
    blockname = None
    blockline = None
    for token in tokens:
        if token.type == 'COMMENT':
            continue
        elif token.type == 'BLOCK':
            block = token
            blockline = token.line
            blocktype = token.value.upper()
            blockname = None
            if blocktype not in d:
                d[blocktype] = collections.OrderedDict()
        elif token.line == blockline:
            if blockname is None:
                blockname = token.value
                d[blocktype][blockname] = collections.defaultdict(list)
            else:
                d[blocktype][blockname]['info'].append(numval(token))
        elif token.line != prev_line:
            if blockname is None:
                raise ParseError("Found value outside block!")
            d[blocktype][blockname]['values'].append([numval(token)])
        else:
            if blockname is None:
                raise ParseError("Found value outside block!")
            d[blocktype][blockname]['values'][-1].append(numval(token))
        prev_line = token.line
    return d
1175073
def _decode_token(cls, token):
        
        missing_padding = len(token) % 4
        if missing_padding != 0:
            token += '=' * (4 - missing_padding)
        return json.loads(base64.b64decode(token).decode('utf-8'))
1039436
def parse(contents, tokens=None):
    """"""
    # Shortcut for users who are interested in tokens
    if tokens is None:
        tokens = [t for t in tokenize(contents)]

    token_index, body = _ast_worker(tokens, len(tokens), 0, None)

    assert token_index == len(tokens)
    assert body.arguments == []

    return ToplevelBody(statements=body.statements)
1212970
def parse(self, response):
        """"""
        info = response.get('info')
        res = self._regex.search(info)

        self._processed += int(res.group(1))
        self._failed += int(res.group(2))
        self._total += int(res.group(3))
        self._time += Decimal(res.group(4))
        self._chunk += 1
642187
def encode_token(self, token):
        """"""
        key = current_app.secret_key
        if key is None:
            raise RuntimeError(
                "please set app.secret_key before generate token")
        return jwt.encode(token, key, algorithm=self.config["algorithm"])
299212
def extract_jwt_token(self, token):
        
        # Note: we disable exp verification because we will do it ourselves
        with InvalidTokenHeader.handle_errors('failed to decode JWT token'):
            data = jwt.decode(
                token,
                self.encode_key,
                algorithms=self.allowed_algorithms,
                options={'verify_exp': False},
            )
        self._validate_jwt_data(data, access_type=AccessType.access)
        return data