partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
valid
GoogleCredentials._get_implicit_credentials
Gets credentials implicitly from the environment. Checks environment in order of precedence: - Environment variable GOOGLE_APPLICATION_CREDENTIALS pointing to a file with stored credentials information. - Stored "well known" file associated with `gcloud` command line tool. - Google App Engine (production and testing) - Google Compute Engine production environment. Raises: ApplicationDefaultCredentialsError: raised when the credentials fail to be retrieved.
oauth2client/client.py
def _get_implicit_credentials(cls): """Gets credentials implicitly from the environment. Checks environment in order of precedence: - Environment variable GOOGLE_APPLICATION_CREDENTIALS pointing to a file with stored credentials information. - Stored "well known" file associated with `gcloud` command line tool. - Google App Engine (production and testing) - Google Compute Engine production environment. Raises: ApplicationDefaultCredentialsError: raised when the credentials fail to be retrieved. """ # Environ checks (in order). environ_checkers = [ cls._implicit_credentials_from_files, cls._implicit_credentials_from_gae, cls._implicit_credentials_from_gce, ] for checker in environ_checkers: credentials = checker() if credentials is not None: return credentials # If no credentials, fail. raise ApplicationDefaultCredentialsError(ADC_HELP_MSG)
def _get_implicit_credentials(cls): """Gets credentials implicitly from the environment. Checks environment in order of precedence: - Environment variable GOOGLE_APPLICATION_CREDENTIALS pointing to a file with stored credentials information. - Stored "well known" file associated with `gcloud` command line tool. - Google App Engine (production and testing) - Google Compute Engine production environment. Raises: ApplicationDefaultCredentialsError: raised when the credentials fail to be retrieved. """ # Environ checks (in order). environ_checkers = [ cls._implicit_credentials_from_files, cls._implicit_credentials_from_gae, cls._implicit_credentials_from_gce, ] for checker in environ_checkers: credentials = checker() if credentials is not None: return credentials # If no credentials, fail. raise ApplicationDefaultCredentialsError(ADC_HELP_MSG)
[ "Gets", "credentials", "implicitly", "from", "the", "environment", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/client.py#L1234-L1261
[ "def", "_get_implicit_credentials", "(", "cls", ")", ":", "# Environ checks (in order).", "environ_checkers", "=", "[", "cls", ".", "_implicit_credentials_from_files", ",", "cls", ".", "_implicit_credentials_from_gae", ",", "cls", ".", "_implicit_credentials_from_gce", ",", "]", "for", "checker", "in", "environ_checkers", ":", "credentials", "=", "checker", "(", ")", "if", "credentials", "is", "not", "None", ":", "return", "credentials", "# If no credentials, fail.", "raise", "ApplicationDefaultCredentialsError", "(", "ADC_HELP_MSG", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
GoogleCredentials.from_stream
Create a Credentials object by reading information from a file. It returns an object of type GoogleCredentials. Args: credential_filename: the path to the file from where the credentials are to be read Raises: ApplicationDefaultCredentialsError: raised when the credentials fail to be retrieved.
oauth2client/client.py
def from_stream(credential_filename): """Create a Credentials object by reading information from a file. It returns an object of type GoogleCredentials. Args: credential_filename: the path to the file from where the credentials are to be read Raises: ApplicationDefaultCredentialsError: raised when the credentials fail to be retrieved. """ if credential_filename and os.path.isfile(credential_filename): try: return _get_application_default_credential_from_file( credential_filename) except (ApplicationDefaultCredentialsError, ValueError) as error: extra_help = (' (provided as parameter to the ' 'from_stream() method)') _raise_exception_for_reading_json(credential_filename, extra_help, error) else: raise ApplicationDefaultCredentialsError( 'The parameter passed to the from_stream() ' 'method should point to a file.')
def from_stream(credential_filename): """Create a Credentials object by reading information from a file. It returns an object of type GoogleCredentials. Args: credential_filename: the path to the file from where the credentials are to be read Raises: ApplicationDefaultCredentialsError: raised when the credentials fail to be retrieved. """ if credential_filename and os.path.isfile(credential_filename): try: return _get_application_default_credential_from_file( credential_filename) except (ApplicationDefaultCredentialsError, ValueError) as error: extra_help = (' (provided as parameter to the ' 'from_stream() method)') _raise_exception_for_reading_json(credential_filename, extra_help, error) else: raise ApplicationDefaultCredentialsError( 'The parameter passed to the from_stream() ' 'method should point to a file.')
[ "Create", "a", "Credentials", "object", "by", "reading", "information", "from", "a", "file", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/client.py#L1274-L1300
[ "def", "from_stream", "(", "credential_filename", ")", ":", "if", "credential_filename", "and", "os", ".", "path", ".", "isfile", "(", "credential_filename", ")", ":", "try", ":", "return", "_get_application_default_credential_from_file", "(", "credential_filename", ")", "except", "(", "ApplicationDefaultCredentialsError", ",", "ValueError", ")", "as", "error", ":", "extra_help", "=", "(", "' (provided as parameter to the '", "'from_stream() method)'", ")", "_raise_exception_for_reading_json", "(", "credential_filename", ",", "extra_help", ",", "error", ")", "else", ":", "raise", "ApplicationDefaultCredentialsError", "(", "'The parameter passed to the from_stream() '", "'method should point to a file.'", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
DeviceFlowInfo.FromResponse
Create a DeviceFlowInfo from a server response. The response should be a dict containing entries as described here: http://tools.ietf.org/html/draft-ietf-oauth-v2-05#section-3.7.1
oauth2client/client.py
def FromResponse(cls, response): """Create a DeviceFlowInfo from a server response. The response should be a dict containing entries as described here: http://tools.ietf.org/html/draft-ietf-oauth-v2-05#section-3.7.1 """ # device_code, user_code, and verification_url are required. kwargs = { 'device_code': response['device_code'], 'user_code': response['user_code'], } # The response may list the verification address as either # verification_url or verification_uri, so we check for both. verification_url = response.get( 'verification_url', response.get('verification_uri')) if verification_url is None: raise OAuth2DeviceCodeError( 'No verification_url provided in server response') kwargs['verification_url'] = verification_url # expires_in and interval are optional. kwargs.update({ 'interval': response.get('interval'), 'user_code_expiry': None, }) if 'expires_in' in response: kwargs['user_code_expiry'] = ( _UTCNOW() + datetime.timedelta(seconds=int(response['expires_in']))) return cls(**kwargs)
def FromResponse(cls, response): """Create a DeviceFlowInfo from a server response. The response should be a dict containing entries as described here: http://tools.ietf.org/html/draft-ietf-oauth-v2-05#section-3.7.1 """ # device_code, user_code, and verification_url are required. kwargs = { 'device_code': response['device_code'], 'user_code': response['user_code'], } # The response may list the verification address as either # verification_url or verification_uri, so we check for both. verification_url = response.get( 'verification_url', response.get('verification_uri')) if verification_url is None: raise OAuth2DeviceCodeError( 'No verification_url provided in server response') kwargs['verification_url'] = verification_url # expires_in and interval are optional. kwargs.update({ 'interval': response.get('interval'), 'user_code_expiry': None, }) if 'expires_in' in response: kwargs['user_code_expiry'] = ( _UTCNOW() + datetime.timedelta(seconds=int(response['expires_in']))) return cls(**kwargs)
[ "Create", "a", "DeviceFlowInfo", "from", "a", "server", "response", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/client.py#L1746-L1775
[ "def", "FromResponse", "(", "cls", ",", "response", ")", ":", "# device_code, user_code, and verification_url are required.", "kwargs", "=", "{", "'device_code'", ":", "response", "[", "'device_code'", "]", ",", "'user_code'", ":", "response", "[", "'user_code'", "]", ",", "}", "# The response may list the verification address as either", "# verification_url or verification_uri, so we check for both.", "verification_url", "=", "response", ".", "get", "(", "'verification_url'", ",", "response", ".", "get", "(", "'verification_uri'", ")", ")", "if", "verification_url", "is", "None", ":", "raise", "OAuth2DeviceCodeError", "(", "'No verification_url provided in server response'", ")", "kwargs", "[", "'verification_url'", "]", "=", "verification_url", "# expires_in and interval are optional.", "kwargs", ".", "update", "(", "{", "'interval'", ":", "response", ".", "get", "(", "'interval'", ")", ",", "'user_code_expiry'", ":", "None", ",", "}", ")", "if", "'expires_in'", "in", "response", ":", "kwargs", "[", "'user_code_expiry'", "]", "=", "(", "_UTCNOW", "(", ")", "+", "datetime", ".", "timedelta", "(", "seconds", "=", "int", "(", "response", "[", "'expires_in'", "]", ")", ")", ")", "return", "cls", "(", "*", "*", "kwargs", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
OAuth2WebServerFlow.step1_get_authorize_url
Returns a URI to redirect to the provider. Args: redirect_uri: string, Either the string 'urn:ietf:wg:oauth:2.0:oob' for a non-web-based application, or a URI that handles the callback from the authorization server. This parameter is deprecated, please move to passing the redirect_uri in via the constructor. state: string, Opaque state string which is passed through the OAuth2 flow and returned to the client as a query parameter in the callback. Returns: A URI as a string to redirect the user to begin the authorization flow.
oauth2client/client.py
def step1_get_authorize_url(self, redirect_uri=None, state=None): """Returns a URI to redirect to the provider. Args: redirect_uri: string, Either the string 'urn:ietf:wg:oauth:2.0:oob' for a non-web-based application, or a URI that handles the callback from the authorization server. This parameter is deprecated, please move to passing the redirect_uri in via the constructor. state: string, Opaque state string which is passed through the OAuth2 flow and returned to the client as a query parameter in the callback. Returns: A URI as a string to redirect the user to begin the authorization flow. """ if redirect_uri is not None: logger.warning(( 'The redirect_uri parameter for ' 'OAuth2WebServerFlow.step1_get_authorize_url is deprecated. ' 'Please move to passing the redirect_uri in via the ' 'constructor.')) self.redirect_uri = redirect_uri if self.redirect_uri is None: raise ValueError('The value of redirect_uri must not be None.') query_params = { 'client_id': self.client_id, 'redirect_uri': self.redirect_uri, 'scope': self.scope, } if state is not None: query_params['state'] = state if self.login_hint is not None: query_params['login_hint'] = self.login_hint if self._pkce: if not self.code_verifier: self.code_verifier = _pkce.code_verifier() challenge = _pkce.code_challenge(self.code_verifier) query_params['code_challenge'] = challenge query_params['code_challenge_method'] = 'S256' query_params.update(self.params) return _helpers.update_query_params(self.auth_uri, query_params)
def step1_get_authorize_url(self, redirect_uri=None, state=None): """Returns a URI to redirect to the provider. Args: redirect_uri: string, Either the string 'urn:ietf:wg:oauth:2.0:oob' for a non-web-based application, or a URI that handles the callback from the authorization server. This parameter is deprecated, please move to passing the redirect_uri in via the constructor. state: string, Opaque state string which is passed through the OAuth2 flow and returned to the client as a query parameter in the callback. Returns: A URI as a string to redirect the user to begin the authorization flow. """ if redirect_uri is not None: logger.warning(( 'The redirect_uri parameter for ' 'OAuth2WebServerFlow.step1_get_authorize_url is deprecated. ' 'Please move to passing the redirect_uri in via the ' 'constructor.')) self.redirect_uri = redirect_uri if self.redirect_uri is None: raise ValueError('The value of redirect_uri must not be None.') query_params = { 'client_id': self.client_id, 'redirect_uri': self.redirect_uri, 'scope': self.scope, } if state is not None: query_params['state'] = state if self.login_hint is not None: query_params['login_hint'] = self.login_hint if self._pkce: if not self.code_verifier: self.code_verifier = _pkce.code_verifier() challenge = _pkce.code_challenge(self.code_verifier) query_params['code_challenge'] = challenge query_params['code_challenge_method'] = 'S256' query_params.update(self.params) return _helpers.update_query_params(self.auth_uri, query_params)
[ "Returns", "a", "URI", "to", "redirect", "to", "the", "provider", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/client.py#L1896-L1941
[ "def", "step1_get_authorize_url", "(", "self", ",", "redirect_uri", "=", "None", ",", "state", "=", "None", ")", ":", "if", "redirect_uri", "is", "not", "None", ":", "logger", ".", "warning", "(", "(", "'The redirect_uri parameter for '", "'OAuth2WebServerFlow.step1_get_authorize_url is deprecated. '", "'Please move to passing the redirect_uri in via the '", "'constructor.'", ")", ")", "self", ".", "redirect_uri", "=", "redirect_uri", "if", "self", ".", "redirect_uri", "is", "None", ":", "raise", "ValueError", "(", "'The value of redirect_uri must not be None.'", ")", "query_params", "=", "{", "'client_id'", ":", "self", ".", "client_id", ",", "'redirect_uri'", ":", "self", ".", "redirect_uri", ",", "'scope'", ":", "self", ".", "scope", ",", "}", "if", "state", "is", "not", "None", ":", "query_params", "[", "'state'", "]", "=", "state", "if", "self", ".", "login_hint", "is", "not", "None", ":", "query_params", "[", "'login_hint'", "]", "=", "self", ".", "login_hint", "if", "self", ".", "_pkce", ":", "if", "not", "self", ".", "code_verifier", ":", "self", ".", "code_verifier", "=", "_pkce", ".", "code_verifier", "(", ")", "challenge", "=", "_pkce", ".", "code_challenge", "(", "self", ".", "code_verifier", ")", "query_params", "[", "'code_challenge'", "]", "=", "challenge", "query_params", "[", "'code_challenge_method'", "]", "=", "'S256'", "query_params", ".", "update", "(", "self", ".", "params", ")", "return", "_helpers", ".", "update_query_params", "(", "self", ".", "auth_uri", ",", "query_params", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
OAuth2WebServerFlow.step1_get_device_and_user_codes
Returns a user code and the verification URL where to enter it Returns: A user code as a string for the user to authorize the application An URL as a string where the user has to enter the code
oauth2client/client.py
def step1_get_device_and_user_codes(self, http=None): """Returns a user code and the verification URL where to enter it Returns: A user code as a string for the user to authorize the application An URL as a string where the user has to enter the code """ if self.device_uri is None: raise ValueError('The value of device_uri must not be None.') body = urllib.parse.urlencode({ 'client_id': self.client_id, 'scope': self.scope, }) headers = { 'content-type': 'application/x-www-form-urlencoded', } if self.user_agent is not None: headers['user-agent'] = self.user_agent if http is None: http = transport.get_http_object() resp, content = transport.request( http, self.device_uri, method='POST', body=body, headers=headers) content = _helpers._from_bytes(content) if resp.status == http_client.OK: try: flow_info = json.loads(content) except ValueError as exc: raise OAuth2DeviceCodeError( 'Could not parse server response as JSON: "{0}", ' 'error: "{1}"'.format(content, exc)) return DeviceFlowInfo.FromResponse(flow_info) else: error_msg = 'Invalid response {0}.'.format(resp.status) try: error_dict = json.loads(content) if 'error' in error_dict: error_msg += ' Error: {0}'.format(error_dict['error']) except ValueError: # Couldn't decode a JSON response, stick with the # default message. pass raise OAuth2DeviceCodeError(error_msg)
def step1_get_device_and_user_codes(self, http=None): """Returns a user code and the verification URL where to enter it Returns: A user code as a string for the user to authorize the application An URL as a string where the user has to enter the code """ if self.device_uri is None: raise ValueError('The value of device_uri must not be None.') body = urllib.parse.urlencode({ 'client_id': self.client_id, 'scope': self.scope, }) headers = { 'content-type': 'application/x-www-form-urlencoded', } if self.user_agent is not None: headers['user-agent'] = self.user_agent if http is None: http = transport.get_http_object() resp, content = transport.request( http, self.device_uri, method='POST', body=body, headers=headers) content = _helpers._from_bytes(content) if resp.status == http_client.OK: try: flow_info = json.loads(content) except ValueError as exc: raise OAuth2DeviceCodeError( 'Could not parse server response as JSON: "{0}", ' 'error: "{1}"'.format(content, exc)) return DeviceFlowInfo.FromResponse(flow_info) else: error_msg = 'Invalid response {0}.'.format(resp.status) try: error_dict = json.loads(content) if 'error' in error_dict: error_msg += ' Error: {0}'.format(error_dict['error']) except ValueError: # Couldn't decode a JSON response, stick with the # default message. pass raise OAuth2DeviceCodeError(error_msg)
[ "Returns", "a", "user", "code", "and", "the", "verification", "URL", "where", "to", "enter", "it" ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/client.py#L1944-L1989
[ "def", "step1_get_device_and_user_codes", "(", "self", ",", "http", "=", "None", ")", ":", "if", "self", ".", "device_uri", "is", "None", ":", "raise", "ValueError", "(", "'The value of device_uri must not be None.'", ")", "body", "=", "urllib", ".", "parse", ".", "urlencode", "(", "{", "'client_id'", ":", "self", ".", "client_id", ",", "'scope'", ":", "self", ".", "scope", ",", "}", ")", "headers", "=", "{", "'content-type'", ":", "'application/x-www-form-urlencoded'", ",", "}", "if", "self", ".", "user_agent", "is", "not", "None", ":", "headers", "[", "'user-agent'", "]", "=", "self", ".", "user_agent", "if", "http", "is", "None", ":", "http", "=", "transport", ".", "get_http_object", "(", ")", "resp", ",", "content", "=", "transport", ".", "request", "(", "http", ",", "self", ".", "device_uri", ",", "method", "=", "'POST'", ",", "body", "=", "body", ",", "headers", "=", "headers", ")", "content", "=", "_helpers", ".", "_from_bytes", "(", "content", ")", "if", "resp", ".", "status", "==", "http_client", ".", "OK", ":", "try", ":", "flow_info", "=", "json", ".", "loads", "(", "content", ")", "except", "ValueError", "as", "exc", ":", "raise", "OAuth2DeviceCodeError", "(", "'Could not parse server response as JSON: \"{0}\", '", "'error: \"{1}\"'", ".", "format", "(", "content", ",", "exc", ")", ")", "return", "DeviceFlowInfo", ".", "FromResponse", "(", "flow_info", ")", "else", ":", "error_msg", "=", "'Invalid response {0}.'", ".", "format", "(", "resp", ".", "status", ")", "try", ":", "error_dict", "=", "json", ".", "loads", "(", "content", ")", "if", "'error'", "in", "error_dict", ":", "error_msg", "+=", "' Error: {0}'", ".", "format", "(", "error_dict", "[", "'error'", "]", ")", "except", "ValueError", ":", "# Couldn't decode a JSON response, stick with the", "# default message.", "pass", "raise", "OAuth2DeviceCodeError", "(", "error_msg", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
OAuth2WebServerFlow.step2_exchange
Exchanges a code for OAuth2Credentials. Args: code: string, a dict-like object, or None. For a non-device flow, this is either the response code as a string, or a dictionary of query parameters to the redirect_uri. For a device flow, this should be None. http: httplib2.Http, optional http instance to use when fetching credentials. device_flow_info: DeviceFlowInfo, return value from step1 in the case of a device flow. Returns: An OAuth2Credentials object that can be used to authorize requests. Raises: FlowExchangeError: if a problem occurred exchanging the code for a refresh_token. ValueError: if code and device_flow_info are both provided or both missing.
oauth2client/client.py
def step2_exchange(self, code=None, http=None, device_flow_info=None): """Exchanges a code for OAuth2Credentials. Args: code: string, a dict-like object, or None. For a non-device flow, this is either the response code as a string, or a dictionary of query parameters to the redirect_uri. For a device flow, this should be None. http: httplib2.Http, optional http instance to use when fetching credentials. device_flow_info: DeviceFlowInfo, return value from step1 in the case of a device flow. Returns: An OAuth2Credentials object that can be used to authorize requests. Raises: FlowExchangeError: if a problem occurred exchanging the code for a refresh_token. ValueError: if code and device_flow_info are both provided or both missing. """ if code is None and device_flow_info is None: raise ValueError('No code or device_flow_info provided.') if code is not None and device_flow_info is not None: raise ValueError('Cannot provide both code and device_flow_info.') if code is None: code = device_flow_info.device_code elif not isinstance(code, (six.string_types, six.binary_type)): if 'code' not in code: raise FlowExchangeError(code.get( 'error', 'No code was supplied in the query parameters.')) code = code['code'] post_data = { 'client_id': self.client_id, 'code': code, 'scope': self.scope, } if self.client_secret is not None: post_data['client_secret'] = self.client_secret if self._pkce: post_data['code_verifier'] = self.code_verifier if device_flow_info is not None: post_data['grant_type'] = 'http://oauth.net/grant_type/device/1.0' else: post_data['grant_type'] = 'authorization_code' post_data['redirect_uri'] = self.redirect_uri body = urllib.parse.urlencode(post_data) headers = { 'content-type': 'application/x-www-form-urlencoded', } if self.authorization_header is not None: headers['Authorization'] = self.authorization_header if self.user_agent is not None: headers['user-agent'] = self.user_agent if http is None: http = transport.get_http_object() resp, content = transport.request( http, self.token_uri, method='POST', body=body, headers=headers) d = _parse_exchange_token_response(content) if resp.status == http_client.OK and 'access_token' in d: access_token = d['access_token'] refresh_token = d.get('refresh_token', None) if not refresh_token: logger.info( 'Received token response with no refresh_token. Consider ' "reauthenticating with prompt='consent'.") token_expiry = None if 'expires_in' in d: delta = datetime.timedelta(seconds=int(d['expires_in'])) token_expiry = delta + _UTCNOW() extracted_id_token = None id_token_jwt = None if 'id_token' in d: extracted_id_token = _extract_id_token(d['id_token']) id_token_jwt = d['id_token'] logger.info('Successfully retrieved access token') return OAuth2Credentials( access_token, self.client_id, self.client_secret, refresh_token, token_expiry, self.token_uri, self.user_agent, revoke_uri=self.revoke_uri, id_token=extracted_id_token, id_token_jwt=id_token_jwt, token_response=d, scopes=self.scope, token_info_uri=self.token_info_uri) else: logger.info('Failed to retrieve access token: %s', content) if 'error' in d: # you never know what those providers got to say error_msg = (str(d['error']) + str(d.get('error_description', ''))) else: error_msg = 'Invalid response: {0}.'.format(str(resp.status)) raise FlowExchangeError(error_msg)
def step2_exchange(self, code=None, http=None, device_flow_info=None): """Exchanges a code for OAuth2Credentials. Args: code: string, a dict-like object, or None. For a non-device flow, this is either the response code as a string, or a dictionary of query parameters to the redirect_uri. For a device flow, this should be None. http: httplib2.Http, optional http instance to use when fetching credentials. device_flow_info: DeviceFlowInfo, return value from step1 in the case of a device flow. Returns: An OAuth2Credentials object that can be used to authorize requests. Raises: FlowExchangeError: if a problem occurred exchanging the code for a refresh_token. ValueError: if code and device_flow_info are both provided or both missing. """ if code is None and device_flow_info is None: raise ValueError('No code or device_flow_info provided.') if code is not None and device_flow_info is not None: raise ValueError('Cannot provide both code and device_flow_info.') if code is None: code = device_flow_info.device_code elif not isinstance(code, (six.string_types, six.binary_type)): if 'code' not in code: raise FlowExchangeError(code.get( 'error', 'No code was supplied in the query parameters.')) code = code['code'] post_data = { 'client_id': self.client_id, 'code': code, 'scope': self.scope, } if self.client_secret is not None: post_data['client_secret'] = self.client_secret if self._pkce: post_data['code_verifier'] = self.code_verifier if device_flow_info is not None: post_data['grant_type'] = 'http://oauth.net/grant_type/device/1.0' else: post_data['grant_type'] = 'authorization_code' post_data['redirect_uri'] = self.redirect_uri body = urllib.parse.urlencode(post_data) headers = { 'content-type': 'application/x-www-form-urlencoded', } if self.authorization_header is not None: headers['Authorization'] = self.authorization_header if self.user_agent is not None: headers['user-agent'] = self.user_agent if http is None: http = transport.get_http_object() resp, content = transport.request( http, self.token_uri, method='POST', body=body, headers=headers) d = _parse_exchange_token_response(content) if resp.status == http_client.OK and 'access_token' in d: access_token = d['access_token'] refresh_token = d.get('refresh_token', None) if not refresh_token: logger.info( 'Received token response with no refresh_token. Consider ' "reauthenticating with prompt='consent'.") token_expiry = None if 'expires_in' in d: delta = datetime.timedelta(seconds=int(d['expires_in'])) token_expiry = delta + _UTCNOW() extracted_id_token = None id_token_jwt = None if 'id_token' in d: extracted_id_token = _extract_id_token(d['id_token']) id_token_jwt = d['id_token'] logger.info('Successfully retrieved access token') return OAuth2Credentials( access_token, self.client_id, self.client_secret, refresh_token, token_expiry, self.token_uri, self.user_agent, revoke_uri=self.revoke_uri, id_token=extracted_id_token, id_token_jwt=id_token_jwt, token_response=d, scopes=self.scope, token_info_uri=self.token_info_uri) else: logger.info('Failed to retrieve access token: %s', content) if 'error' in d: # you never know what those providers got to say error_msg = (str(d['error']) + str(d.get('error_description', ''))) else: error_msg = 'Invalid response: {0}.'.format(str(resp.status)) raise FlowExchangeError(error_msg)
[ "Exchanges", "a", "code", "for", "OAuth2Credentials", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/client.py#L1992-L2089
[ "def", "step2_exchange", "(", "self", ",", "code", "=", "None", ",", "http", "=", "None", ",", "device_flow_info", "=", "None", ")", ":", "if", "code", "is", "None", "and", "device_flow_info", "is", "None", ":", "raise", "ValueError", "(", "'No code or device_flow_info provided.'", ")", "if", "code", "is", "not", "None", "and", "device_flow_info", "is", "not", "None", ":", "raise", "ValueError", "(", "'Cannot provide both code and device_flow_info.'", ")", "if", "code", "is", "None", ":", "code", "=", "device_flow_info", ".", "device_code", "elif", "not", "isinstance", "(", "code", ",", "(", "six", ".", "string_types", ",", "six", ".", "binary_type", ")", ")", ":", "if", "'code'", "not", "in", "code", ":", "raise", "FlowExchangeError", "(", "code", ".", "get", "(", "'error'", ",", "'No code was supplied in the query parameters.'", ")", ")", "code", "=", "code", "[", "'code'", "]", "post_data", "=", "{", "'client_id'", ":", "self", ".", "client_id", ",", "'code'", ":", "code", ",", "'scope'", ":", "self", ".", "scope", ",", "}", "if", "self", ".", "client_secret", "is", "not", "None", ":", "post_data", "[", "'client_secret'", "]", "=", "self", ".", "client_secret", "if", "self", ".", "_pkce", ":", "post_data", "[", "'code_verifier'", "]", "=", "self", ".", "code_verifier", "if", "device_flow_info", "is", "not", "None", ":", "post_data", "[", "'grant_type'", "]", "=", "'http://oauth.net/grant_type/device/1.0'", "else", ":", "post_data", "[", "'grant_type'", "]", "=", "'authorization_code'", "post_data", "[", "'redirect_uri'", "]", "=", "self", ".", "redirect_uri", "body", "=", "urllib", ".", "parse", ".", "urlencode", "(", "post_data", ")", "headers", "=", "{", "'content-type'", ":", "'application/x-www-form-urlencoded'", ",", "}", "if", "self", ".", "authorization_header", "is", "not", "None", ":", "headers", "[", "'Authorization'", "]", "=", "self", ".", "authorization_header", "if", "self", ".", "user_agent", "is", "not", "None", ":", "headers", "[", "'user-agent'", "]", "=", "self", ".", "user_agent", "if", "http", "is", "None", ":", "http", "=", "transport", ".", "get_http_object", "(", ")", "resp", ",", "content", "=", "transport", ".", "request", "(", "http", ",", "self", ".", "token_uri", ",", "method", "=", "'POST'", ",", "body", "=", "body", ",", "headers", "=", "headers", ")", "d", "=", "_parse_exchange_token_response", "(", "content", ")", "if", "resp", ".", "status", "==", "http_client", ".", "OK", "and", "'access_token'", "in", "d", ":", "access_token", "=", "d", "[", "'access_token'", "]", "refresh_token", "=", "d", ".", "get", "(", "'refresh_token'", ",", "None", ")", "if", "not", "refresh_token", ":", "logger", ".", "info", "(", "'Received token response with no refresh_token. Consider '", "\"reauthenticating with prompt='consent'.\"", ")", "token_expiry", "=", "None", "if", "'expires_in'", "in", "d", ":", "delta", "=", "datetime", ".", "timedelta", "(", "seconds", "=", "int", "(", "d", "[", "'expires_in'", "]", ")", ")", "token_expiry", "=", "delta", "+", "_UTCNOW", "(", ")", "extracted_id_token", "=", "None", "id_token_jwt", "=", "None", "if", "'id_token'", "in", "d", ":", "extracted_id_token", "=", "_extract_id_token", "(", "d", "[", "'id_token'", "]", ")", "id_token_jwt", "=", "d", "[", "'id_token'", "]", "logger", ".", "info", "(", "'Successfully retrieved access token'", ")", "return", "OAuth2Credentials", "(", "access_token", ",", "self", ".", "client_id", ",", "self", ".", "client_secret", ",", "refresh_token", ",", "token_expiry", ",", "self", ".", "token_uri", ",", "self", ".", "user_agent", ",", "revoke_uri", "=", "self", ".", "revoke_uri", ",", "id_token", "=", "extracted_id_token", ",", "id_token_jwt", "=", "id_token_jwt", ",", "token_response", "=", "d", ",", "scopes", "=", "self", ".", "scope", ",", "token_info_uri", "=", "self", ".", "token_info_uri", ")", "else", ":", "logger", ".", "info", "(", "'Failed to retrieve access token: %s'", ",", "content", ")", "if", "'error'", "in", "d", ":", "# you never know what those providers got to say", "error_msg", "=", "(", "str", "(", "d", "[", "'error'", "]", ")", "+", "str", "(", "d", ".", "get", "(", "'error_description'", ",", "''", ")", ")", ")", "else", ":", "error_msg", "=", "'Invalid response: {0}.'", ".", "format", "(", "str", "(", "resp", ".", "status", ")", ")", "raise", "FlowExchangeError", "(", "error_msg", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
RsaVerifier.verify
Verifies a message against a signature. Args: message: string or bytes, The message to verify. If string, will be encoded to bytes as utf-8. signature: string or bytes, The signature on the message. If string, will be encoded to bytes as utf-8. Returns: True if message was signed by the private key associated with the public key that this object was constructed with.
oauth2client/_pure_python_crypt.py
def verify(self, message, signature): """Verifies a message against a signature. Args: message: string or bytes, The message to verify. If string, will be encoded to bytes as utf-8. signature: string or bytes, The signature on the message. If string, will be encoded to bytes as utf-8. Returns: True if message was signed by the private key associated with the public key that this object was constructed with. """ message = _helpers._to_bytes(message, encoding='utf-8') try: return rsa.pkcs1.verify(message, signature, self._pubkey) except (ValueError, rsa.pkcs1.VerificationError): return False
def verify(self, message, signature): """Verifies a message against a signature. Args: message: string or bytes, The message to verify. If string, will be encoded to bytes as utf-8. signature: string or bytes, The signature on the message. If string, will be encoded to bytes as utf-8. Returns: True if message was signed by the private key associated with the public key that this object was constructed with. """ message = _helpers._to_bytes(message, encoding='utf-8') try: return rsa.pkcs1.verify(message, signature, self._pubkey) except (ValueError, rsa.pkcs1.VerificationError): return False
[ "Verifies", "a", "message", "against", "a", "signature", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/_pure_python_crypt.py#L75-L92
[ "def", "verify", "(", "self", ",", "message", ",", "signature", ")", ":", "message", "=", "_helpers", ".", "_to_bytes", "(", "message", ",", "encoding", "=", "'utf-8'", ")", "try", ":", "return", "rsa", ".", "pkcs1", ".", "verify", "(", "message", ",", "signature", ",", "self", ".", "_pubkey", ")", "except", "(", "ValueError", ",", "rsa", ".", "pkcs1", ".", "VerificationError", ")", ":", "return", "False" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
RsaVerifier.from_string
Construct an RsaVerifier instance from a string. Args: key_pem: string, public key in PEM format. is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it is expected to be an RSA key in PEM format. Returns: RsaVerifier instance. Raises: ValueError: if the key_pem can't be parsed. In either case, error will begin with 'No PEM start marker'. If ``is_x509_cert`` is True, will fail to find the "-----BEGIN CERTIFICATE-----" error, otherwise fails to find "-----BEGIN RSA PUBLIC KEY-----".
oauth2client/_pure_python_crypt.py
def from_string(cls, key_pem, is_x509_cert): """Construct an RsaVerifier instance from a string. Args: key_pem: string, public key in PEM format. is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it is expected to be an RSA key in PEM format. Returns: RsaVerifier instance. Raises: ValueError: if the key_pem can't be parsed. In either case, error will begin with 'No PEM start marker'. If ``is_x509_cert`` is True, will fail to find the "-----BEGIN CERTIFICATE-----" error, otherwise fails to find "-----BEGIN RSA PUBLIC KEY-----". """ key_pem = _helpers._to_bytes(key_pem) if is_x509_cert: der = rsa.pem.load_pem(key_pem, 'CERTIFICATE') asn1_cert, remaining = decoder.decode(der, asn1Spec=Certificate()) if remaining != b'': raise ValueError('Unused bytes', remaining) cert_info = asn1_cert['tbsCertificate']['subjectPublicKeyInfo'] key_bytes = _bit_list_to_bytes(cert_info['subjectPublicKey']) pubkey = rsa.PublicKey.load_pkcs1(key_bytes, 'DER') else: pubkey = rsa.PublicKey.load_pkcs1(key_pem, 'PEM') return cls(pubkey)
def from_string(cls, key_pem, is_x509_cert): """Construct an RsaVerifier instance from a string. Args: key_pem: string, public key in PEM format. is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it is expected to be an RSA key in PEM format. Returns: RsaVerifier instance. Raises: ValueError: if the key_pem can't be parsed. In either case, error will begin with 'No PEM start marker'. If ``is_x509_cert`` is True, will fail to find the "-----BEGIN CERTIFICATE-----" error, otherwise fails to find "-----BEGIN RSA PUBLIC KEY-----". """ key_pem = _helpers._to_bytes(key_pem) if is_x509_cert: der = rsa.pem.load_pem(key_pem, 'CERTIFICATE') asn1_cert, remaining = decoder.decode(der, asn1Spec=Certificate()) if remaining != b'': raise ValueError('Unused bytes', remaining) cert_info = asn1_cert['tbsCertificate']['subjectPublicKeyInfo'] key_bytes = _bit_list_to_bytes(cert_info['subjectPublicKey']) pubkey = rsa.PublicKey.load_pkcs1(key_bytes, 'DER') else: pubkey = rsa.PublicKey.load_pkcs1(key_pem, 'PEM') return cls(pubkey)
[ "Construct", "an", "RsaVerifier", "instance", "from", "a", "string", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/_pure_python_crypt.py#L95-L125
[ "def", "from_string", "(", "cls", ",", "key_pem", ",", "is_x509_cert", ")", ":", "key_pem", "=", "_helpers", ".", "_to_bytes", "(", "key_pem", ")", "if", "is_x509_cert", ":", "der", "=", "rsa", ".", "pem", ".", "load_pem", "(", "key_pem", ",", "'CERTIFICATE'", ")", "asn1_cert", ",", "remaining", "=", "decoder", ".", "decode", "(", "der", ",", "asn1Spec", "=", "Certificate", "(", ")", ")", "if", "remaining", "!=", "b''", ":", "raise", "ValueError", "(", "'Unused bytes'", ",", "remaining", ")", "cert_info", "=", "asn1_cert", "[", "'tbsCertificate'", "]", "[", "'subjectPublicKeyInfo'", "]", "key_bytes", "=", "_bit_list_to_bytes", "(", "cert_info", "[", "'subjectPublicKey'", "]", ")", "pubkey", "=", "rsa", ".", "PublicKey", ".", "load_pkcs1", "(", "key_bytes", ",", "'DER'", ")", "else", ":", "pubkey", "=", "rsa", ".", "PublicKey", ".", "load_pkcs1", "(", "key_pem", ",", "'PEM'", ")", "return", "cls", "(", "pubkey", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
RsaSigner.sign
Signs a message. Args: message: bytes, Message to be signed. Returns: string, The signature of the message for the given key.
oauth2client/_pure_python_crypt.py
def sign(self, message): """Signs a message. Args: message: bytes, Message to be signed. Returns: string, The signature of the message for the given key. """ message = _helpers._to_bytes(message, encoding='utf-8') return rsa.pkcs1.sign(message, self._key, 'SHA-256')
def sign(self, message): """Signs a message. Args: message: bytes, Message to be signed. Returns: string, The signature of the message for the given key. """ message = _helpers._to_bytes(message, encoding='utf-8') return rsa.pkcs1.sign(message, self._key, 'SHA-256')
[ "Signs", "a", "message", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/_pure_python_crypt.py#L138-L148
[ "def", "sign", "(", "self", ",", "message", ")", ":", "message", "=", "_helpers", ".", "_to_bytes", "(", "message", ",", "encoding", "=", "'utf-8'", ")", "return", "rsa", ".", "pkcs1", ".", "sign", "(", "message", ",", "self", ".", "_key", ",", "'SHA-256'", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
RsaSigner.from_string
Construct an RsaSigner instance from a string. Args: key: string, private key in PEM format. password: string, password for private key file. Unused for PEM files. Returns: RsaSigner instance. Raises: ValueError if the key cannot be parsed as PKCS#1 or PKCS#8 in PEM format.
oauth2client/_pure_python_crypt.py
def from_string(cls, key, password='notasecret'): """Construct an RsaSigner instance from a string. Args: key: string, private key in PEM format. password: string, password for private key file. Unused for PEM files. Returns: RsaSigner instance. Raises: ValueError if the key cannot be parsed as PKCS#1 or PKCS#8 in PEM format. """ key = _helpers._from_bytes(key) # pem expects str in Py3 marker_id, key_bytes = pem.readPemBlocksFromFile( six.StringIO(key), _PKCS1_MARKER, _PKCS8_MARKER) if marker_id == 0: pkey = rsa.key.PrivateKey.load_pkcs1(key_bytes, format='DER') elif marker_id == 1: key_info, remaining = decoder.decode( key_bytes, asn1Spec=_PKCS8_SPEC) if remaining != b'': raise ValueError('Unused bytes', remaining) pkey_info = key_info.getComponentByName('privateKey') pkey = rsa.key.PrivateKey.load_pkcs1(pkey_info.asOctets(), format='DER') else: raise ValueError('No key could be detected.') return cls(pkey)
def from_string(cls, key, password='notasecret'): """Construct an RsaSigner instance from a string. Args: key: string, private key in PEM format. password: string, password for private key file. Unused for PEM files. Returns: RsaSigner instance. Raises: ValueError if the key cannot be parsed as PKCS#1 or PKCS#8 in PEM format. """ key = _helpers._from_bytes(key) # pem expects str in Py3 marker_id, key_bytes = pem.readPemBlocksFromFile( six.StringIO(key), _PKCS1_MARKER, _PKCS8_MARKER) if marker_id == 0: pkey = rsa.key.PrivateKey.load_pkcs1(key_bytes, format='DER') elif marker_id == 1: key_info, remaining = decoder.decode( key_bytes, asn1Spec=_PKCS8_SPEC) if remaining != b'': raise ValueError('Unused bytes', remaining) pkey_info = key_info.getComponentByName('privateKey') pkey = rsa.key.PrivateKey.load_pkcs1(pkey_info.asOctets(), format='DER') else: raise ValueError('No key could be detected.') return cls(pkey)
[ "Construct", "an", "RsaSigner", "instance", "from", "a", "string", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/_pure_python_crypt.py#L151-L184
[ "def", "from_string", "(", "cls", ",", "key", ",", "password", "=", "'notasecret'", ")", ":", "key", "=", "_helpers", ".", "_from_bytes", "(", "key", ")", "# pem expects str in Py3", "marker_id", ",", "key_bytes", "=", "pem", ".", "readPemBlocksFromFile", "(", "six", ".", "StringIO", "(", "key", ")", ",", "_PKCS1_MARKER", ",", "_PKCS8_MARKER", ")", "if", "marker_id", "==", "0", ":", "pkey", "=", "rsa", ".", "key", ".", "PrivateKey", ".", "load_pkcs1", "(", "key_bytes", ",", "format", "=", "'DER'", ")", "elif", "marker_id", "==", "1", ":", "key_info", ",", "remaining", "=", "decoder", ".", "decode", "(", "key_bytes", ",", "asn1Spec", "=", "_PKCS8_SPEC", ")", "if", "remaining", "!=", "b''", ":", "raise", "ValueError", "(", "'Unused bytes'", ",", "remaining", ")", "pkey_info", "=", "key_info", ".", "getComponentByName", "(", "'privateKey'", ")", "pkey", "=", "rsa", ".", "key", ".", "PrivateKey", ".", "load_pkcs1", "(", "pkey_info", ".", "asOctets", "(", ")", ",", "format", "=", "'DER'", ")", "else", ":", "raise", "ValueError", "(", "'No key could be detected.'", ")", "return", "cls", "(", "pkey", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
_create_file_if_needed
Creates the an empty file if it does not already exist. Returns: True if the file was created, False otherwise.
oauth2client/contrib/multiprocess_file_storage.py
def _create_file_if_needed(filename): """Creates the an empty file if it does not already exist. Returns: True if the file was created, False otherwise. """ if os.path.exists(filename): return False else: # Equivalent to "touch". open(filename, 'a+b').close() logger.info('Credential file {0} created'.format(filename)) return True
def _create_file_if_needed(filename): """Creates the an empty file if it does not already exist. Returns: True if the file was created, False otherwise. """ if os.path.exists(filename): return False else: # Equivalent to "touch". open(filename, 'a+b').close() logger.info('Credential file {0} created'.format(filename)) return True
[ "Creates", "the", "an", "empty", "file", "if", "it", "does", "not", "already", "exist", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/multiprocess_file_storage.py#L100-L112
[ "def", "_create_file_if_needed", "(", "filename", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "return", "False", "else", ":", "# Equivalent to \"touch\".", "open", "(", "filename", ",", "'a+b'", ")", ".", "close", "(", ")", "logger", ".", "info", "(", "'Credential file {0} created'", ".", "format", "(", "filename", ")", ")", "return", "True" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
_load_credentials_file
Load credentials from the given file handle. The file is expected to be in this format: { "file_version": 2, "credentials": { "key": "base64 encoded json representation of credentials." } } This function will warn and return empty credentials instead of raising exceptions. Args: credentials_file: An open file handle. Returns: A dictionary mapping user-defined keys to an instance of :class:`oauth2client.client.Credentials`.
oauth2client/contrib/multiprocess_file_storage.py
def _load_credentials_file(credentials_file): """Load credentials from the given file handle. The file is expected to be in this format: { "file_version": 2, "credentials": { "key": "base64 encoded json representation of credentials." } } This function will warn and return empty credentials instead of raising exceptions. Args: credentials_file: An open file handle. Returns: A dictionary mapping user-defined keys to an instance of :class:`oauth2client.client.Credentials`. """ try: credentials_file.seek(0) data = json.load(credentials_file) except Exception: logger.warning( 'Credentials file could not be loaded, will ignore and ' 'overwrite.') return {} if data.get('file_version') != 2: logger.warning( 'Credentials file is not version 2, will ignore and ' 'overwrite.') return {} credentials = {} for key, encoded_credential in iteritems(data.get('credentials', {})): try: credential_json = base64.b64decode(encoded_credential) credential = client.Credentials.new_from_json(credential_json) credentials[key] = credential except: logger.warning( 'Invalid credential {0} in file, ignoring.'.format(key)) return credentials
def _load_credentials_file(credentials_file): """Load credentials from the given file handle. The file is expected to be in this format: { "file_version": 2, "credentials": { "key": "base64 encoded json representation of credentials." } } This function will warn and return empty credentials instead of raising exceptions. Args: credentials_file: An open file handle. Returns: A dictionary mapping user-defined keys to an instance of :class:`oauth2client.client.Credentials`. """ try: credentials_file.seek(0) data = json.load(credentials_file) except Exception: logger.warning( 'Credentials file could not be loaded, will ignore and ' 'overwrite.') return {} if data.get('file_version') != 2: logger.warning( 'Credentials file is not version 2, will ignore and ' 'overwrite.') return {} credentials = {} for key, encoded_credential in iteritems(data.get('credentials', {})): try: credential_json = base64.b64decode(encoded_credential) credential = client.Credentials.new_from_json(credential_json) credentials[key] = credential except: logger.warning( 'Invalid credential {0} in file, ignoring.'.format(key)) return credentials
[ "Load", "credentials", "from", "the", "given", "file", "handle", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/multiprocess_file_storage.py#L115-L163
[ "def", "_load_credentials_file", "(", "credentials_file", ")", ":", "try", ":", "credentials_file", ".", "seek", "(", "0", ")", "data", "=", "json", ".", "load", "(", "credentials_file", ")", "except", "Exception", ":", "logger", ".", "warning", "(", "'Credentials file could not be loaded, will ignore and '", "'overwrite.'", ")", "return", "{", "}", "if", "data", ".", "get", "(", "'file_version'", ")", "!=", "2", ":", "logger", ".", "warning", "(", "'Credentials file is not version 2, will ignore and '", "'overwrite.'", ")", "return", "{", "}", "credentials", "=", "{", "}", "for", "key", ",", "encoded_credential", "in", "iteritems", "(", "data", ".", "get", "(", "'credentials'", ",", "{", "}", ")", ")", ":", "try", ":", "credential_json", "=", "base64", ".", "b64decode", "(", "encoded_credential", ")", "credential", "=", "client", ".", "Credentials", ".", "new_from_json", "(", "credential_json", ")", "credentials", "[", "key", "]", "=", "credential", "except", ":", "logger", ".", "warning", "(", "'Invalid credential {0} in file, ignoring.'", ".", "format", "(", "key", ")", ")", "return", "credentials" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
_write_credentials_file
Writes credentials to a file. Refer to :func:`_load_credentials_file` for the format. Args: credentials_file: An open file handle, must be read/write. credentials: A dictionary mapping user-defined keys to an instance of :class:`oauth2client.client.Credentials`.
oauth2client/contrib/multiprocess_file_storage.py
def _write_credentials_file(credentials_file, credentials): """Writes credentials to a file. Refer to :func:`_load_credentials_file` for the format. Args: credentials_file: An open file handle, must be read/write. credentials: A dictionary mapping user-defined keys to an instance of :class:`oauth2client.client.Credentials`. """ data = {'file_version': 2, 'credentials': {}} for key, credential in iteritems(credentials): credential_json = credential.to_json() encoded_credential = _helpers._from_bytes(base64.b64encode( _helpers._to_bytes(credential_json))) data['credentials'][key] = encoded_credential credentials_file.seek(0) json.dump(data, credentials_file) credentials_file.truncate()
def _write_credentials_file(credentials_file, credentials): """Writes credentials to a file. Refer to :func:`_load_credentials_file` for the format. Args: credentials_file: An open file handle, must be read/write. credentials: A dictionary mapping user-defined keys to an instance of :class:`oauth2client.client.Credentials`. """ data = {'file_version': 2, 'credentials': {}} for key, credential in iteritems(credentials): credential_json = credential.to_json() encoded_credential = _helpers._from_bytes(base64.b64encode( _helpers._to_bytes(credential_json))) data['credentials'][key] = encoded_credential credentials_file.seek(0) json.dump(data, credentials_file) credentials_file.truncate()
[ "Writes", "credentials", "to", "a", "file", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/multiprocess_file_storage.py#L166-L186
[ "def", "_write_credentials_file", "(", "credentials_file", ",", "credentials", ")", ":", "data", "=", "{", "'file_version'", ":", "2", ",", "'credentials'", ":", "{", "}", "}", "for", "key", ",", "credential", "in", "iteritems", "(", "credentials", ")", ":", "credential_json", "=", "credential", ".", "to_json", "(", ")", "encoded_credential", "=", "_helpers", ".", "_from_bytes", "(", "base64", ".", "b64encode", "(", "_helpers", ".", "_to_bytes", "(", "credential_json", ")", ")", ")", "data", "[", "'credentials'", "]", "[", "key", "]", "=", "encoded_credential", "credentials_file", ".", "seek", "(", "0", ")", "json", ".", "dump", "(", "data", ",", "credentials_file", ")", "credentials_file", ".", "truncate", "(", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
_get_backend
A helper method to get or create a backend with thread locking. This ensures that only one backend is used per-file per-process, so that thread and process locks are appropriately shared. Args: filename: The full path to the credential storage file. Returns: An instance of :class:`_MultiprocessStorageBackend`.
oauth2client/contrib/multiprocess_file_storage.py
def _get_backend(filename): """A helper method to get or create a backend with thread locking. This ensures that only one backend is used per-file per-process, so that thread and process locks are appropriately shared. Args: filename: The full path to the credential storage file. Returns: An instance of :class:`_MultiprocessStorageBackend`. """ filename = os.path.abspath(filename) with _backends_lock: if filename not in _backends: _backends[filename] = _MultiprocessStorageBackend(filename) return _backends[filename]
def _get_backend(filename): """A helper method to get or create a backend with thread locking. This ensures that only one backend is used per-file per-process, so that thread and process locks are appropriately shared. Args: filename: The full path to the credential storage file. Returns: An instance of :class:`_MultiprocessStorageBackend`. """ filename = os.path.abspath(filename) with _backends_lock: if filename not in _backends: _backends[filename] = _MultiprocessStorageBackend(filename) return _backends[filename]
[ "A", "helper", "method", "to", "get", "or", "create", "a", "backend", "with", "thread", "locking", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/multiprocess_file_storage.py#L292-L309
[ "def", "_get_backend", "(", "filename", ")", ":", "filename", "=", "os", ".", "path", ".", "abspath", "(", "filename", ")", "with", "_backends_lock", ":", "if", "filename", "not", "in", "_backends", ":", "_backends", "[", "filename", "]", "=", "_MultiprocessStorageBackend", "(", "filename", ")", "return", "_backends", "[", "filename", "]" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
_MultiprocessStorageBackend._load_credentials
(Re-)loads the credentials from the file.
oauth2client/contrib/multiprocess_file_storage.py
def _load_credentials(self): """(Re-)loads the credentials from the file.""" if not self._file: return loaded_credentials = _load_credentials_file(self._file) self._credentials.update(loaded_credentials) logger.debug('Read credential file')
def _load_credentials(self): """(Re-)loads the credentials from the file.""" if not self._file: return loaded_credentials = _load_credentials_file(self._file) self._credentials.update(loaded_credentials) logger.debug('Read credential file')
[ "(", "Re", "-", ")", "loads", "the", "credentials", "from", "the", "file", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/multiprocess_file_storage.py#L206-L214
[ "def", "_load_credentials", "(", "self", ")", ":", "if", "not", "self", ".", "_file", ":", "return", "loaded_credentials", "=", "_load_credentials_file", "(", "self", ".", "_file", ")", "self", ".", "_credentials", ".", "update", "(", "loaded_credentials", ")", "logger", ".", "debug", "(", "'Read credential file'", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
MultiprocessFileStorage.locked_get
Retrieves the current credentials from the store. Returns: An instance of :class:`oauth2client.client.Credentials` or `None`.
oauth2client/contrib/multiprocess_file_storage.py
def locked_get(self): """Retrieves the current credentials from the store. Returns: An instance of :class:`oauth2client.client.Credentials` or `None`. """ credential = self._backend.locked_get(self._key) if credential is not None: credential.set_store(self) return credential
def locked_get(self): """Retrieves the current credentials from the store. Returns: An instance of :class:`oauth2client.client.Credentials` or `None`. """ credential = self._backend.locked_get(self._key) if credential is not None: credential.set_store(self) return credential
[ "Retrieves", "the", "current", "credentials", "from", "the", "store", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/multiprocess_file_storage.py#L331-L342
[ "def", "locked_get", "(", "self", ")", ":", "credential", "=", "self", ".", "_backend", ".", "locked_get", "(", "self", ".", "_key", ")", "if", "credential", "is", "not", "None", ":", "credential", ".", "set_store", "(", "self", ")", "return", "credential" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
positional
A decorator to declare that only the first N arguments my be positional. This decorator makes it easy to support Python 3 style keyword-only parameters. For example, in Python 3 it is possible to write:: def fn(pos1, *, kwonly1=None, kwonly1=None): ... All named parameters after ``*`` must be a keyword:: fn(10, 'kw1', 'kw2') # Raises exception. fn(10, kwonly1='kw1') # Ok. Example ^^^^^^^ To define a function like above, do:: @positional(1) def fn(pos1, kwonly1=None, kwonly2=None): ... If no default value is provided to a keyword argument, it becomes a required keyword argument:: @positional(0) def fn(required_kw): ... This must be called with the keyword parameter:: fn() # Raises exception. fn(10) # Raises exception. fn(required_kw=10) # Ok. When defining instance or class methods always remember to account for ``self`` and ``cls``:: class MyClass(object): @positional(2) def my_method(self, pos1, kwonly1=None): ... @classmethod @positional(2) def my_method(cls, pos1, kwonly1=None): ... The positional decorator behavior is controlled by ``_helpers.positional_parameters_enforcement``, which may be set to ``POSITIONAL_EXCEPTION``, ``POSITIONAL_WARNING`` or ``POSITIONAL_IGNORE`` to raise an exception, log a warning, or do nothing, respectively, if a declaration is violated. Args: max_positional_arguments: Maximum number of positional arguments. All parameters after the this index must be keyword only. Returns: A decorator that prevents using arguments after max_positional_args from being used as positional parameters. Raises: TypeError: if a key-word only argument is provided as a positional parameter, but only if _helpers.positional_parameters_enforcement is set to POSITIONAL_EXCEPTION.
oauth2client/_helpers.py
def positional(max_positional_args): """A decorator to declare that only the first N arguments my be positional. This decorator makes it easy to support Python 3 style keyword-only parameters. For example, in Python 3 it is possible to write:: def fn(pos1, *, kwonly1=None, kwonly1=None): ... All named parameters after ``*`` must be a keyword:: fn(10, 'kw1', 'kw2') # Raises exception. fn(10, kwonly1='kw1') # Ok. Example ^^^^^^^ To define a function like above, do:: @positional(1) def fn(pos1, kwonly1=None, kwonly2=None): ... If no default value is provided to a keyword argument, it becomes a required keyword argument:: @positional(0) def fn(required_kw): ... This must be called with the keyword parameter:: fn() # Raises exception. fn(10) # Raises exception. fn(required_kw=10) # Ok. When defining instance or class methods always remember to account for ``self`` and ``cls``:: class MyClass(object): @positional(2) def my_method(self, pos1, kwonly1=None): ... @classmethod @positional(2) def my_method(cls, pos1, kwonly1=None): ... The positional decorator behavior is controlled by ``_helpers.positional_parameters_enforcement``, which may be set to ``POSITIONAL_EXCEPTION``, ``POSITIONAL_WARNING`` or ``POSITIONAL_IGNORE`` to raise an exception, log a warning, or do nothing, respectively, if a declaration is violated. Args: max_positional_arguments: Maximum number of positional arguments. All parameters after the this index must be keyword only. Returns: A decorator that prevents using arguments after max_positional_args from being used as positional parameters. Raises: TypeError: if a key-word only argument is provided as a positional parameter, but only if _helpers.positional_parameters_enforcement is set to POSITIONAL_EXCEPTION. """ def positional_decorator(wrapped): @functools.wraps(wrapped) def positional_wrapper(*args, **kwargs): if len(args) > max_positional_args: plural_s = '' if max_positional_args != 1: plural_s = 's' message = ('{function}() takes at most {args_max} positional ' 'argument{plural} ({args_given} given)'.format( function=wrapped.__name__, args_max=max_positional_args, args_given=len(args), plural=plural_s)) if positional_parameters_enforcement == POSITIONAL_EXCEPTION: raise TypeError(message) elif positional_parameters_enforcement == POSITIONAL_WARNING: logger.warning(message) return wrapped(*args, **kwargs) return positional_wrapper if isinstance(max_positional_args, six.integer_types): return positional_decorator else: args, _, _, defaults = inspect.getargspec(max_positional_args) return positional(len(args) - len(defaults))(max_positional_args)
def positional(max_positional_args): """A decorator to declare that only the first N arguments my be positional. This decorator makes it easy to support Python 3 style keyword-only parameters. For example, in Python 3 it is possible to write:: def fn(pos1, *, kwonly1=None, kwonly1=None): ... All named parameters after ``*`` must be a keyword:: fn(10, 'kw1', 'kw2') # Raises exception. fn(10, kwonly1='kw1') # Ok. Example ^^^^^^^ To define a function like above, do:: @positional(1) def fn(pos1, kwonly1=None, kwonly2=None): ... If no default value is provided to a keyword argument, it becomes a required keyword argument:: @positional(0) def fn(required_kw): ... This must be called with the keyword parameter:: fn() # Raises exception. fn(10) # Raises exception. fn(required_kw=10) # Ok. When defining instance or class methods always remember to account for ``self`` and ``cls``:: class MyClass(object): @positional(2) def my_method(self, pos1, kwonly1=None): ... @classmethod @positional(2) def my_method(cls, pos1, kwonly1=None): ... The positional decorator behavior is controlled by ``_helpers.positional_parameters_enforcement``, which may be set to ``POSITIONAL_EXCEPTION``, ``POSITIONAL_WARNING`` or ``POSITIONAL_IGNORE`` to raise an exception, log a warning, or do nothing, respectively, if a declaration is violated. Args: max_positional_arguments: Maximum number of positional arguments. All parameters after the this index must be keyword only. Returns: A decorator that prevents using arguments after max_positional_args from being used as positional parameters. Raises: TypeError: if a key-word only argument is provided as a positional parameter, but only if _helpers.positional_parameters_enforcement is set to POSITIONAL_EXCEPTION. """ def positional_decorator(wrapped): @functools.wraps(wrapped) def positional_wrapper(*args, **kwargs): if len(args) > max_positional_args: plural_s = '' if max_positional_args != 1: plural_s = 's' message = ('{function}() takes at most {args_max} positional ' 'argument{plural} ({args_given} given)'.format( function=wrapped.__name__, args_max=max_positional_args, args_given=len(args), plural=plural_s)) if positional_parameters_enforcement == POSITIONAL_EXCEPTION: raise TypeError(message) elif positional_parameters_enforcement == POSITIONAL_WARNING: logger.warning(message) return wrapped(*args, **kwargs) return positional_wrapper if isinstance(max_positional_args, six.integer_types): return positional_decorator else: args, _, _, defaults = inspect.getargspec(max_positional_args) return positional(len(args) - len(defaults))(max_positional_args)
[ "A", "decorator", "to", "declare", "that", "only", "the", "first", "N", "arguments", "my", "be", "positional", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/_helpers.py#L44-L140
[ "def", "positional", "(", "max_positional_args", ")", ":", "def", "positional_decorator", "(", "wrapped", ")", ":", "@", "functools", ".", "wraps", "(", "wrapped", ")", "def", "positional_wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "args", ")", ">", "max_positional_args", ":", "plural_s", "=", "''", "if", "max_positional_args", "!=", "1", ":", "plural_s", "=", "'s'", "message", "=", "(", "'{function}() takes at most {args_max} positional '", "'argument{plural} ({args_given} given)'", ".", "format", "(", "function", "=", "wrapped", ".", "__name__", ",", "args_max", "=", "max_positional_args", ",", "args_given", "=", "len", "(", "args", ")", ",", "plural", "=", "plural_s", ")", ")", "if", "positional_parameters_enforcement", "==", "POSITIONAL_EXCEPTION", ":", "raise", "TypeError", "(", "message", ")", "elif", "positional_parameters_enforcement", "==", "POSITIONAL_WARNING", ":", "logger", ".", "warning", "(", "message", ")", "return", "wrapped", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "positional_wrapper", "if", "isinstance", "(", "max_positional_args", ",", "six", ".", "integer_types", ")", ":", "return", "positional_decorator", "else", ":", "args", ",", "_", ",", "_", ",", "defaults", "=", "inspect", ".", "getargspec", "(", "max_positional_args", ")", "return", "positional", "(", "len", "(", "args", ")", "-", "len", "(", "defaults", ")", ")", "(", "max_positional_args", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
string_to_scopes
Converts stringifed scope value to a list. If scopes is a list then it is simply passed through. If scopes is an string then a list of each individual scope is returned. Args: scopes: a string or iterable of strings, the scopes. Returns: The scopes in a list.
oauth2client/_helpers.py
def string_to_scopes(scopes): """Converts stringifed scope value to a list. If scopes is a list then it is simply passed through. If scopes is an string then a list of each individual scope is returned. Args: scopes: a string or iterable of strings, the scopes. Returns: The scopes in a list. """ if not scopes: return [] elif isinstance(scopes, six.string_types): return scopes.split(' ') else: return scopes
def string_to_scopes(scopes): """Converts stringifed scope value to a list. If scopes is a list then it is simply passed through. If scopes is an string then a list of each individual scope is returned. Args: scopes: a string or iterable of strings, the scopes. Returns: The scopes in a list. """ if not scopes: return [] elif isinstance(scopes, six.string_types): return scopes.split(' ') else: return scopes
[ "Converts", "stringifed", "scope", "value", "to", "a", "list", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/_helpers.py#L162-L179
[ "def", "string_to_scopes", "(", "scopes", ")", ":", "if", "not", "scopes", ":", "return", "[", "]", "elif", "isinstance", "(", "scopes", ",", "six", ".", "string_types", ")", ":", "return", "scopes", ".", "split", "(", "' '", ")", "else", ":", "return", "scopes" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
parse_unique_urlencoded
Parses unique key-value parameters from urlencoded content. Args: content: string, URL-encoded key-value pairs. Returns: dict, The key-value pairs from ``content``. Raises: ValueError: if one of the keys is repeated.
oauth2client/_helpers.py
def parse_unique_urlencoded(content): """Parses unique key-value parameters from urlencoded content. Args: content: string, URL-encoded key-value pairs. Returns: dict, The key-value pairs from ``content``. Raises: ValueError: if one of the keys is repeated. """ urlencoded_params = urllib.parse.parse_qs(content) params = {} for key, value in six.iteritems(urlencoded_params): if len(value) != 1: msg = ('URL-encoded content contains a repeated value:' '%s -> %s' % (key, ', '.join(value))) raise ValueError(msg) params[key] = value[0] return params
def parse_unique_urlencoded(content): """Parses unique key-value parameters from urlencoded content. Args: content: string, URL-encoded key-value pairs. Returns: dict, The key-value pairs from ``content``. Raises: ValueError: if one of the keys is repeated. """ urlencoded_params = urllib.parse.parse_qs(content) params = {} for key, value in six.iteritems(urlencoded_params): if len(value) != 1: msg = ('URL-encoded content contains a repeated value:' '%s -> %s' % (key, ', '.join(value))) raise ValueError(msg) params[key] = value[0] return params
[ "Parses", "unique", "key", "-", "value", "parameters", "from", "urlencoded", "content", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/_helpers.py#L182-L202
[ "def", "parse_unique_urlencoded", "(", "content", ")", ":", "urlencoded_params", "=", "urllib", ".", "parse", ".", "parse_qs", "(", "content", ")", "params", "=", "{", "}", "for", "key", ",", "value", "in", "six", ".", "iteritems", "(", "urlencoded_params", ")", ":", "if", "len", "(", "value", ")", "!=", "1", ":", "msg", "=", "(", "'URL-encoded content contains a repeated value:'", "'%s -> %s'", "%", "(", "key", ",", "', '", ".", "join", "(", "value", ")", ")", ")", "raise", "ValueError", "(", "msg", ")", "params", "[", "key", "]", "=", "value", "[", "0", "]", "return", "params" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
update_query_params
Updates a URI with new query parameters. If a given key from ``params`` is repeated in the ``uri``, then the URI will be considered invalid and an error will occur. If the URI is valid, then each value from ``params`` will replace the corresponding value in the query parameters (if it exists). Args: uri: string, A valid URI, with potential existing query parameters. params: dict, A dictionary of query parameters. Returns: The same URI but with the new query parameters added.
oauth2client/_helpers.py
def update_query_params(uri, params): """Updates a URI with new query parameters. If a given key from ``params`` is repeated in the ``uri``, then the URI will be considered invalid and an error will occur. If the URI is valid, then each value from ``params`` will replace the corresponding value in the query parameters (if it exists). Args: uri: string, A valid URI, with potential existing query parameters. params: dict, A dictionary of query parameters. Returns: The same URI but with the new query parameters added. """ parts = urllib.parse.urlparse(uri) query_params = parse_unique_urlencoded(parts.query) query_params.update(params) new_query = urllib.parse.urlencode(query_params) new_parts = parts._replace(query=new_query) return urllib.parse.urlunparse(new_parts)
def update_query_params(uri, params): """Updates a URI with new query parameters. If a given key from ``params`` is repeated in the ``uri``, then the URI will be considered invalid and an error will occur. If the URI is valid, then each value from ``params`` will replace the corresponding value in the query parameters (if it exists). Args: uri: string, A valid URI, with potential existing query parameters. params: dict, A dictionary of query parameters. Returns: The same URI but with the new query parameters added. """ parts = urllib.parse.urlparse(uri) query_params = parse_unique_urlencoded(parts.query) query_params.update(params) new_query = urllib.parse.urlencode(query_params) new_parts = parts._replace(query=new_query) return urllib.parse.urlunparse(new_parts)
[ "Updates", "a", "URI", "with", "new", "query", "parameters", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/_helpers.py#L205-L227
[ "def", "update_query_params", "(", "uri", ",", "params", ")", ":", "parts", "=", "urllib", ".", "parse", ".", "urlparse", "(", "uri", ")", "query_params", "=", "parse_unique_urlencoded", "(", "parts", ".", "query", ")", "query_params", ".", "update", "(", "params", ")", "new_query", "=", "urllib", ".", "parse", ".", "urlencode", "(", "query_params", ")", "new_parts", "=", "parts", ".", "_replace", "(", "query", "=", "new_query", ")", "return", "urllib", ".", "parse", ".", "urlunparse", "(", "new_parts", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
_add_query_parameter
Adds a query parameter to a url. Replaces the current value if it already exists in the URL. Args: url: string, url to add the query parameter to. name: string, query parameter name. value: string, query parameter value. Returns: Updated query parameter. Does not update the url if value is None.
oauth2client/_helpers.py
def _add_query_parameter(url, name, value): """Adds a query parameter to a url. Replaces the current value if it already exists in the URL. Args: url: string, url to add the query parameter to. name: string, query parameter name. value: string, query parameter value. Returns: Updated query parameter. Does not update the url if value is None. """ if value is None: return url else: return update_query_params(url, {name: value})
def _add_query_parameter(url, name, value): """Adds a query parameter to a url. Replaces the current value if it already exists in the URL. Args: url: string, url to add the query parameter to. name: string, query parameter name. value: string, query parameter value. Returns: Updated query parameter. Does not update the url if value is None. """ if value is None: return url else: return update_query_params(url, {name: value})
[ "Adds", "a", "query", "parameter", "to", "a", "url", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/_helpers.py#L230-L246
[ "def", "_add_query_parameter", "(", "url", ",", "name", ",", "value", ")", ":", "if", "value", "is", "None", ":", "return", "url", "else", ":", "return", "update_query_params", "(", "url", ",", "{", "name", ":", "value", "}", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
_apply_user_agent
Adds a user-agent to the headers. Args: headers: dict, request headers to add / modify user agent within. user_agent: str, the user agent to add. Returns: dict, the original headers passed in, but modified if the user agent is not None.
oauth2client/transport.py
def _apply_user_agent(headers, user_agent): """Adds a user-agent to the headers. Args: headers: dict, request headers to add / modify user agent within. user_agent: str, the user agent to add. Returns: dict, the original headers passed in, but modified if the user agent is not None. """ if user_agent is not None: if 'user-agent' in headers: headers['user-agent'] = (user_agent + ' ' + headers['user-agent']) else: headers['user-agent'] = user_agent return headers
def _apply_user_agent(headers, user_agent): """Adds a user-agent to the headers. Args: headers: dict, request headers to add / modify user agent within. user_agent: str, the user agent to add. Returns: dict, the original headers passed in, but modified if the user agent is not None. """ if user_agent is not None: if 'user-agent' in headers: headers['user-agent'] = (user_agent + ' ' + headers['user-agent']) else: headers['user-agent'] = user_agent return headers
[ "Adds", "a", "user", "-", "agent", "to", "the", "headers", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/transport.py#L89-L107
[ "def", "_apply_user_agent", "(", "headers", ",", "user_agent", ")", ":", "if", "user_agent", "is", "not", "None", ":", "if", "'user-agent'", "in", "headers", ":", "headers", "[", "'user-agent'", "]", "=", "(", "user_agent", "+", "' '", "+", "headers", "[", "'user-agent'", "]", ")", "else", ":", "headers", "[", "'user-agent'", "]", "=", "user_agent", "return", "headers" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
clean_headers
Forces header keys and values to be strings, i.e not unicode. The httplib module just concats the header keys and values in a way that may make the message header a unicode string, which, if it then tries to contatenate to a binary request body may result in a unicode decode error. Args: headers: dict, A dictionary of headers. Returns: The same dictionary but with all the keys converted to strings.
oauth2client/transport.py
def clean_headers(headers): """Forces header keys and values to be strings, i.e not unicode. The httplib module just concats the header keys and values in a way that may make the message header a unicode string, which, if it then tries to contatenate to a binary request body may result in a unicode decode error. Args: headers: dict, A dictionary of headers. Returns: The same dictionary but with all the keys converted to strings. """ clean = {} try: for k, v in six.iteritems(headers): if not isinstance(k, six.binary_type): k = str(k) if not isinstance(v, six.binary_type): v = str(v) clean[_helpers._to_bytes(k)] = _helpers._to_bytes(v) except UnicodeEncodeError: from oauth2client.client import NonAsciiHeaderError raise NonAsciiHeaderError(k, ': ', v) return clean
def clean_headers(headers): """Forces header keys and values to be strings, i.e not unicode. The httplib module just concats the header keys and values in a way that may make the message header a unicode string, which, if it then tries to contatenate to a binary request body may result in a unicode decode error. Args: headers: dict, A dictionary of headers. Returns: The same dictionary but with all the keys converted to strings. """ clean = {} try: for k, v in six.iteritems(headers): if not isinstance(k, six.binary_type): k = str(k) if not isinstance(v, six.binary_type): v = str(v) clean[_helpers._to_bytes(k)] = _helpers._to_bytes(v) except UnicodeEncodeError: from oauth2client.client import NonAsciiHeaderError raise NonAsciiHeaderError(k, ': ', v) return clean
[ "Forces", "header", "keys", "and", "values", "to", "be", "strings", "i", ".", "e", "not", "unicode", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/transport.py#L110-L134
[ "def", "clean_headers", "(", "headers", ")", ":", "clean", "=", "{", "}", "try", ":", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "headers", ")", ":", "if", "not", "isinstance", "(", "k", ",", "six", ".", "binary_type", ")", ":", "k", "=", "str", "(", "k", ")", "if", "not", "isinstance", "(", "v", ",", "six", ".", "binary_type", ")", ":", "v", "=", "str", "(", "v", ")", "clean", "[", "_helpers", ".", "_to_bytes", "(", "k", ")", "]", "=", "_helpers", ".", "_to_bytes", "(", "v", ")", "except", "UnicodeEncodeError", ":", "from", "oauth2client", ".", "client", "import", "NonAsciiHeaderError", "raise", "NonAsciiHeaderError", "(", "k", ",", "': '", ",", "v", ")", "return", "clean" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
wrap_http_for_auth
Prepares an HTTP object's request method for auth. Wraps HTTP requests with logic to catch auth failures (typically identified via a 401 status code). In the event of failure, tries to refresh the token used and then retry the original request. Args: credentials: Credentials, the credentials used to identify the authenticated user. http: httplib2.Http, an http object to be used to make auth requests.
oauth2client/transport.py
def wrap_http_for_auth(credentials, http): """Prepares an HTTP object's request method for auth. Wraps HTTP requests with logic to catch auth failures (typically identified via a 401 status code). In the event of failure, tries to refresh the token used and then retry the original request. Args: credentials: Credentials, the credentials used to identify the authenticated user. http: httplib2.Http, an http object to be used to make auth requests. """ orig_request_method = http.request # The closure that will replace 'httplib2.Http.request'. def new_request(uri, method='GET', body=None, headers=None, redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None): if not credentials.access_token: _LOGGER.info('Attempting refresh to obtain ' 'initial access_token') credentials._refresh(orig_request_method) # Clone and modify the request headers to add the appropriate # Authorization header. headers = _initialize_headers(headers) credentials.apply(headers) _apply_user_agent(headers, credentials.user_agent) body_stream_position = None # Check if the body is a file-like stream. if all(getattr(body, stream_prop, None) for stream_prop in _STREAM_PROPERTIES): body_stream_position = body.tell() resp, content = request(orig_request_method, uri, method, body, clean_headers(headers), redirections, connection_type) # A stored token may expire between the time it is retrieved and # the time the request is made, so we may need to try twice. max_refresh_attempts = 2 for refresh_attempt in range(max_refresh_attempts): if resp.status not in REFRESH_STATUS_CODES: break _LOGGER.info('Refreshing due to a %s (attempt %s/%s)', resp.status, refresh_attempt + 1, max_refresh_attempts) credentials._refresh(orig_request_method) credentials.apply(headers) if body_stream_position is not None: body.seek(body_stream_position) resp, content = request(orig_request_method, uri, method, body, clean_headers(headers), redirections, connection_type) return resp, content # Replace the request method with our own closure. http.request = new_request # Set credentials as a property of the request method. http.request.credentials = credentials
def wrap_http_for_auth(credentials, http): """Prepares an HTTP object's request method for auth. Wraps HTTP requests with logic to catch auth failures (typically identified via a 401 status code). In the event of failure, tries to refresh the token used and then retry the original request. Args: credentials: Credentials, the credentials used to identify the authenticated user. http: httplib2.Http, an http object to be used to make auth requests. """ orig_request_method = http.request # The closure that will replace 'httplib2.Http.request'. def new_request(uri, method='GET', body=None, headers=None, redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None): if not credentials.access_token: _LOGGER.info('Attempting refresh to obtain ' 'initial access_token') credentials._refresh(orig_request_method) # Clone and modify the request headers to add the appropriate # Authorization header. headers = _initialize_headers(headers) credentials.apply(headers) _apply_user_agent(headers, credentials.user_agent) body_stream_position = None # Check if the body is a file-like stream. if all(getattr(body, stream_prop, None) for stream_prop in _STREAM_PROPERTIES): body_stream_position = body.tell() resp, content = request(orig_request_method, uri, method, body, clean_headers(headers), redirections, connection_type) # A stored token may expire between the time it is retrieved and # the time the request is made, so we may need to try twice. max_refresh_attempts = 2 for refresh_attempt in range(max_refresh_attempts): if resp.status not in REFRESH_STATUS_CODES: break _LOGGER.info('Refreshing due to a %s (attempt %s/%s)', resp.status, refresh_attempt + 1, max_refresh_attempts) credentials._refresh(orig_request_method) credentials.apply(headers) if body_stream_position is not None: body.seek(body_stream_position) resp, content = request(orig_request_method, uri, method, body, clean_headers(headers), redirections, connection_type) return resp, content # Replace the request method with our own closure. http.request = new_request # Set credentials as a property of the request method. http.request.credentials = credentials
[ "Prepares", "an", "HTTP", "object", "s", "request", "method", "for", "auth", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/transport.py#L137-L201
[ "def", "wrap_http_for_auth", "(", "credentials", ",", "http", ")", ":", "orig_request_method", "=", "http", ".", "request", "# The closure that will replace 'httplib2.Http.request'.", "def", "new_request", "(", "uri", ",", "method", "=", "'GET'", ",", "body", "=", "None", ",", "headers", "=", "None", ",", "redirections", "=", "httplib2", ".", "DEFAULT_MAX_REDIRECTS", ",", "connection_type", "=", "None", ")", ":", "if", "not", "credentials", ".", "access_token", ":", "_LOGGER", ".", "info", "(", "'Attempting refresh to obtain '", "'initial access_token'", ")", "credentials", ".", "_refresh", "(", "orig_request_method", ")", "# Clone and modify the request headers to add the appropriate", "# Authorization header.", "headers", "=", "_initialize_headers", "(", "headers", ")", "credentials", ".", "apply", "(", "headers", ")", "_apply_user_agent", "(", "headers", ",", "credentials", ".", "user_agent", ")", "body_stream_position", "=", "None", "# Check if the body is a file-like stream.", "if", "all", "(", "getattr", "(", "body", ",", "stream_prop", ",", "None", ")", "for", "stream_prop", "in", "_STREAM_PROPERTIES", ")", ":", "body_stream_position", "=", "body", ".", "tell", "(", ")", "resp", ",", "content", "=", "request", "(", "orig_request_method", ",", "uri", ",", "method", ",", "body", ",", "clean_headers", "(", "headers", ")", ",", "redirections", ",", "connection_type", ")", "# A stored token may expire between the time it is retrieved and", "# the time the request is made, so we may need to try twice.", "max_refresh_attempts", "=", "2", "for", "refresh_attempt", "in", "range", "(", "max_refresh_attempts", ")", ":", "if", "resp", ".", "status", "not", "in", "REFRESH_STATUS_CODES", ":", "break", "_LOGGER", ".", "info", "(", "'Refreshing due to a %s (attempt %s/%s)'", ",", "resp", ".", "status", ",", "refresh_attempt", "+", "1", ",", "max_refresh_attempts", ")", "credentials", ".", "_refresh", "(", "orig_request_method", ")", "credentials", ".", "apply", "(", "headers", ")", "if", "body_stream_position", "is", "not", "None", ":", "body", ".", "seek", "(", "body_stream_position", ")", "resp", ",", "content", "=", "request", "(", "orig_request_method", ",", "uri", ",", "method", ",", "body", ",", "clean_headers", "(", "headers", ")", ",", "redirections", ",", "connection_type", ")", "return", "resp", ",", "content", "# Replace the request method with our own closure.", "http", ".", "request", "=", "new_request", "# Set credentials as a property of the request method.", "http", ".", "request", ".", "credentials", "=", "credentials" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
wrap_http_for_jwt_access
Prepares an HTTP object's request method for JWT access. Wraps HTTP requests with logic to catch auth failures (typically identified via a 401 status code). In the event of failure, tries to refresh the token used and then retry the original request. Args: credentials: _JWTAccessCredentials, the credentials used to identify a service account that uses JWT access tokens. http: httplib2.Http, an http object to be used to make auth requests.
oauth2client/transport.py
def wrap_http_for_jwt_access(credentials, http): """Prepares an HTTP object's request method for JWT access. Wraps HTTP requests with logic to catch auth failures (typically identified via a 401 status code). In the event of failure, tries to refresh the token used and then retry the original request. Args: credentials: _JWTAccessCredentials, the credentials used to identify a service account that uses JWT access tokens. http: httplib2.Http, an http object to be used to make auth requests. """ orig_request_method = http.request wrap_http_for_auth(credentials, http) # The new value of ``http.request`` set by ``wrap_http_for_auth``. authenticated_request_method = http.request # The closure that will replace 'httplib2.Http.request'. def new_request(uri, method='GET', body=None, headers=None, redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None): if 'aud' in credentials._kwargs: # Preemptively refresh token, this is not done for OAuth2 if (credentials.access_token is None or credentials.access_token_expired): credentials.refresh(None) return request(authenticated_request_method, uri, method, body, headers, redirections, connection_type) else: # If we don't have an 'aud' (audience) claim, # create a 1-time token with the uri root as the audience headers = _initialize_headers(headers) _apply_user_agent(headers, credentials.user_agent) uri_root = uri.split('?', 1)[0] token, unused_expiry = credentials._create_token({'aud': uri_root}) headers['Authorization'] = 'Bearer ' + token return request(orig_request_method, uri, method, body, clean_headers(headers), redirections, connection_type) # Replace the request method with our own closure. http.request = new_request # Set credentials as a property of the request method. http.request.credentials = credentials
def wrap_http_for_jwt_access(credentials, http): """Prepares an HTTP object's request method for JWT access. Wraps HTTP requests with logic to catch auth failures (typically identified via a 401 status code). In the event of failure, tries to refresh the token used and then retry the original request. Args: credentials: _JWTAccessCredentials, the credentials used to identify a service account that uses JWT access tokens. http: httplib2.Http, an http object to be used to make auth requests. """ orig_request_method = http.request wrap_http_for_auth(credentials, http) # The new value of ``http.request`` set by ``wrap_http_for_auth``. authenticated_request_method = http.request # The closure that will replace 'httplib2.Http.request'. def new_request(uri, method='GET', body=None, headers=None, redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None): if 'aud' in credentials._kwargs: # Preemptively refresh token, this is not done for OAuth2 if (credentials.access_token is None or credentials.access_token_expired): credentials.refresh(None) return request(authenticated_request_method, uri, method, body, headers, redirections, connection_type) else: # If we don't have an 'aud' (audience) claim, # create a 1-time token with the uri root as the audience headers = _initialize_headers(headers) _apply_user_agent(headers, credentials.user_agent) uri_root = uri.split('?', 1)[0] token, unused_expiry = credentials._create_token({'aud': uri_root}) headers['Authorization'] = 'Bearer ' + token return request(orig_request_method, uri, method, body, clean_headers(headers), redirections, connection_type) # Replace the request method with our own closure. http.request = new_request # Set credentials as a property of the request method. http.request.credentials = credentials
[ "Prepares", "an", "HTTP", "object", "s", "request", "method", "for", "JWT", "access", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/transport.py#L204-L251
[ "def", "wrap_http_for_jwt_access", "(", "credentials", ",", "http", ")", ":", "orig_request_method", "=", "http", ".", "request", "wrap_http_for_auth", "(", "credentials", ",", "http", ")", "# The new value of ``http.request`` set by ``wrap_http_for_auth``.", "authenticated_request_method", "=", "http", ".", "request", "# The closure that will replace 'httplib2.Http.request'.", "def", "new_request", "(", "uri", ",", "method", "=", "'GET'", ",", "body", "=", "None", ",", "headers", "=", "None", ",", "redirections", "=", "httplib2", ".", "DEFAULT_MAX_REDIRECTS", ",", "connection_type", "=", "None", ")", ":", "if", "'aud'", "in", "credentials", ".", "_kwargs", ":", "# Preemptively refresh token, this is not done for OAuth2", "if", "(", "credentials", ".", "access_token", "is", "None", "or", "credentials", ".", "access_token_expired", ")", ":", "credentials", ".", "refresh", "(", "None", ")", "return", "request", "(", "authenticated_request_method", ",", "uri", ",", "method", ",", "body", ",", "headers", ",", "redirections", ",", "connection_type", ")", "else", ":", "# If we don't have an 'aud' (audience) claim,", "# create a 1-time token with the uri root as the audience", "headers", "=", "_initialize_headers", "(", "headers", ")", "_apply_user_agent", "(", "headers", ",", "credentials", ".", "user_agent", ")", "uri_root", "=", "uri", ".", "split", "(", "'?'", ",", "1", ")", "[", "0", "]", "token", ",", "unused_expiry", "=", "credentials", ".", "_create_token", "(", "{", "'aud'", ":", "uri_root", "}", ")", "headers", "[", "'Authorization'", "]", "=", "'Bearer '", "+", "token", "return", "request", "(", "orig_request_method", ",", "uri", ",", "method", ",", "body", ",", "clean_headers", "(", "headers", ")", ",", "redirections", ",", "connection_type", ")", "# Replace the request method with our own closure.", "http", ".", "request", "=", "new_request", "# Set credentials as a property of the request method.", "http", ".", "request", ".", "credentials", "=", "credentials" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
request
Make an HTTP request with an HTTP object and arguments. Args: http: httplib2.Http, an http object to be used to make requests. uri: string, The URI to be requested. method: string, The HTTP method to use for the request. Defaults to 'GET'. body: string, The payload / body in HTTP request. By default there is no payload. headers: dict, Key-value pairs of request headers. By default there are no headers. redirections: int, The number of allowed 203 redirects for the request. Defaults to 5. connection_type: httplib.HTTPConnection, a subclass to be used for establishing connection. If not set, the type will be determined from the ``uri``. Returns: tuple, a pair of a httplib2.Response with the status code and other headers and the bytes of the content returned.
oauth2client/transport.py
def request(http, uri, method='GET', body=None, headers=None, redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None): """Make an HTTP request with an HTTP object and arguments. Args: http: httplib2.Http, an http object to be used to make requests. uri: string, The URI to be requested. method: string, The HTTP method to use for the request. Defaults to 'GET'. body: string, The payload / body in HTTP request. By default there is no payload. headers: dict, Key-value pairs of request headers. By default there are no headers. redirections: int, The number of allowed 203 redirects for the request. Defaults to 5. connection_type: httplib.HTTPConnection, a subclass to be used for establishing connection. If not set, the type will be determined from the ``uri``. Returns: tuple, a pair of a httplib2.Response with the status code and other headers and the bytes of the content returned. """ # NOTE: Allowing http or http.request is temporary (See Issue 601). http_callable = getattr(http, 'request', http) return http_callable(uri, method=method, body=body, headers=headers, redirections=redirections, connection_type=connection_type)
def request(http, uri, method='GET', body=None, headers=None, redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None): """Make an HTTP request with an HTTP object and arguments. Args: http: httplib2.Http, an http object to be used to make requests. uri: string, The URI to be requested. method: string, The HTTP method to use for the request. Defaults to 'GET'. body: string, The payload / body in HTTP request. By default there is no payload. headers: dict, Key-value pairs of request headers. By default there are no headers. redirections: int, The number of allowed 203 redirects for the request. Defaults to 5. connection_type: httplib.HTTPConnection, a subclass to be used for establishing connection. If not set, the type will be determined from the ``uri``. Returns: tuple, a pair of a httplib2.Response with the status code and other headers and the bytes of the content returned. """ # NOTE: Allowing http or http.request is temporary (See Issue 601). http_callable = getattr(http, 'request', http) return http_callable(uri, method=method, body=body, headers=headers, redirections=redirections, connection_type=connection_type)
[ "Make", "an", "HTTP", "request", "with", "an", "HTTP", "object", "and", "arguments", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/transport.py#L254-L282
[ "def", "request", "(", "http", ",", "uri", ",", "method", "=", "'GET'", ",", "body", "=", "None", ",", "headers", "=", "None", ",", "redirections", "=", "httplib2", ".", "DEFAULT_MAX_REDIRECTS", ",", "connection_type", "=", "None", ")", ":", "# NOTE: Allowing http or http.request is temporary (See Issue 601).", "http_callable", "=", "getattr", "(", "http", ",", "'request'", ",", "http", ")", "return", "http_callable", "(", "uri", ",", "method", "=", "method", ",", "body", "=", "body", ",", "headers", "=", "headers", ",", "redirections", "=", "redirections", ",", "connection_type", "=", "connection_type", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
_get_flow_for_token
Retrieves the flow instance associated with a given CSRF token from the Flask session.
oauth2client/contrib/flask_util.py
def _get_flow_for_token(csrf_token): """Retrieves the flow instance associated with a given CSRF token from the Flask session.""" flow_pickle = session.pop( _FLOW_KEY.format(csrf_token), None) if flow_pickle is None: return None else: return pickle.loads(flow_pickle)
def _get_flow_for_token(csrf_token): """Retrieves the flow instance associated with a given CSRF token from the Flask session.""" flow_pickle = session.pop( _FLOW_KEY.format(csrf_token), None) if flow_pickle is None: return None else: return pickle.loads(flow_pickle)
[ "Retrieves", "the", "flow", "instance", "associated", "with", "a", "given", "CSRF", "token", "from", "the", "Flask", "session", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/flask_util.py#L197-L206
[ "def", "_get_flow_for_token", "(", "csrf_token", ")", ":", "flow_pickle", "=", "session", ".", "pop", "(", "_FLOW_KEY", ".", "format", "(", "csrf_token", ")", ",", "None", ")", "if", "flow_pickle", "is", "None", ":", "return", "None", "else", ":", "return", "pickle", ".", "loads", "(", "flow_pickle", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
UserOAuth2.init_app
Initialize this extension for the given app. Arguments: app: A Flask application. scopes: Optional list of scopes to authorize. client_secrets_file: Path to a file containing client secrets. You can also specify the GOOGLE_OAUTH2_CLIENT_SECRETS_FILE config value. client_id: If not specifying a client secrets file, specify the OAuth2 client id. You can also specify the GOOGLE_OAUTH2_CLIENT_ID config value. You must also provide a client secret. client_secret: The OAuth2 client secret. You can also specify the GOOGLE_OAUTH2_CLIENT_SECRET config value. authorize_callback: A function that is executed after successful user authorization. storage: A oauth2client.client.Storage subclass for storing the credentials. By default, this is a Flask session based storage. kwargs: Any additional args are passed along to the Flow constructor.
oauth2client/contrib/flask_util.py
def init_app(self, app, scopes=None, client_secrets_file=None, client_id=None, client_secret=None, authorize_callback=None, storage=None, **kwargs): """Initialize this extension for the given app. Arguments: app: A Flask application. scopes: Optional list of scopes to authorize. client_secrets_file: Path to a file containing client secrets. You can also specify the GOOGLE_OAUTH2_CLIENT_SECRETS_FILE config value. client_id: If not specifying a client secrets file, specify the OAuth2 client id. You can also specify the GOOGLE_OAUTH2_CLIENT_ID config value. You must also provide a client secret. client_secret: The OAuth2 client secret. You can also specify the GOOGLE_OAUTH2_CLIENT_SECRET config value. authorize_callback: A function that is executed after successful user authorization. storage: A oauth2client.client.Storage subclass for storing the credentials. By default, this is a Flask session based storage. kwargs: Any additional args are passed along to the Flow constructor. """ self.app = app self.authorize_callback = authorize_callback self.flow_kwargs = kwargs if storage is None: storage = dictionary_storage.DictionaryStorage( session, key=_CREDENTIALS_KEY) self.storage = storage if scopes is None: scopes = app.config.get('GOOGLE_OAUTH2_SCOPES', _DEFAULT_SCOPES) self.scopes = scopes self._load_config(client_secrets_file, client_id, client_secret) app.register_blueprint(self._create_blueprint())
def init_app(self, app, scopes=None, client_secrets_file=None, client_id=None, client_secret=None, authorize_callback=None, storage=None, **kwargs): """Initialize this extension for the given app. Arguments: app: A Flask application. scopes: Optional list of scopes to authorize. client_secrets_file: Path to a file containing client secrets. You can also specify the GOOGLE_OAUTH2_CLIENT_SECRETS_FILE config value. client_id: If not specifying a client secrets file, specify the OAuth2 client id. You can also specify the GOOGLE_OAUTH2_CLIENT_ID config value. You must also provide a client secret. client_secret: The OAuth2 client secret. You can also specify the GOOGLE_OAUTH2_CLIENT_SECRET config value. authorize_callback: A function that is executed after successful user authorization. storage: A oauth2client.client.Storage subclass for storing the credentials. By default, this is a Flask session based storage. kwargs: Any additional args are passed along to the Flow constructor. """ self.app = app self.authorize_callback = authorize_callback self.flow_kwargs = kwargs if storage is None: storage = dictionary_storage.DictionaryStorage( session, key=_CREDENTIALS_KEY) self.storage = storage if scopes is None: scopes = app.config.get('GOOGLE_OAUTH2_SCOPES', _DEFAULT_SCOPES) self.scopes = scopes self._load_config(client_secrets_file, client_id, client_secret) app.register_blueprint(self._create_blueprint())
[ "Initialize", "this", "extension", "for", "the", "given", "app", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/flask_util.py#L235-L274
[ "def", "init_app", "(", "self", ",", "app", ",", "scopes", "=", "None", ",", "client_secrets_file", "=", "None", ",", "client_id", "=", "None", ",", "client_secret", "=", "None", ",", "authorize_callback", "=", "None", ",", "storage", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "app", "=", "app", "self", ".", "authorize_callback", "=", "authorize_callback", "self", ".", "flow_kwargs", "=", "kwargs", "if", "storage", "is", "None", ":", "storage", "=", "dictionary_storage", ".", "DictionaryStorage", "(", "session", ",", "key", "=", "_CREDENTIALS_KEY", ")", "self", ".", "storage", "=", "storage", "if", "scopes", "is", "None", ":", "scopes", "=", "app", ".", "config", ".", "get", "(", "'GOOGLE_OAUTH2_SCOPES'", ",", "_DEFAULT_SCOPES", ")", "self", ".", "scopes", "=", "scopes", "self", ".", "_load_config", "(", "client_secrets_file", ",", "client_id", ",", "client_secret", ")", "app", ".", "register_blueprint", "(", "self", ".", "_create_blueprint", "(", ")", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
UserOAuth2._load_config
Loads oauth2 configuration in order of priority. Priority: 1. Config passed to the constructor or init_app. 2. Config passed via the GOOGLE_OAUTH2_CLIENT_SECRETS_FILE app config. 3. Config passed via the GOOGLE_OAUTH2_CLIENT_ID and GOOGLE_OAUTH2_CLIENT_SECRET app config. Raises: ValueError if no config could be found.
oauth2client/contrib/flask_util.py
def _load_config(self, client_secrets_file, client_id, client_secret): """Loads oauth2 configuration in order of priority. Priority: 1. Config passed to the constructor or init_app. 2. Config passed via the GOOGLE_OAUTH2_CLIENT_SECRETS_FILE app config. 3. Config passed via the GOOGLE_OAUTH2_CLIENT_ID and GOOGLE_OAUTH2_CLIENT_SECRET app config. Raises: ValueError if no config could be found. """ if client_id and client_secret: self.client_id, self.client_secret = client_id, client_secret return if client_secrets_file: self._load_client_secrets(client_secrets_file) return if 'GOOGLE_OAUTH2_CLIENT_SECRETS_FILE' in self.app.config: self._load_client_secrets( self.app.config['GOOGLE_OAUTH2_CLIENT_SECRETS_FILE']) return try: self.client_id, self.client_secret = ( self.app.config['GOOGLE_OAUTH2_CLIENT_ID'], self.app.config['GOOGLE_OAUTH2_CLIENT_SECRET']) except KeyError: raise ValueError( 'OAuth2 configuration could not be found. Either specify the ' 'client_secrets_file or client_id and client_secret or set ' 'the app configuration variables ' 'GOOGLE_OAUTH2_CLIENT_SECRETS_FILE or ' 'GOOGLE_OAUTH2_CLIENT_ID and GOOGLE_OAUTH2_CLIENT_SECRET.')
def _load_config(self, client_secrets_file, client_id, client_secret): """Loads oauth2 configuration in order of priority. Priority: 1. Config passed to the constructor or init_app. 2. Config passed via the GOOGLE_OAUTH2_CLIENT_SECRETS_FILE app config. 3. Config passed via the GOOGLE_OAUTH2_CLIENT_ID and GOOGLE_OAUTH2_CLIENT_SECRET app config. Raises: ValueError if no config could be found. """ if client_id and client_secret: self.client_id, self.client_secret = client_id, client_secret return if client_secrets_file: self._load_client_secrets(client_secrets_file) return if 'GOOGLE_OAUTH2_CLIENT_SECRETS_FILE' in self.app.config: self._load_client_secrets( self.app.config['GOOGLE_OAUTH2_CLIENT_SECRETS_FILE']) return try: self.client_id, self.client_secret = ( self.app.config['GOOGLE_OAUTH2_CLIENT_ID'], self.app.config['GOOGLE_OAUTH2_CLIENT_SECRET']) except KeyError: raise ValueError( 'OAuth2 configuration could not be found. Either specify the ' 'client_secrets_file or client_id and client_secret or set ' 'the app configuration variables ' 'GOOGLE_OAUTH2_CLIENT_SECRETS_FILE or ' 'GOOGLE_OAUTH2_CLIENT_ID and GOOGLE_OAUTH2_CLIENT_SECRET.')
[ "Loads", "oauth2", "configuration", "in", "order", "of", "priority", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/flask_util.py#L276-L312
[ "def", "_load_config", "(", "self", ",", "client_secrets_file", ",", "client_id", ",", "client_secret", ")", ":", "if", "client_id", "and", "client_secret", ":", "self", ".", "client_id", ",", "self", ".", "client_secret", "=", "client_id", ",", "client_secret", "return", "if", "client_secrets_file", ":", "self", ".", "_load_client_secrets", "(", "client_secrets_file", ")", "return", "if", "'GOOGLE_OAUTH2_CLIENT_SECRETS_FILE'", "in", "self", ".", "app", ".", "config", ":", "self", ".", "_load_client_secrets", "(", "self", ".", "app", ".", "config", "[", "'GOOGLE_OAUTH2_CLIENT_SECRETS_FILE'", "]", ")", "return", "try", ":", "self", ".", "client_id", ",", "self", ".", "client_secret", "=", "(", "self", ".", "app", ".", "config", "[", "'GOOGLE_OAUTH2_CLIENT_ID'", "]", ",", "self", ".", "app", ".", "config", "[", "'GOOGLE_OAUTH2_CLIENT_SECRET'", "]", ")", "except", "KeyError", ":", "raise", "ValueError", "(", "'OAuth2 configuration could not be found. Either specify the '", "'client_secrets_file or client_id and client_secret or set '", "'the app configuration variables '", "'GOOGLE_OAUTH2_CLIENT_SECRETS_FILE or '", "'GOOGLE_OAUTH2_CLIENT_ID and GOOGLE_OAUTH2_CLIENT_SECRET.'", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
UserOAuth2._load_client_secrets
Loads client secrets from the given filename.
oauth2client/contrib/flask_util.py
def _load_client_secrets(self, filename): """Loads client secrets from the given filename.""" client_type, client_info = clientsecrets.loadfile(filename) if client_type != clientsecrets.TYPE_WEB: raise ValueError( 'The flow specified in {0} is not supported.'.format( client_type)) self.client_id = client_info['client_id'] self.client_secret = client_info['client_secret']
def _load_client_secrets(self, filename): """Loads client secrets from the given filename.""" client_type, client_info = clientsecrets.loadfile(filename) if client_type != clientsecrets.TYPE_WEB: raise ValueError( 'The flow specified in {0} is not supported.'.format( client_type)) self.client_id = client_info['client_id'] self.client_secret = client_info['client_secret']
[ "Loads", "client", "secrets", "from", "the", "given", "filename", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/flask_util.py#L314-L323
[ "def", "_load_client_secrets", "(", "self", ",", "filename", ")", ":", "client_type", ",", "client_info", "=", "clientsecrets", ".", "loadfile", "(", "filename", ")", "if", "client_type", "!=", "clientsecrets", ".", "TYPE_WEB", ":", "raise", "ValueError", "(", "'The flow specified in {0} is not supported.'", ".", "format", "(", "client_type", ")", ")", "self", ".", "client_id", "=", "client_info", "[", "'client_id'", "]", "self", ".", "client_secret", "=", "client_info", "[", "'client_secret'", "]" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
UserOAuth2._make_flow
Creates a Web Server Flow
oauth2client/contrib/flask_util.py
def _make_flow(self, return_url=None, **kwargs): """Creates a Web Server Flow""" # Generate a CSRF token to prevent malicious requests. csrf_token = hashlib.sha256(os.urandom(1024)).hexdigest() session[_CSRF_KEY] = csrf_token state = json.dumps({ 'csrf_token': csrf_token, 'return_url': return_url }) kw = self.flow_kwargs.copy() kw.update(kwargs) extra_scopes = kw.pop('scopes', []) scopes = set(self.scopes).union(set(extra_scopes)) flow = client.OAuth2WebServerFlow( client_id=self.client_id, client_secret=self.client_secret, scope=scopes, state=state, redirect_uri=url_for('oauth2.callback', _external=True), **kw) flow_key = _FLOW_KEY.format(csrf_token) session[flow_key] = pickle.dumps(flow) return flow
def _make_flow(self, return_url=None, **kwargs): """Creates a Web Server Flow""" # Generate a CSRF token to prevent malicious requests. csrf_token = hashlib.sha256(os.urandom(1024)).hexdigest() session[_CSRF_KEY] = csrf_token state = json.dumps({ 'csrf_token': csrf_token, 'return_url': return_url }) kw = self.flow_kwargs.copy() kw.update(kwargs) extra_scopes = kw.pop('scopes', []) scopes = set(self.scopes).union(set(extra_scopes)) flow = client.OAuth2WebServerFlow( client_id=self.client_id, client_secret=self.client_secret, scope=scopes, state=state, redirect_uri=url_for('oauth2.callback', _external=True), **kw) flow_key = _FLOW_KEY.format(csrf_token) session[flow_key] = pickle.dumps(flow) return flow
[ "Creates", "a", "Web", "Server", "Flow" ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/flask_util.py#L325-L354
[ "def", "_make_flow", "(", "self", ",", "return_url", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Generate a CSRF token to prevent malicious requests.", "csrf_token", "=", "hashlib", ".", "sha256", "(", "os", ".", "urandom", "(", "1024", ")", ")", ".", "hexdigest", "(", ")", "session", "[", "_CSRF_KEY", "]", "=", "csrf_token", "state", "=", "json", ".", "dumps", "(", "{", "'csrf_token'", ":", "csrf_token", ",", "'return_url'", ":", "return_url", "}", ")", "kw", "=", "self", ".", "flow_kwargs", ".", "copy", "(", ")", "kw", ".", "update", "(", "kwargs", ")", "extra_scopes", "=", "kw", ".", "pop", "(", "'scopes'", ",", "[", "]", ")", "scopes", "=", "set", "(", "self", ".", "scopes", ")", ".", "union", "(", "set", "(", "extra_scopes", ")", ")", "flow", "=", "client", ".", "OAuth2WebServerFlow", "(", "client_id", "=", "self", ".", "client_id", ",", "client_secret", "=", "self", ".", "client_secret", ",", "scope", "=", "scopes", ",", "state", "=", "state", ",", "redirect_uri", "=", "url_for", "(", "'oauth2.callback'", ",", "_external", "=", "True", ")", ",", "*", "*", "kw", ")", "flow_key", "=", "_FLOW_KEY", ".", "format", "(", "csrf_token", ")", "session", "[", "flow_key", "]", "=", "pickle", ".", "dumps", "(", "flow", ")", "return", "flow" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
UserOAuth2.authorize_view
Flask view that starts the authorization flow. Starts flow by redirecting the user to the OAuth2 provider.
oauth2client/contrib/flask_util.py
def authorize_view(self): """Flask view that starts the authorization flow. Starts flow by redirecting the user to the OAuth2 provider. """ args = request.args.to_dict() # Scopes will be passed as mutliple args, and to_dict() will only # return one. So, we use getlist() to get all of the scopes. args['scopes'] = request.args.getlist('scopes') return_url = args.pop('return_url', None) if return_url is None: return_url = request.referrer or '/' flow = self._make_flow(return_url=return_url, **args) auth_url = flow.step1_get_authorize_url() return redirect(auth_url)
def authorize_view(self): """Flask view that starts the authorization flow. Starts flow by redirecting the user to the OAuth2 provider. """ args = request.args.to_dict() # Scopes will be passed as mutliple args, and to_dict() will only # return one. So, we use getlist() to get all of the scopes. args['scopes'] = request.args.getlist('scopes') return_url = args.pop('return_url', None) if return_url is None: return_url = request.referrer or '/' flow = self._make_flow(return_url=return_url, **args) auth_url = flow.step1_get_authorize_url() return redirect(auth_url)
[ "Flask", "view", "that", "starts", "the", "authorization", "flow", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/flask_util.py#L363-L381
[ "def", "authorize_view", "(", "self", ")", ":", "args", "=", "request", ".", "args", ".", "to_dict", "(", ")", "# Scopes will be passed as mutliple args, and to_dict() will only", "# return one. So, we use getlist() to get all of the scopes.", "args", "[", "'scopes'", "]", "=", "request", ".", "args", ".", "getlist", "(", "'scopes'", ")", "return_url", "=", "args", ".", "pop", "(", "'return_url'", ",", "None", ")", "if", "return_url", "is", "None", ":", "return_url", "=", "request", ".", "referrer", "or", "'/'", "flow", "=", "self", ".", "_make_flow", "(", "return_url", "=", "return_url", ",", "*", "*", "args", ")", "auth_url", "=", "flow", ".", "step1_get_authorize_url", "(", ")", "return", "redirect", "(", "auth_url", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
UserOAuth2.callback_view
Flask view that handles the user's return from OAuth2 provider. On return, exchanges the authorization code for credentials and stores the credentials.
oauth2client/contrib/flask_util.py
def callback_view(self): """Flask view that handles the user's return from OAuth2 provider. On return, exchanges the authorization code for credentials and stores the credentials. """ if 'error' in request.args: reason = request.args.get( 'error_description', request.args.get('error', '')) reason = markupsafe.escape(reason) return ('Authorization failed: {0}'.format(reason), httplib.BAD_REQUEST) try: encoded_state = request.args['state'] server_csrf = session[_CSRF_KEY] code = request.args['code'] except KeyError: return 'Invalid request', httplib.BAD_REQUEST try: state = json.loads(encoded_state) client_csrf = state['csrf_token'] return_url = state['return_url'] except (ValueError, KeyError): return 'Invalid request state', httplib.BAD_REQUEST if client_csrf != server_csrf: return 'Invalid request state', httplib.BAD_REQUEST flow = _get_flow_for_token(server_csrf) if flow is None: return 'Invalid request state', httplib.BAD_REQUEST # Exchange the auth code for credentials. try: credentials = flow.step2_exchange(code) except client.FlowExchangeError as exchange_error: current_app.logger.exception(exchange_error) content = 'An error occurred: {0}'.format(exchange_error) return content, httplib.BAD_REQUEST # Save the credentials to the storage. self.storage.put(credentials) if self.authorize_callback: self.authorize_callback(credentials) return redirect(return_url)
def callback_view(self): """Flask view that handles the user's return from OAuth2 provider. On return, exchanges the authorization code for credentials and stores the credentials. """ if 'error' in request.args: reason = request.args.get( 'error_description', request.args.get('error', '')) reason = markupsafe.escape(reason) return ('Authorization failed: {0}'.format(reason), httplib.BAD_REQUEST) try: encoded_state = request.args['state'] server_csrf = session[_CSRF_KEY] code = request.args['code'] except KeyError: return 'Invalid request', httplib.BAD_REQUEST try: state = json.loads(encoded_state) client_csrf = state['csrf_token'] return_url = state['return_url'] except (ValueError, KeyError): return 'Invalid request state', httplib.BAD_REQUEST if client_csrf != server_csrf: return 'Invalid request state', httplib.BAD_REQUEST flow = _get_flow_for_token(server_csrf) if flow is None: return 'Invalid request state', httplib.BAD_REQUEST # Exchange the auth code for credentials. try: credentials = flow.step2_exchange(code) except client.FlowExchangeError as exchange_error: current_app.logger.exception(exchange_error) content = 'An error occurred: {0}'.format(exchange_error) return content, httplib.BAD_REQUEST # Save the credentials to the storage. self.storage.put(credentials) if self.authorize_callback: self.authorize_callback(credentials) return redirect(return_url)
[ "Flask", "view", "that", "handles", "the", "user", "s", "return", "from", "OAuth2", "provider", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/flask_util.py#L383-L432
[ "def", "callback_view", "(", "self", ")", ":", "if", "'error'", "in", "request", ".", "args", ":", "reason", "=", "request", ".", "args", ".", "get", "(", "'error_description'", ",", "request", ".", "args", ".", "get", "(", "'error'", ",", "''", ")", ")", "reason", "=", "markupsafe", ".", "escape", "(", "reason", ")", "return", "(", "'Authorization failed: {0}'", ".", "format", "(", "reason", ")", ",", "httplib", ".", "BAD_REQUEST", ")", "try", ":", "encoded_state", "=", "request", ".", "args", "[", "'state'", "]", "server_csrf", "=", "session", "[", "_CSRF_KEY", "]", "code", "=", "request", ".", "args", "[", "'code'", "]", "except", "KeyError", ":", "return", "'Invalid request'", ",", "httplib", ".", "BAD_REQUEST", "try", ":", "state", "=", "json", ".", "loads", "(", "encoded_state", ")", "client_csrf", "=", "state", "[", "'csrf_token'", "]", "return_url", "=", "state", "[", "'return_url'", "]", "except", "(", "ValueError", ",", "KeyError", ")", ":", "return", "'Invalid request state'", ",", "httplib", ".", "BAD_REQUEST", "if", "client_csrf", "!=", "server_csrf", ":", "return", "'Invalid request state'", ",", "httplib", ".", "BAD_REQUEST", "flow", "=", "_get_flow_for_token", "(", "server_csrf", ")", "if", "flow", "is", "None", ":", "return", "'Invalid request state'", ",", "httplib", ".", "BAD_REQUEST", "# Exchange the auth code for credentials.", "try", ":", "credentials", "=", "flow", ".", "step2_exchange", "(", "code", ")", "except", "client", ".", "FlowExchangeError", "as", "exchange_error", ":", "current_app", ".", "logger", ".", "exception", "(", "exchange_error", ")", "content", "=", "'An error occurred: {0}'", ".", "format", "(", "exchange_error", ")", "return", "content", ",", "httplib", ".", "BAD_REQUEST", "# Save the credentials to the storage.", "self", ".", "storage", ".", "put", "(", "credentials", ")", "if", "self", ".", "authorize_callback", ":", "self", ".", "authorize_callback", "(", "credentials", ")", "return", "redirect", "(", "return_url", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
UserOAuth2.credentials
The credentials for the current user or None if unavailable.
oauth2client/contrib/flask_util.py
def credentials(self): """The credentials for the current user or None if unavailable.""" ctx = _app_ctx_stack.top if not hasattr(ctx, _CREDENTIALS_KEY): ctx.google_oauth2_credentials = self.storage.get() return ctx.google_oauth2_credentials
def credentials(self): """The credentials for the current user or None if unavailable.""" ctx = _app_ctx_stack.top if not hasattr(ctx, _CREDENTIALS_KEY): ctx.google_oauth2_credentials = self.storage.get() return ctx.google_oauth2_credentials
[ "The", "credentials", "for", "the", "current", "user", "or", "None", "if", "unavailable", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/flask_util.py#L435-L442
[ "def", "credentials", "(", "self", ")", ":", "ctx", "=", "_app_ctx_stack", ".", "top", "if", "not", "hasattr", "(", "ctx", ",", "_CREDENTIALS_KEY", ")", ":", "ctx", ".", "google_oauth2_credentials", "=", "self", ".", "storage", ".", "get", "(", ")", "return", "ctx", ".", "google_oauth2_credentials" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
UserOAuth2.has_credentials
Returns True if there are valid credentials for the current user.
oauth2client/contrib/flask_util.py
def has_credentials(self): """Returns True if there are valid credentials for the current user.""" if not self.credentials: return False # Is the access token expired? If so, do we have an refresh token? elif (self.credentials.access_token_expired and not self.credentials.refresh_token): return False else: return True
def has_credentials(self): """Returns True if there are valid credentials for the current user.""" if not self.credentials: return False # Is the access token expired? If so, do we have an refresh token? elif (self.credentials.access_token_expired and not self.credentials.refresh_token): return False else: return True
[ "Returns", "True", "if", "there", "are", "valid", "credentials", "for", "the", "current", "user", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/flask_util.py#L444-L453
[ "def", "has_credentials", "(", "self", ")", ":", "if", "not", "self", ".", "credentials", ":", "return", "False", "# Is the access token expired? If so, do we have an refresh token?", "elif", "(", "self", ".", "credentials", ".", "access_token_expired", "and", "not", "self", ".", "credentials", ".", "refresh_token", ")", ":", "return", "False", "else", ":", "return", "True" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
UserOAuth2.email
Returns the user's email address or None if there are no credentials. The email address is provided by the current credentials' id_token. This should not be used as unique identifier as the user can change their email. If you need a unique identifier, use user_id.
oauth2client/contrib/flask_util.py
def email(self): """Returns the user's email address or None if there are no credentials. The email address is provided by the current credentials' id_token. This should not be used as unique identifier as the user can change their email. If you need a unique identifier, use user_id. """ if not self.credentials: return None try: return self.credentials.id_token['email'] except KeyError: current_app.logger.error( 'Invalid id_token {0}'.format(self.credentials.id_token))
def email(self): """Returns the user's email address or None if there are no credentials. The email address is provided by the current credentials' id_token. This should not be used as unique identifier as the user can change their email. If you need a unique identifier, use user_id. """ if not self.credentials: return None try: return self.credentials.id_token['email'] except KeyError: current_app.logger.error( 'Invalid id_token {0}'.format(self.credentials.id_token))
[ "Returns", "the", "user", "s", "email", "address", "or", "None", "if", "there", "are", "no", "credentials", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/flask_util.py#L456-L469
[ "def", "email", "(", "self", ")", ":", "if", "not", "self", ".", "credentials", ":", "return", "None", "try", ":", "return", "self", ".", "credentials", ".", "id_token", "[", "'email'", "]", "except", "KeyError", ":", "current_app", ".", "logger", ".", "error", "(", "'Invalid id_token {0}'", ".", "format", "(", "self", ".", "credentials", ".", "id_token", ")", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
UserOAuth2.required
Decorator to require OAuth2 credentials for a view. If credentials are not available for the current user, then they will be redirected to the authorization flow. Once complete, the user will be redirected back to the original page.
oauth2client/contrib/flask_util.py
def required(self, decorated_function=None, scopes=None, **decorator_kwargs): """Decorator to require OAuth2 credentials for a view. If credentials are not available for the current user, then they will be redirected to the authorization flow. Once complete, the user will be redirected back to the original page. """ def curry_wrapper(wrapped_function): @wraps(wrapped_function) def required_wrapper(*args, **kwargs): return_url = decorator_kwargs.pop('return_url', request.url) requested_scopes = set(self.scopes) if scopes is not None: requested_scopes |= set(scopes) if self.has_credentials(): requested_scopes |= self.credentials.scopes requested_scopes = list(requested_scopes) # Does the user have credentials and does the credentials have # all of the needed scopes? if (self.has_credentials() and self.credentials.has_scopes(requested_scopes)): return wrapped_function(*args, **kwargs) # Otherwise, redirect to authorization else: auth_url = self.authorize_url( return_url, scopes=requested_scopes, **decorator_kwargs) return redirect(auth_url) return required_wrapper if decorated_function: return curry_wrapper(decorated_function) else: return curry_wrapper
def required(self, decorated_function=None, scopes=None, **decorator_kwargs): """Decorator to require OAuth2 credentials for a view. If credentials are not available for the current user, then they will be redirected to the authorization flow. Once complete, the user will be redirected back to the original page. """ def curry_wrapper(wrapped_function): @wraps(wrapped_function) def required_wrapper(*args, **kwargs): return_url = decorator_kwargs.pop('return_url', request.url) requested_scopes = set(self.scopes) if scopes is not None: requested_scopes |= set(scopes) if self.has_credentials(): requested_scopes |= self.credentials.scopes requested_scopes = list(requested_scopes) # Does the user have credentials and does the credentials have # all of the needed scopes? if (self.has_credentials() and self.credentials.has_scopes(requested_scopes)): return wrapped_function(*args, **kwargs) # Otherwise, redirect to authorization else: auth_url = self.authorize_url( return_url, scopes=requested_scopes, **decorator_kwargs) return redirect(auth_url) return required_wrapper if decorated_function: return curry_wrapper(decorated_function) else: return curry_wrapper
[ "Decorator", "to", "require", "OAuth2", "credentials", "for", "a", "view", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/flask_util.py#L498-L539
[ "def", "required", "(", "self", ",", "decorated_function", "=", "None", ",", "scopes", "=", "None", ",", "*", "*", "decorator_kwargs", ")", ":", "def", "curry_wrapper", "(", "wrapped_function", ")", ":", "@", "wraps", "(", "wrapped_function", ")", "def", "required_wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return_url", "=", "decorator_kwargs", ".", "pop", "(", "'return_url'", ",", "request", ".", "url", ")", "requested_scopes", "=", "set", "(", "self", ".", "scopes", ")", "if", "scopes", "is", "not", "None", ":", "requested_scopes", "|=", "set", "(", "scopes", ")", "if", "self", ".", "has_credentials", "(", ")", ":", "requested_scopes", "|=", "self", ".", "credentials", ".", "scopes", "requested_scopes", "=", "list", "(", "requested_scopes", ")", "# Does the user have credentials and does the credentials have", "# all of the needed scopes?", "if", "(", "self", ".", "has_credentials", "(", ")", "and", "self", ".", "credentials", ".", "has_scopes", "(", "requested_scopes", ")", ")", ":", "return", "wrapped_function", "(", "*", "args", ",", "*", "*", "kwargs", ")", "# Otherwise, redirect to authorization", "else", ":", "auth_url", "=", "self", ".", "authorize_url", "(", "return_url", ",", "scopes", "=", "requested_scopes", ",", "*", "*", "decorator_kwargs", ")", "return", "redirect", "(", "auth_url", ")", "return", "required_wrapper", "if", "decorated_function", ":", "return", "curry_wrapper", "(", "decorated_function", ")", "else", ":", "return", "curry_wrapper" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
get
Fetch a resource from the metadata server. Args: http: an object to be used to make HTTP requests. path: A string indicating the resource to retrieve. For example, 'instance/service-accounts/default' root: A string indicating the full path to the metadata server root. recursive: A boolean indicating whether to do a recursive query of metadata. See https://cloud.google.com/compute/docs/metadata#aggcontents Returns: A dictionary if the metadata server returns JSON, otherwise a string. Raises: http_client.HTTPException if an error corrured while retrieving metadata.
oauth2client/contrib/_metadata.py
def get(http, path, root=METADATA_ROOT, recursive=None): """Fetch a resource from the metadata server. Args: http: an object to be used to make HTTP requests. path: A string indicating the resource to retrieve. For example, 'instance/service-accounts/default' root: A string indicating the full path to the metadata server root. recursive: A boolean indicating whether to do a recursive query of metadata. See https://cloud.google.com/compute/docs/metadata#aggcontents Returns: A dictionary if the metadata server returns JSON, otherwise a string. Raises: http_client.HTTPException if an error corrured while retrieving metadata. """ url = urlparse.urljoin(root, path) url = _helpers._add_query_parameter(url, 'recursive', recursive) response, content = transport.request( http, url, headers=METADATA_HEADERS) if response.status == http_client.OK: decoded = _helpers._from_bytes(content) if response['content-type'] == 'application/json': return json.loads(decoded) else: return decoded else: raise http_client.HTTPException( 'Failed to retrieve {0} from the Google Compute Engine' 'metadata service. Response:\n{1}'.format(url, response))
def get(http, path, root=METADATA_ROOT, recursive=None): """Fetch a resource from the metadata server. Args: http: an object to be used to make HTTP requests. path: A string indicating the resource to retrieve. For example, 'instance/service-accounts/default' root: A string indicating the full path to the metadata server root. recursive: A boolean indicating whether to do a recursive query of metadata. See https://cloud.google.com/compute/docs/metadata#aggcontents Returns: A dictionary if the metadata server returns JSON, otherwise a string. Raises: http_client.HTTPException if an error corrured while retrieving metadata. """ url = urlparse.urljoin(root, path) url = _helpers._add_query_parameter(url, 'recursive', recursive) response, content = transport.request( http, url, headers=METADATA_HEADERS) if response.status == http_client.OK: decoded = _helpers._from_bytes(content) if response['content-type'] == 'application/json': return json.loads(decoded) else: return decoded else: raise http_client.HTTPException( 'Failed to retrieve {0} from the Google Compute Engine' 'metadata service. Response:\n{1}'.format(url, response))
[ "Fetch", "a", "resource", "from", "the", "metadata", "server", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/_metadata.py#L37-L71
[ "def", "get", "(", "http", ",", "path", ",", "root", "=", "METADATA_ROOT", ",", "recursive", "=", "None", ")", ":", "url", "=", "urlparse", ".", "urljoin", "(", "root", ",", "path", ")", "url", "=", "_helpers", ".", "_add_query_parameter", "(", "url", ",", "'recursive'", ",", "recursive", ")", "response", ",", "content", "=", "transport", ".", "request", "(", "http", ",", "url", ",", "headers", "=", "METADATA_HEADERS", ")", "if", "response", ".", "status", "==", "http_client", ".", "OK", ":", "decoded", "=", "_helpers", ".", "_from_bytes", "(", "content", ")", "if", "response", "[", "'content-type'", "]", "==", "'application/json'", ":", "return", "json", ".", "loads", "(", "decoded", ")", "else", ":", "return", "decoded", "else", ":", "raise", "http_client", ".", "HTTPException", "(", "'Failed to retrieve {0} from the Google Compute Engine'", "'metadata service. Response:\\n{1}'", ".", "format", "(", "url", ",", "response", ")", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
get_token
Fetch an oauth token for the Args: http: an object to be used to make HTTP requests. service_account: An email specifying the service account this token should represent. Default will be a token for the "default" service account of the current compute engine instance. Returns: A tuple of (access token, token expiration), where access token is the access token as a string and token expiration is a datetime object that indicates when the access token will expire.
oauth2client/contrib/_metadata.py
def get_token(http, service_account='default'): """Fetch an oauth token for the Args: http: an object to be used to make HTTP requests. service_account: An email specifying the service account this token should represent. Default will be a token for the "default" service account of the current compute engine instance. Returns: A tuple of (access token, token expiration), where access token is the access token as a string and token expiration is a datetime object that indicates when the access token will expire. """ token_json = get( http, 'instance/service-accounts/{0}/token'.format(service_account)) token_expiry = client._UTCNOW() + datetime.timedelta( seconds=token_json['expires_in']) return token_json['access_token'], token_expiry
def get_token(http, service_account='default'): """Fetch an oauth token for the Args: http: an object to be used to make HTTP requests. service_account: An email specifying the service account this token should represent. Default will be a token for the "default" service account of the current compute engine instance. Returns: A tuple of (access token, token expiration), where access token is the access token as a string and token expiration is a datetime object that indicates when the access token will expire. """ token_json = get( http, 'instance/service-accounts/{0}/token'.format(service_account)) token_expiry = client._UTCNOW() + datetime.timedelta( seconds=token_json['expires_in']) return token_json['access_token'], token_expiry
[ "Fetch", "an", "oauth", "token", "for", "the" ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/_metadata.py#L99-L118
[ "def", "get_token", "(", "http", ",", "service_account", "=", "'default'", ")", ":", "token_json", "=", "get", "(", "http", ",", "'instance/service-accounts/{0}/token'", ".", "format", "(", "service_account", ")", ")", "token_expiry", "=", "client", ".", "_UTCNOW", "(", ")", "+", "datetime", ".", "timedelta", "(", "seconds", "=", "token_json", "[", "'expires_in'", "]", ")", "return", "token_json", "[", "'access_token'", "]", ",", "token_expiry" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
xsrf_secret_key
Return the secret key for use for XSRF protection. If the Site entity does not have a secret key, this method will also create one and persist it. Returns: The secret key.
oauth2client/contrib/appengine.py
def xsrf_secret_key(): """Return the secret key for use for XSRF protection. If the Site entity does not have a secret key, this method will also create one and persist it. Returns: The secret key. """ secret = memcache.get(XSRF_MEMCACHE_ID, namespace=OAUTH2CLIENT_NAMESPACE) if not secret: # Load the one and only instance of SiteXsrfSecretKey. model = SiteXsrfSecretKey.get_or_insert(key_name='site') if not model.secret: model.secret = _generate_new_xsrf_secret_key() model.put() secret = model.secret memcache.add(XSRF_MEMCACHE_ID, secret, namespace=OAUTH2CLIENT_NAMESPACE) return str(secret)
def xsrf_secret_key(): """Return the secret key for use for XSRF protection. If the Site entity does not have a secret key, this method will also create one and persist it. Returns: The secret key. """ secret = memcache.get(XSRF_MEMCACHE_ID, namespace=OAUTH2CLIENT_NAMESPACE) if not secret: # Load the one and only instance of SiteXsrfSecretKey. model = SiteXsrfSecretKey.get_or_insert(key_name='site') if not model.secret: model.secret = _generate_new_xsrf_secret_key() model.put() secret = model.secret memcache.add(XSRF_MEMCACHE_ID, secret, namespace=OAUTH2CLIENT_NAMESPACE) return str(secret)
[ "Return", "the", "secret", "key", "for", "use", "for", "XSRF", "protection", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/appengine.py#L96-L116
[ "def", "xsrf_secret_key", "(", ")", ":", "secret", "=", "memcache", ".", "get", "(", "XSRF_MEMCACHE_ID", ",", "namespace", "=", "OAUTH2CLIENT_NAMESPACE", ")", "if", "not", "secret", ":", "# Load the one and only instance of SiteXsrfSecretKey.", "model", "=", "SiteXsrfSecretKey", ".", "get_or_insert", "(", "key_name", "=", "'site'", ")", "if", "not", "model", ".", "secret", ":", "model", ".", "secret", "=", "_generate_new_xsrf_secret_key", "(", ")", "model", ".", "put", "(", ")", "secret", "=", "model", ".", "secret", "memcache", ".", "add", "(", "XSRF_MEMCACHE_ID", ",", "secret", ",", "namespace", "=", "OAUTH2CLIENT_NAMESPACE", ")", "return", "str", "(", "secret", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
_build_state_value
Composes the value for the 'state' parameter. Packs the current request URI and an XSRF token into an opaque string that can be passed to the authentication server via the 'state' parameter. Args: request_handler: webapp.RequestHandler, The request. user: google.appengine.api.users.User, The current user. Returns: The state value as a string.
oauth2client/contrib/appengine.py
def _build_state_value(request_handler, user): """Composes the value for the 'state' parameter. Packs the current request URI and an XSRF token into an opaque string that can be passed to the authentication server via the 'state' parameter. Args: request_handler: webapp.RequestHandler, The request. user: google.appengine.api.users.User, The current user. Returns: The state value as a string. """ uri = request_handler.request.url token = xsrfutil.generate_token(xsrf_secret_key(), user.user_id(), action_id=str(uri)) return uri + ':' + token
def _build_state_value(request_handler, user): """Composes the value for the 'state' parameter. Packs the current request URI and an XSRF token into an opaque string that can be passed to the authentication server via the 'state' parameter. Args: request_handler: webapp.RequestHandler, The request. user: google.appengine.api.users.User, The current user. Returns: The state value as a string. """ uri = request_handler.request.url token = xsrfutil.generate_token(xsrf_secret_key(), user.user_id(), action_id=str(uri)) return uri + ':' + token
[ "Composes", "the", "value", "for", "the", "state", "parameter", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/appengine.py#L431-L447
[ "def", "_build_state_value", "(", "request_handler", ",", "user", ")", ":", "uri", "=", "request_handler", ".", "request", ".", "url", "token", "=", "xsrfutil", ".", "generate_token", "(", "xsrf_secret_key", "(", ")", ",", "user", ".", "user_id", "(", ")", ",", "action_id", "=", "str", "(", "uri", ")", ")", "return", "uri", "+", "':'", "+", "token" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
_parse_state_value
Parse the value of the 'state' parameter. Parses the value and validates the XSRF token in the state parameter. Args: state: string, The value of the state parameter. user: google.appengine.api.users.User, The current user. Returns: The redirect URI, or None if XSRF token is not valid.
oauth2client/contrib/appengine.py
def _parse_state_value(state, user): """Parse the value of the 'state' parameter. Parses the value and validates the XSRF token in the state parameter. Args: state: string, The value of the state parameter. user: google.appengine.api.users.User, The current user. Returns: The redirect URI, or None if XSRF token is not valid. """ uri, token = state.rsplit(':', 1) if xsrfutil.validate_token(xsrf_secret_key(), token, user.user_id(), action_id=uri): return uri else: return None
def _parse_state_value(state, user): """Parse the value of the 'state' parameter. Parses the value and validates the XSRF token in the state parameter. Args: state: string, The value of the state parameter. user: google.appengine.api.users.User, The current user. Returns: The redirect URI, or None if XSRF token is not valid. """ uri, token = state.rsplit(':', 1) if xsrfutil.validate_token(xsrf_secret_key(), token, user.user_id(), action_id=uri): return uri else: return None
[ "Parse", "the", "value", "of", "the", "state", "parameter", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/appengine.py#L450-L467
[ "def", "_parse_state_value", "(", "state", ",", "user", ")", ":", "uri", ",", "token", "=", "state", ".", "rsplit", "(", "':'", ",", "1", ")", "if", "xsrfutil", ".", "validate_token", "(", "xsrf_secret_key", "(", ")", ",", "token", ",", "user", ".", "user_id", "(", ")", ",", "action_id", "=", "uri", ")", ":", "return", "uri", "else", ":", "return", "None" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
oauth2decorator_from_clientsecrets
Creates an OAuth2Decorator populated from a clientsecrets file. Args: filename: string, File name of client secrets. scope: string or list of strings, scope(s) of the credentials being requested. message: string, A friendly string to display to the user if the clientsecrets file is missing or invalid. The message may contain HTML and will be presented on the web interface for any method that uses the decorator. cache: An optional cache service client that implements get() and set() methods. See clientsecrets.loadfile() for details. Returns: An OAuth2Decorator
oauth2client/contrib/appengine.py
def oauth2decorator_from_clientsecrets(filename, scope, message=None, cache=None): """Creates an OAuth2Decorator populated from a clientsecrets file. Args: filename: string, File name of client secrets. scope: string or list of strings, scope(s) of the credentials being requested. message: string, A friendly string to display to the user if the clientsecrets file is missing or invalid. The message may contain HTML and will be presented on the web interface for any method that uses the decorator. cache: An optional cache service client that implements get() and set() methods. See clientsecrets.loadfile() for details. Returns: An OAuth2Decorator """ return OAuth2DecoratorFromClientSecrets(filename, scope, message=message, cache=cache)
def oauth2decorator_from_clientsecrets(filename, scope, message=None, cache=None): """Creates an OAuth2Decorator populated from a clientsecrets file. Args: filename: string, File name of client secrets. scope: string or list of strings, scope(s) of the credentials being requested. message: string, A friendly string to display to the user if the clientsecrets file is missing or invalid. The message may contain HTML and will be presented on the web interface for any method that uses the decorator. cache: An optional cache service client that implements get() and set() methods. See clientsecrets.loadfile() for details. Returns: An OAuth2Decorator """ return OAuth2DecoratorFromClientSecrets(filename, scope, message=message, cache=cache)
[ "Creates", "an", "OAuth2Decorator", "populated", "from", "a", "clientsecrets", "file", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/appengine.py#L892-L910
[ "def", "oauth2decorator_from_clientsecrets", "(", "filename", ",", "scope", ",", "message", "=", "None", ",", "cache", "=", "None", ")", ":", "return", "OAuth2DecoratorFromClientSecrets", "(", "filename", ",", "scope", ",", "message", "=", "message", ",", "cache", "=", "cache", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
AppAssertionCredentials._refresh
Refreshes the access token. Since the underlying App Engine app_identity implementation does its own caching we can skip all the storage hoops and just to a refresh using the API. Args: http: unused HTTP object Raises: AccessTokenRefreshError: When the refresh fails.
oauth2client/contrib/appengine.py
def _refresh(self, http): """Refreshes the access token. Since the underlying App Engine app_identity implementation does its own caching we can skip all the storage hoops and just to a refresh using the API. Args: http: unused HTTP object Raises: AccessTokenRefreshError: When the refresh fails. """ try: scopes = self.scope.split() (token, _) = app_identity.get_access_token( scopes, service_account_id=self.service_account_id) except app_identity.Error as e: raise client.AccessTokenRefreshError(str(e)) self.access_token = token
def _refresh(self, http): """Refreshes the access token. Since the underlying App Engine app_identity implementation does its own caching we can skip all the storage hoops and just to a refresh using the API. Args: http: unused HTTP object Raises: AccessTokenRefreshError: When the refresh fails. """ try: scopes = self.scope.split() (token, _) = app_identity.get_access_token( scopes, service_account_id=self.service_account_id) except app_identity.Error as e: raise client.AccessTokenRefreshError(str(e)) self.access_token = token
[ "Refreshes", "the", "access", "token", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/appengine.py#L158-L177
[ "def", "_refresh", "(", "self", ",", "http", ")", ":", "try", ":", "scopes", "=", "self", ".", "scope", ".", "split", "(", ")", "(", "token", ",", "_", ")", "=", "app_identity", ".", "get_access_token", "(", "scopes", ",", "service_account_id", "=", "self", ".", "service_account_id", ")", "except", "app_identity", ".", "Error", "as", "e", ":", "raise", "client", ".", "AccessTokenRefreshError", "(", "str", "(", "e", ")", ")", "self", ".", "access_token", "=", "token" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
AppAssertionCredentials.service_account_email
Get the email for the current service account. Returns: string, The email associated with the Google App Engine service account.
oauth2client/contrib/appengine.py
def service_account_email(self): """Get the email for the current service account. Returns: string, The email associated with the Google App Engine service account. """ if self._service_account_email is None: self._service_account_email = ( app_identity.get_service_account_name()) return self._service_account_email
def service_account_email(self): """Get the email for the current service account. Returns: string, The email associated with the Google App Engine service account. """ if self._service_account_email is None: self._service_account_email = ( app_identity.get_service_account_name()) return self._service_account_email
[ "Get", "the", "email", "for", "the", "current", "service", "account", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/appengine.py#L206-L216
[ "def", "service_account_email", "(", "self", ")", ":", "if", "self", ".", "_service_account_email", "is", "None", ":", "self", ".", "_service_account_email", "=", "(", "app_identity", ".", "get_service_account_name", "(", ")", ")", "return", "self", ".", "_service_account_email" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
StorageByKeyName._is_ndb
Determine whether the model of the instance is an NDB model. Returns: Boolean indicating whether or not the model is an NDB or DB model.
oauth2client/contrib/appengine.py
def _is_ndb(self): """Determine whether the model of the instance is an NDB model. Returns: Boolean indicating whether or not the model is an NDB or DB model. """ # issubclass will fail if one of the arguments is not a class, only # need worry about new-style classes since ndb and db models are # new-style if isinstance(self._model, type): if _NDB_MODEL is not None and issubclass(self._model, _NDB_MODEL): return True elif issubclass(self._model, db.Model): return False raise TypeError( 'Model class not an NDB or DB model: {0}.'.format(self._model))
def _is_ndb(self): """Determine whether the model of the instance is an NDB model. Returns: Boolean indicating whether or not the model is an NDB or DB model. """ # issubclass will fail if one of the arguments is not a class, only # need worry about new-style classes since ndb and db models are # new-style if isinstance(self._model, type): if _NDB_MODEL is not None and issubclass(self._model, _NDB_MODEL): return True elif issubclass(self._model, db.Model): return False raise TypeError( 'Model class not an NDB or DB model: {0}.'.format(self._model))
[ "Determine", "whether", "the", "model", "of", "the", "instance", "is", "an", "NDB", "model", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/appengine.py#L333-L349
[ "def", "_is_ndb", "(", "self", ")", ":", "# issubclass will fail if one of the arguments is not a class, only", "# need worry about new-style classes since ndb and db models are", "# new-style", "if", "isinstance", "(", "self", ".", "_model", ",", "type", ")", ":", "if", "_NDB_MODEL", "is", "not", "None", "and", "issubclass", "(", "self", ".", "_model", ",", "_NDB_MODEL", ")", ":", "return", "True", "elif", "issubclass", "(", "self", ".", "_model", ",", "db", ".", "Model", ")", ":", "return", "False", "raise", "TypeError", "(", "'Model class not an NDB or DB model: {0}.'", ".", "format", "(", "self", ".", "_model", ")", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
StorageByKeyName._get_entity
Retrieve entity from datastore. Uses a different model method for db or ndb models. Returns: Instance of the model corresponding to the current storage object and stored using the key name of the storage object.
oauth2client/contrib/appengine.py
def _get_entity(self): """Retrieve entity from datastore. Uses a different model method for db or ndb models. Returns: Instance of the model corresponding to the current storage object and stored using the key name of the storage object. """ if self._is_ndb(): return self._model.get_by_id(self._key_name) else: return self._model.get_by_key_name(self._key_name)
def _get_entity(self): """Retrieve entity from datastore. Uses a different model method for db or ndb models. Returns: Instance of the model corresponding to the current storage object and stored using the key name of the storage object. """ if self._is_ndb(): return self._model.get_by_id(self._key_name) else: return self._model.get_by_key_name(self._key_name)
[ "Retrieve", "entity", "from", "datastore", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/appengine.py#L351-L363
[ "def", "_get_entity", "(", "self", ")", ":", "if", "self", ".", "_is_ndb", "(", ")", ":", "return", "self", ".", "_model", ".", "get_by_id", "(", "self", ".", "_key_name", ")", "else", ":", "return", "self", ".", "_model", ".", "get_by_key_name", "(", "self", ".", "_key_name", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
StorageByKeyName._delete_entity
Delete entity from datastore. Attempts to delete using the key_name stored on the object, whether or not the given key is in the datastore.
oauth2client/contrib/appengine.py
def _delete_entity(self): """Delete entity from datastore. Attempts to delete using the key_name stored on the object, whether or not the given key is in the datastore. """ if self._is_ndb(): _NDB_KEY(self._model, self._key_name).delete() else: entity_key = db.Key.from_path(self._model.kind(), self._key_name) db.delete(entity_key)
def _delete_entity(self): """Delete entity from datastore. Attempts to delete using the key_name stored on the object, whether or not the given key is in the datastore. """ if self._is_ndb(): _NDB_KEY(self._model, self._key_name).delete() else: entity_key = db.Key.from_path(self._model.kind(), self._key_name) db.delete(entity_key)
[ "Delete", "entity", "from", "datastore", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/appengine.py#L365-L375
[ "def", "_delete_entity", "(", "self", ")", ":", "if", "self", ".", "_is_ndb", "(", ")", ":", "_NDB_KEY", "(", "self", ".", "_model", ",", "self", ".", "_key_name", ")", ".", "delete", "(", ")", "else", ":", "entity_key", "=", "db", ".", "Key", ".", "from_path", "(", "self", ".", "_model", ".", "kind", "(", ")", ",", "self", ".", "_key_name", ")", "db", ".", "delete", "(", "entity_key", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
StorageByKeyName.locked_get
Retrieve Credential from datastore. Returns: oauth2client.Credentials
oauth2client/contrib/appengine.py
def locked_get(self): """Retrieve Credential from datastore. Returns: oauth2client.Credentials """ credentials = None if self._cache: json = self._cache.get(self._key_name) if json: credentials = client.Credentials.new_from_json(json) if credentials is None: entity = self._get_entity() if entity is not None: credentials = getattr(entity, self._property_name) if self._cache: self._cache.set(self._key_name, credentials.to_json()) if credentials and hasattr(credentials, 'set_store'): credentials.set_store(self) return credentials
def locked_get(self): """Retrieve Credential from datastore. Returns: oauth2client.Credentials """ credentials = None if self._cache: json = self._cache.get(self._key_name) if json: credentials = client.Credentials.new_from_json(json) if credentials is None: entity = self._get_entity() if entity is not None: credentials = getattr(entity, self._property_name) if self._cache: self._cache.set(self._key_name, credentials.to_json()) if credentials and hasattr(credentials, 'set_store'): credentials.set_store(self) return credentials
[ "Retrieve", "Credential", "from", "datastore", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/appengine.py#L378-L398
[ "def", "locked_get", "(", "self", ")", ":", "credentials", "=", "None", "if", "self", ".", "_cache", ":", "json", "=", "self", ".", "_cache", ".", "get", "(", "self", ".", "_key_name", ")", "if", "json", ":", "credentials", "=", "client", ".", "Credentials", ".", "new_from_json", "(", "json", ")", "if", "credentials", "is", "None", ":", "entity", "=", "self", ".", "_get_entity", "(", ")", "if", "entity", "is", "not", "None", ":", "credentials", "=", "getattr", "(", "entity", ",", "self", ".", "_property_name", ")", "if", "self", ".", "_cache", ":", "self", ".", "_cache", ".", "set", "(", "self", ".", "_key_name", ",", "credentials", ".", "to_json", "(", ")", ")", "if", "credentials", "and", "hasattr", "(", "credentials", ",", "'set_store'", ")", ":", "credentials", ".", "set_store", "(", "self", ")", "return", "credentials" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
StorageByKeyName.locked_put
Write a Credentials to the datastore. Args: credentials: Credentials, the credentials to store.
oauth2client/contrib/appengine.py
def locked_put(self, credentials): """Write a Credentials to the datastore. Args: credentials: Credentials, the credentials to store. """ entity = self._model.get_or_insert(self._key_name) setattr(entity, self._property_name, credentials) entity.put() if self._cache: self._cache.set(self._key_name, credentials.to_json())
def locked_put(self, credentials): """Write a Credentials to the datastore. Args: credentials: Credentials, the credentials to store. """ entity = self._model.get_or_insert(self._key_name) setattr(entity, self._property_name, credentials) entity.put() if self._cache: self._cache.set(self._key_name, credentials.to_json())
[ "Write", "a", "Credentials", "to", "the", "datastore", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/appengine.py#L401-L411
[ "def", "locked_put", "(", "self", ",", "credentials", ")", ":", "entity", "=", "self", ".", "_model", ".", "get_or_insert", "(", "self", ".", "_key_name", ")", "setattr", "(", "entity", ",", "self", ".", "_property_name", ",", "credentials", ")", "entity", ".", "put", "(", ")", "if", "self", ".", "_cache", ":", "self", ".", "_cache", ".", "set", "(", "self", ".", "_key_name", ",", "credentials", ".", "to_json", "(", ")", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
StorageByKeyName.locked_delete
Delete Credential from datastore.
oauth2client/contrib/appengine.py
def locked_delete(self): """Delete Credential from datastore.""" if self._cache: self._cache.delete(self._key_name) self._delete_entity()
def locked_delete(self): """Delete Credential from datastore.""" if self._cache: self._cache.delete(self._key_name) self._delete_entity()
[ "Delete", "Credential", "from", "datastore", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/appengine.py#L414-L420
[ "def", "locked_delete", "(", "self", ")", ":", "if", "self", ".", "_cache", ":", "self", ".", "_cache", ".", "delete", "(", "self", ".", "_key_name", ")", "self", ".", "_delete_entity", "(", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
OAuth2Decorator.oauth_required
Decorator that starts the OAuth 2.0 dance. Starts the OAuth dance for the logged in user if they haven't already granted access for this application. Args: method: callable, to be decorated method of a webapp.RequestHandler instance.
oauth2client/contrib/appengine.py
def oauth_required(self, method): """Decorator that starts the OAuth 2.0 dance. Starts the OAuth dance for the logged in user if they haven't already granted access for this application. Args: method: callable, to be decorated method of a webapp.RequestHandler instance. """ def check_oauth(request_handler, *args, **kwargs): if self._in_error: self._display_error_message(request_handler) return user = users.get_current_user() # Don't use @login_decorator as this could be used in a # POST request. if not user: request_handler.redirect(users.create_login_url( request_handler.request.uri)) return self._create_flow(request_handler) # Store the request URI in 'state' so we can use it later self.flow.params['state'] = _build_state_value( request_handler, user) self.credentials = self._storage_class( self._credentials_class, None, self._credentials_property_name, user=user).get() if not self.has_credentials(): return request_handler.redirect(self.authorize_url()) try: resp = method(request_handler, *args, **kwargs) except client.AccessTokenRefreshError: return request_handler.redirect(self.authorize_url()) finally: self.credentials = None return resp return check_oauth
def oauth_required(self, method): """Decorator that starts the OAuth 2.0 dance. Starts the OAuth dance for the logged in user if they haven't already granted access for this application. Args: method: callable, to be decorated method of a webapp.RequestHandler instance. """ def check_oauth(request_handler, *args, **kwargs): if self._in_error: self._display_error_message(request_handler) return user = users.get_current_user() # Don't use @login_decorator as this could be used in a # POST request. if not user: request_handler.redirect(users.create_login_url( request_handler.request.uri)) return self._create_flow(request_handler) # Store the request URI in 'state' so we can use it later self.flow.params['state'] = _build_state_value( request_handler, user) self.credentials = self._storage_class( self._credentials_class, None, self._credentials_property_name, user=user).get() if not self.has_credentials(): return request_handler.redirect(self.authorize_url()) try: resp = method(request_handler, *args, **kwargs) except client.AccessTokenRefreshError: return request_handler.redirect(self.authorize_url()) finally: self.credentials = None return resp return check_oauth
[ "Decorator", "that", "starts", "the", "OAuth", "2", ".", "0", "dance", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/appengine.py#L608-L651
[ "def", "oauth_required", "(", "self", ",", "method", ")", ":", "def", "check_oauth", "(", "request_handler", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_in_error", ":", "self", ".", "_display_error_message", "(", "request_handler", ")", "return", "user", "=", "users", ".", "get_current_user", "(", ")", "# Don't use @login_decorator as this could be used in a", "# POST request.", "if", "not", "user", ":", "request_handler", ".", "redirect", "(", "users", ".", "create_login_url", "(", "request_handler", ".", "request", ".", "uri", ")", ")", "return", "self", ".", "_create_flow", "(", "request_handler", ")", "# Store the request URI in 'state' so we can use it later", "self", ".", "flow", ".", "params", "[", "'state'", "]", "=", "_build_state_value", "(", "request_handler", ",", "user", ")", "self", ".", "credentials", "=", "self", ".", "_storage_class", "(", "self", ".", "_credentials_class", ",", "None", ",", "self", ".", "_credentials_property_name", ",", "user", "=", "user", ")", ".", "get", "(", ")", "if", "not", "self", ".", "has_credentials", "(", ")", ":", "return", "request_handler", ".", "redirect", "(", "self", ".", "authorize_url", "(", ")", ")", "try", ":", "resp", "=", "method", "(", "request_handler", ",", "*", "args", ",", "*", "*", "kwargs", ")", "except", "client", ".", "AccessTokenRefreshError", ":", "return", "request_handler", ".", "redirect", "(", "self", ".", "authorize_url", "(", ")", ")", "finally", ":", "self", ".", "credentials", "=", "None", "return", "resp", "return", "check_oauth" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
OAuth2Decorator._create_flow
Create the Flow object. The Flow is calculated lazily since we don't know where this app is running until it receives a request, at which point redirect_uri can be calculated and then the Flow object can be constructed. Args: request_handler: webapp.RequestHandler, the request handler.
oauth2client/contrib/appengine.py
def _create_flow(self, request_handler): """Create the Flow object. The Flow is calculated lazily since we don't know where this app is running until it receives a request, at which point redirect_uri can be calculated and then the Flow object can be constructed. Args: request_handler: webapp.RequestHandler, the request handler. """ if self.flow is None: redirect_uri = request_handler.request.relative_url( self._callback_path) # Usually /oauth2callback self.flow = client.OAuth2WebServerFlow( self._client_id, self._client_secret, self._scope, redirect_uri=redirect_uri, user_agent=self._user_agent, auth_uri=self._auth_uri, token_uri=self._token_uri, revoke_uri=self._revoke_uri, **self._kwargs)
def _create_flow(self, request_handler): """Create the Flow object. The Flow is calculated lazily since we don't know where this app is running until it receives a request, at which point redirect_uri can be calculated and then the Flow object can be constructed. Args: request_handler: webapp.RequestHandler, the request handler. """ if self.flow is None: redirect_uri = request_handler.request.relative_url( self._callback_path) # Usually /oauth2callback self.flow = client.OAuth2WebServerFlow( self._client_id, self._client_secret, self._scope, redirect_uri=redirect_uri, user_agent=self._user_agent, auth_uri=self._auth_uri, token_uri=self._token_uri, revoke_uri=self._revoke_uri, **self._kwargs)
[ "Create", "the", "Flow", "object", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/appengine.py#L653-L670
[ "def", "_create_flow", "(", "self", ",", "request_handler", ")", ":", "if", "self", ".", "flow", "is", "None", ":", "redirect_uri", "=", "request_handler", ".", "request", ".", "relative_url", "(", "self", ".", "_callback_path", ")", "# Usually /oauth2callback", "self", ".", "flow", "=", "client", ".", "OAuth2WebServerFlow", "(", "self", ".", "_client_id", ",", "self", ".", "_client_secret", ",", "self", ".", "_scope", ",", "redirect_uri", "=", "redirect_uri", ",", "user_agent", "=", "self", ".", "_user_agent", ",", "auth_uri", "=", "self", ".", "_auth_uri", ",", "token_uri", "=", "self", ".", "_token_uri", ",", "revoke_uri", "=", "self", ".", "_revoke_uri", ",", "*", "*", "self", ".", "_kwargs", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
OAuth2Decorator.oauth_aware
Decorator that sets up for OAuth 2.0 dance, but doesn't do it. Does all the setup for the OAuth dance, but doesn't initiate it. This decorator is useful if you want to create a page that knows whether or not the user has granted access to this application. From within a method decorated with @oauth_aware the has_credentials() and authorize_url() methods can be called. Args: method: callable, to be decorated method of a webapp.RequestHandler instance.
oauth2client/contrib/appengine.py
def oauth_aware(self, method): """Decorator that sets up for OAuth 2.0 dance, but doesn't do it. Does all the setup for the OAuth dance, but doesn't initiate it. This decorator is useful if you want to create a page that knows whether or not the user has granted access to this application. From within a method decorated with @oauth_aware the has_credentials() and authorize_url() methods can be called. Args: method: callable, to be decorated method of a webapp.RequestHandler instance. """ def setup_oauth(request_handler, *args, **kwargs): if self._in_error: self._display_error_message(request_handler) return user = users.get_current_user() # Don't use @login_decorator as this could be used in a # POST request. if not user: request_handler.redirect(users.create_login_url( request_handler.request.uri)) return self._create_flow(request_handler) self.flow.params['state'] = _build_state_value(request_handler, user) self.credentials = self._storage_class( self._credentials_class, None, self._credentials_property_name, user=user).get() try: resp = method(request_handler, *args, **kwargs) finally: self.credentials = None return resp return setup_oauth
def oauth_aware(self, method): """Decorator that sets up for OAuth 2.0 dance, but doesn't do it. Does all the setup for the OAuth dance, but doesn't initiate it. This decorator is useful if you want to create a page that knows whether or not the user has granted access to this application. From within a method decorated with @oauth_aware the has_credentials() and authorize_url() methods can be called. Args: method: callable, to be decorated method of a webapp.RequestHandler instance. """ def setup_oauth(request_handler, *args, **kwargs): if self._in_error: self._display_error_message(request_handler) return user = users.get_current_user() # Don't use @login_decorator as this could be used in a # POST request. if not user: request_handler.redirect(users.create_login_url( request_handler.request.uri)) return self._create_flow(request_handler) self.flow.params['state'] = _build_state_value(request_handler, user) self.credentials = self._storage_class( self._credentials_class, None, self._credentials_property_name, user=user).get() try: resp = method(request_handler, *args, **kwargs) finally: self.credentials = None return resp return setup_oauth
[ "Decorator", "that", "sets", "up", "for", "OAuth", "2", ".", "0", "dance", "but", "doesn", "t", "do", "it", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/appengine.py#L672-L711
[ "def", "oauth_aware", "(", "self", ",", "method", ")", ":", "def", "setup_oauth", "(", "request_handler", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_in_error", ":", "self", ".", "_display_error_message", "(", "request_handler", ")", "return", "user", "=", "users", ".", "get_current_user", "(", ")", "# Don't use @login_decorator as this could be used in a", "# POST request.", "if", "not", "user", ":", "request_handler", ".", "redirect", "(", "users", ".", "create_login_url", "(", "request_handler", ".", "request", ".", "uri", ")", ")", "return", "self", ".", "_create_flow", "(", "request_handler", ")", "self", ".", "flow", ".", "params", "[", "'state'", "]", "=", "_build_state_value", "(", "request_handler", ",", "user", ")", "self", ".", "credentials", "=", "self", ".", "_storage_class", "(", "self", ".", "_credentials_class", ",", "None", ",", "self", ".", "_credentials_property_name", ",", "user", "=", "user", ")", ".", "get", "(", ")", "try", ":", "resp", "=", "method", "(", "request_handler", ",", "*", "args", ",", "*", "*", "kwargs", ")", "finally", ":", "self", ".", "credentials", "=", "None", "return", "resp", "return", "setup_oauth" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
OAuth2Decorator.http
Returns an authorized http instance. Must only be called from within an @oauth_required decorated method, or from within an @oauth_aware decorated method where has_credentials() returns True. Args: *args: Positional arguments passed to httplib2.Http constructor. **kwargs: Positional arguments passed to httplib2.Http constructor.
oauth2client/contrib/appengine.py
def http(self, *args, **kwargs): """Returns an authorized http instance. Must only be called from within an @oauth_required decorated method, or from within an @oauth_aware decorated method where has_credentials() returns True. Args: *args: Positional arguments passed to httplib2.Http constructor. **kwargs: Positional arguments passed to httplib2.Http constructor. """ return self.credentials.authorize( transport.get_http_object(*args, **kwargs))
def http(self, *args, **kwargs): """Returns an authorized http instance. Must only be called from within an @oauth_required decorated method, or from within an @oauth_aware decorated method where has_credentials() returns True. Args: *args: Positional arguments passed to httplib2.Http constructor. **kwargs: Positional arguments passed to httplib2.Http constructor. """ return self.credentials.authorize( transport.get_http_object(*args, **kwargs))
[ "Returns", "an", "authorized", "http", "instance", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/appengine.py#L730-L742
[ "def", "http", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "credentials", ".", "authorize", "(", "transport", ".", "get_http_object", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
OAuth2Decorator.callback_handler
RequestHandler for the OAuth 2.0 redirect callback. Usage:: app = webapp.WSGIApplication([ ('/index', MyIndexHandler), ..., (decorator.callback_path, decorator.callback_handler()) ]) Returns: A webapp.RequestHandler that handles the redirect back from the server during the OAuth 2.0 dance.
oauth2client/contrib/appengine.py
def callback_handler(self): """RequestHandler for the OAuth 2.0 redirect callback. Usage:: app = webapp.WSGIApplication([ ('/index', MyIndexHandler), ..., (decorator.callback_path, decorator.callback_handler()) ]) Returns: A webapp.RequestHandler that handles the redirect back from the server during the OAuth 2.0 dance. """ decorator = self class OAuth2Handler(webapp.RequestHandler): """Handler for the redirect_uri of the OAuth 2.0 dance.""" @login_required def get(self): error = self.request.get('error') if error: errormsg = self.request.get('error_description', error) self.response.out.write( 'The authorization request failed: {0}'.format( _safe_html(errormsg))) else: user = users.get_current_user() decorator._create_flow(self) credentials = decorator.flow.step2_exchange( self.request.params) decorator._storage_class( decorator._credentials_class, None, decorator._credentials_property_name, user=user).put(credentials) redirect_uri = _parse_state_value( str(self.request.get('state')), user) if redirect_uri is None: self.response.out.write( 'The authorization request failed') return if (decorator._token_response_param and credentials.token_response): resp_json = json.dumps(credentials.token_response) redirect_uri = _helpers._add_query_parameter( redirect_uri, decorator._token_response_param, resp_json) self.redirect(redirect_uri) return OAuth2Handler
def callback_handler(self): """RequestHandler for the OAuth 2.0 redirect callback. Usage:: app = webapp.WSGIApplication([ ('/index', MyIndexHandler), ..., (decorator.callback_path, decorator.callback_handler()) ]) Returns: A webapp.RequestHandler that handles the redirect back from the server during the OAuth 2.0 dance. """ decorator = self class OAuth2Handler(webapp.RequestHandler): """Handler for the redirect_uri of the OAuth 2.0 dance.""" @login_required def get(self): error = self.request.get('error') if error: errormsg = self.request.get('error_description', error) self.response.out.write( 'The authorization request failed: {0}'.format( _safe_html(errormsg))) else: user = users.get_current_user() decorator._create_flow(self) credentials = decorator.flow.step2_exchange( self.request.params) decorator._storage_class( decorator._credentials_class, None, decorator._credentials_property_name, user=user).put(credentials) redirect_uri = _parse_state_value( str(self.request.get('state')), user) if redirect_uri is None: self.response.out.write( 'The authorization request failed') return if (decorator._token_response_param and credentials.token_response): resp_json = json.dumps(credentials.token_response) redirect_uri = _helpers._add_query_parameter( redirect_uri, decorator._token_response_param, resp_json) self.redirect(redirect_uri) return OAuth2Handler
[ "RequestHandler", "for", "the", "OAuth", "2", ".", "0", "redirect", "callback", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/appengine.py#L757-L810
[ "def", "callback_handler", "(", "self", ")", ":", "decorator", "=", "self", "class", "OAuth2Handler", "(", "webapp", ".", "RequestHandler", ")", ":", "\"\"\"Handler for the redirect_uri of the OAuth 2.0 dance.\"\"\"", "@", "login_required", "def", "get", "(", "self", ")", ":", "error", "=", "self", ".", "request", ".", "get", "(", "'error'", ")", "if", "error", ":", "errormsg", "=", "self", ".", "request", ".", "get", "(", "'error_description'", ",", "error", ")", "self", ".", "response", ".", "out", ".", "write", "(", "'The authorization request failed: {0}'", ".", "format", "(", "_safe_html", "(", "errormsg", ")", ")", ")", "else", ":", "user", "=", "users", ".", "get_current_user", "(", ")", "decorator", ".", "_create_flow", "(", "self", ")", "credentials", "=", "decorator", ".", "flow", ".", "step2_exchange", "(", "self", ".", "request", ".", "params", ")", "decorator", ".", "_storage_class", "(", "decorator", ".", "_credentials_class", ",", "None", ",", "decorator", ".", "_credentials_property_name", ",", "user", "=", "user", ")", ".", "put", "(", "credentials", ")", "redirect_uri", "=", "_parse_state_value", "(", "str", "(", "self", ".", "request", ".", "get", "(", "'state'", ")", ")", ",", "user", ")", "if", "redirect_uri", "is", "None", ":", "self", ".", "response", ".", "out", ".", "write", "(", "'The authorization request failed'", ")", "return", "if", "(", "decorator", ".", "_token_response_param", "and", "credentials", ".", "token_response", ")", ":", "resp_json", "=", "json", ".", "dumps", "(", "credentials", ".", "token_response", ")", "redirect_uri", "=", "_helpers", ".", "_add_query_parameter", "(", "redirect_uri", ",", "decorator", ".", "_token_response_param", ",", "resp_json", ")", "self", ".", "redirect", "(", "redirect_uri", ")", "return", "OAuth2Handler" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
generate_token
Generates a URL-safe token for the given user, action, time tuple. Args: key: secret key to use. user_id: the user ID of the authenticated user. action_id: a string identifier of the action they requested authorization for. when: the time in seconds since the epoch at which the user was authorized for this action. If not set the current time is used. Returns: A string XSRF protection token.
oauth2client/contrib/xsrfutil.py
def generate_token(key, user_id, action_id='', when=None): """Generates a URL-safe token for the given user, action, time tuple. Args: key: secret key to use. user_id: the user ID of the authenticated user. action_id: a string identifier of the action they requested authorization for. when: the time in seconds since the epoch at which the user was authorized for this action. If not set the current time is used. Returns: A string XSRF protection token. """ digester = hmac.new(_helpers._to_bytes(key, encoding='utf-8')) digester.update(_helpers._to_bytes(str(user_id), encoding='utf-8')) digester.update(DELIMITER) digester.update(_helpers._to_bytes(action_id, encoding='utf-8')) digester.update(DELIMITER) when = _helpers._to_bytes(str(when or int(time.time())), encoding='utf-8') digester.update(when) digest = digester.digest() token = base64.urlsafe_b64encode(digest + DELIMITER + when) return token
def generate_token(key, user_id, action_id='', when=None): """Generates a URL-safe token for the given user, action, time tuple. Args: key: secret key to use. user_id: the user ID of the authenticated user. action_id: a string identifier of the action they requested authorization for. when: the time in seconds since the epoch at which the user was authorized for this action. If not set the current time is used. Returns: A string XSRF protection token. """ digester = hmac.new(_helpers._to_bytes(key, encoding='utf-8')) digester.update(_helpers._to_bytes(str(user_id), encoding='utf-8')) digester.update(DELIMITER) digester.update(_helpers._to_bytes(action_id, encoding='utf-8')) digester.update(DELIMITER) when = _helpers._to_bytes(str(when or int(time.time())), encoding='utf-8') digester.update(when) digest = digester.digest() token = base64.urlsafe_b64encode(digest + DELIMITER + when) return token
[ "Generates", "a", "URL", "-", "safe", "token", "for", "the", "given", "user", "action", "time", "tuple", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/xsrfutil.py#L33-L57
[ "def", "generate_token", "(", "key", ",", "user_id", ",", "action_id", "=", "''", ",", "when", "=", "None", ")", ":", "digester", "=", "hmac", ".", "new", "(", "_helpers", ".", "_to_bytes", "(", "key", ",", "encoding", "=", "'utf-8'", ")", ")", "digester", ".", "update", "(", "_helpers", ".", "_to_bytes", "(", "str", "(", "user_id", ")", ",", "encoding", "=", "'utf-8'", ")", ")", "digester", ".", "update", "(", "DELIMITER", ")", "digester", ".", "update", "(", "_helpers", ".", "_to_bytes", "(", "action_id", ",", "encoding", "=", "'utf-8'", ")", ")", "digester", ".", "update", "(", "DELIMITER", ")", "when", "=", "_helpers", ".", "_to_bytes", "(", "str", "(", "when", "or", "int", "(", "time", ".", "time", "(", ")", ")", ")", ",", "encoding", "=", "'utf-8'", ")", "digester", ".", "update", "(", "when", ")", "digest", "=", "digester", ".", "digest", "(", ")", "token", "=", "base64", ".", "urlsafe_b64encode", "(", "digest", "+", "DELIMITER", "+", "when", ")", "return", "token" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
validate_token
Validates that the given token authorizes the user for the action. Tokens are invalid if the time of issue is too old or if the token does not match what generateToken outputs (i.e. the token was forged). Args: key: secret key to use. token: a string of the token generated by generateToken. user_id: the user ID of the authenticated user. action_id: a string identifier of the action they requested authorization for. Returns: A boolean - True if the user is authorized for the action, False otherwise.
oauth2client/contrib/xsrfutil.py
def validate_token(key, token, user_id, action_id="", current_time=None): """Validates that the given token authorizes the user for the action. Tokens are invalid if the time of issue is too old or if the token does not match what generateToken outputs (i.e. the token was forged). Args: key: secret key to use. token: a string of the token generated by generateToken. user_id: the user ID of the authenticated user. action_id: a string identifier of the action they requested authorization for. Returns: A boolean - True if the user is authorized for the action, False otherwise. """ if not token: return False try: decoded = base64.urlsafe_b64decode(token) token_time = int(decoded.split(DELIMITER)[-1]) except (TypeError, ValueError, binascii.Error): return False if current_time is None: current_time = time.time() # If the token is too old it's not valid. if current_time - token_time > DEFAULT_TIMEOUT_SECS: return False # The given token should match the generated one with the same time. expected_token = generate_token(key, user_id, action_id=action_id, when=token_time) if len(token) != len(expected_token): return False # Perform constant time comparison to avoid timing attacks different = 0 for x, y in zip(bytearray(token), bytearray(expected_token)): different |= x ^ y return not different
def validate_token(key, token, user_id, action_id="", current_time=None): """Validates that the given token authorizes the user for the action. Tokens are invalid if the time of issue is too old or if the token does not match what generateToken outputs (i.e. the token was forged). Args: key: secret key to use. token: a string of the token generated by generateToken. user_id: the user ID of the authenticated user. action_id: a string identifier of the action they requested authorization for. Returns: A boolean - True if the user is authorized for the action, False otherwise. """ if not token: return False try: decoded = base64.urlsafe_b64decode(token) token_time = int(decoded.split(DELIMITER)[-1]) except (TypeError, ValueError, binascii.Error): return False if current_time is None: current_time = time.time() # If the token is too old it's not valid. if current_time - token_time > DEFAULT_TIMEOUT_SECS: return False # The given token should match the generated one with the same time. expected_token = generate_token(key, user_id, action_id=action_id, when=token_time) if len(token) != len(expected_token): return False # Perform constant time comparison to avoid timing attacks different = 0 for x, y in zip(bytearray(token), bytearray(expected_token)): different |= x ^ y return not different
[ "Validates", "that", "the", "given", "token", "authorizes", "the", "user", "for", "the", "action", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/xsrfutil.py#L61-L101
[ "def", "validate_token", "(", "key", ",", "token", ",", "user_id", ",", "action_id", "=", "\"\"", ",", "current_time", "=", "None", ")", ":", "if", "not", "token", ":", "return", "False", "try", ":", "decoded", "=", "base64", ".", "urlsafe_b64decode", "(", "token", ")", "token_time", "=", "int", "(", "decoded", ".", "split", "(", "DELIMITER", ")", "[", "-", "1", "]", ")", "except", "(", "TypeError", ",", "ValueError", ",", "binascii", ".", "Error", ")", ":", "return", "False", "if", "current_time", "is", "None", ":", "current_time", "=", "time", ".", "time", "(", ")", "# If the token is too old it's not valid.", "if", "current_time", "-", "token_time", ">", "DEFAULT_TIMEOUT_SECS", ":", "return", "False", "# The given token should match the generated one with the same time.", "expected_token", "=", "generate_token", "(", "key", ",", "user_id", ",", "action_id", "=", "action_id", ",", "when", "=", "token_time", ")", "if", "len", "(", "token", ")", "!=", "len", "(", "expected_token", ")", ":", "return", "False", "# Perform constant time comparison to avoid timing attacks", "different", "=", "0", "for", "x", ",", "y", "in", "zip", "(", "bytearray", "(", "token", ")", ",", "bytearray", "(", "expected_token", ")", ")", ":", "different", "|=", "x", "^", "y", "return", "not", "different" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
_validate_clientsecrets
Validate parsed client secrets from a file. Args: clientsecrets_dict: dict, a dictionary holding the client secrets. Returns: tuple, a string of the client type and the information parsed from the file.
oauth2client/clientsecrets.py
def _validate_clientsecrets(clientsecrets_dict): """Validate parsed client secrets from a file. Args: clientsecrets_dict: dict, a dictionary holding the client secrets. Returns: tuple, a string of the client type and the information parsed from the file. """ _INVALID_FILE_FORMAT_MSG = ( 'Invalid file format. See ' 'https://developers.google.com/api-client-library/' 'python/guide/aaa_client_secrets') if clientsecrets_dict is None: raise InvalidClientSecretsError(_INVALID_FILE_FORMAT_MSG) try: (client_type, client_info), = clientsecrets_dict.items() except (ValueError, AttributeError): raise InvalidClientSecretsError( _INVALID_FILE_FORMAT_MSG + ' ' 'Expected a JSON object with a single property for a "web" or ' '"installed" application') if client_type not in VALID_CLIENT: raise InvalidClientSecretsError( 'Unknown client type: {0}.'.format(client_type)) for prop_name in VALID_CLIENT[client_type]['required']: if prop_name not in client_info: raise InvalidClientSecretsError( 'Missing property "{0}" in a client type of "{1}".'.format( prop_name, client_type)) for prop_name in VALID_CLIENT[client_type]['string']: if client_info[prop_name].startswith('[['): raise InvalidClientSecretsError( 'Property "{0}" is not configured.'.format(prop_name)) return client_type, client_info
def _validate_clientsecrets(clientsecrets_dict): """Validate parsed client secrets from a file. Args: clientsecrets_dict: dict, a dictionary holding the client secrets. Returns: tuple, a string of the client type and the information parsed from the file. """ _INVALID_FILE_FORMAT_MSG = ( 'Invalid file format. See ' 'https://developers.google.com/api-client-library/' 'python/guide/aaa_client_secrets') if clientsecrets_dict is None: raise InvalidClientSecretsError(_INVALID_FILE_FORMAT_MSG) try: (client_type, client_info), = clientsecrets_dict.items() except (ValueError, AttributeError): raise InvalidClientSecretsError( _INVALID_FILE_FORMAT_MSG + ' ' 'Expected a JSON object with a single property for a "web" or ' '"installed" application') if client_type not in VALID_CLIENT: raise InvalidClientSecretsError( 'Unknown client type: {0}.'.format(client_type)) for prop_name in VALID_CLIENT[client_type]['required']: if prop_name not in client_info: raise InvalidClientSecretsError( 'Missing property "{0}" in a client type of "{1}".'.format( prop_name, client_type)) for prop_name in VALID_CLIENT[client_type]['string']: if client_info[prop_name].startswith('[['): raise InvalidClientSecretsError( 'Property "{0}" is not configured.'.format(prop_name)) return client_type, client_info
[ "Validate", "parsed", "client", "secrets", "from", "a", "file", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/clientsecrets.py#L68-L106
[ "def", "_validate_clientsecrets", "(", "clientsecrets_dict", ")", ":", "_INVALID_FILE_FORMAT_MSG", "=", "(", "'Invalid file format. See '", "'https://developers.google.com/api-client-library/'", "'python/guide/aaa_client_secrets'", ")", "if", "clientsecrets_dict", "is", "None", ":", "raise", "InvalidClientSecretsError", "(", "_INVALID_FILE_FORMAT_MSG", ")", "try", ":", "(", "client_type", ",", "client_info", ")", ",", "=", "clientsecrets_dict", ".", "items", "(", ")", "except", "(", "ValueError", ",", "AttributeError", ")", ":", "raise", "InvalidClientSecretsError", "(", "_INVALID_FILE_FORMAT_MSG", "+", "' '", "'Expected a JSON object with a single property for a \"web\" or '", "'\"installed\" application'", ")", "if", "client_type", "not", "in", "VALID_CLIENT", ":", "raise", "InvalidClientSecretsError", "(", "'Unknown client type: {0}.'", ".", "format", "(", "client_type", ")", ")", "for", "prop_name", "in", "VALID_CLIENT", "[", "client_type", "]", "[", "'required'", "]", ":", "if", "prop_name", "not", "in", "client_info", ":", "raise", "InvalidClientSecretsError", "(", "'Missing property \"{0}\" in a client type of \"{1}\".'", ".", "format", "(", "prop_name", ",", "client_type", ")", ")", "for", "prop_name", "in", "VALID_CLIENT", "[", "client_type", "]", "[", "'string'", "]", ":", "if", "client_info", "[", "prop_name", "]", ".", "startswith", "(", "'[['", ")", ":", "raise", "InvalidClientSecretsError", "(", "'Property \"{0}\" is not configured.'", ".", "format", "(", "prop_name", ")", ")", "return", "client_type", ",", "client_info" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
loadfile
Loading of client_secrets JSON file, optionally backed by a cache. Typical cache storage would be App Engine memcache service, but you can pass in any other cache client that implements these methods: * ``get(key, namespace=ns)`` * ``set(key, value, namespace=ns)`` Usage:: # without caching client_type, client_info = loadfile('secrets.json') # using App Engine memcache service from google.appengine.api import memcache client_type, client_info = loadfile('secrets.json', cache=memcache) Args: filename: string, Path to a client_secrets.json file on a filesystem. cache: An optional cache service client that implements get() and set() methods. If not specified, the file is always being loaded from a filesystem. Raises: InvalidClientSecretsError: In case of a validation error or some I/O failure. Can happen only on cache miss. Returns: (client_type, client_info) tuple, as _loadfile() normally would. JSON contents is validated only during first load. Cache hits are not validated.
oauth2client/clientsecrets.py
def loadfile(filename, cache=None): """Loading of client_secrets JSON file, optionally backed by a cache. Typical cache storage would be App Engine memcache service, but you can pass in any other cache client that implements these methods: * ``get(key, namespace=ns)`` * ``set(key, value, namespace=ns)`` Usage:: # without caching client_type, client_info = loadfile('secrets.json') # using App Engine memcache service from google.appengine.api import memcache client_type, client_info = loadfile('secrets.json', cache=memcache) Args: filename: string, Path to a client_secrets.json file on a filesystem. cache: An optional cache service client that implements get() and set() methods. If not specified, the file is always being loaded from a filesystem. Raises: InvalidClientSecretsError: In case of a validation error or some I/O failure. Can happen only on cache miss. Returns: (client_type, client_info) tuple, as _loadfile() normally would. JSON contents is validated only during first load. Cache hits are not validated. """ _SECRET_NAMESPACE = 'oauth2client:secrets#ns' if not cache: return _loadfile(filename) obj = cache.get(filename, namespace=_SECRET_NAMESPACE) if obj is None: client_type, client_info = _loadfile(filename) obj = {client_type: client_info} cache.set(filename, obj, namespace=_SECRET_NAMESPACE) return next(six.iteritems(obj))
def loadfile(filename, cache=None): """Loading of client_secrets JSON file, optionally backed by a cache. Typical cache storage would be App Engine memcache service, but you can pass in any other cache client that implements these methods: * ``get(key, namespace=ns)`` * ``set(key, value, namespace=ns)`` Usage:: # without caching client_type, client_info = loadfile('secrets.json') # using App Engine memcache service from google.appengine.api import memcache client_type, client_info = loadfile('secrets.json', cache=memcache) Args: filename: string, Path to a client_secrets.json file on a filesystem. cache: An optional cache service client that implements get() and set() methods. If not specified, the file is always being loaded from a filesystem. Raises: InvalidClientSecretsError: In case of a validation error or some I/O failure. Can happen only on cache miss. Returns: (client_type, client_info) tuple, as _loadfile() normally would. JSON contents is validated only during first load. Cache hits are not validated. """ _SECRET_NAMESPACE = 'oauth2client:secrets#ns' if not cache: return _loadfile(filename) obj = cache.get(filename, namespace=_SECRET_NAMESPACE) if obj is None: client_type, client_info = _loadfile(filename) obj = {client_type: client_info} cache.set(filename, obj, namespace=_SECRET_NAMESPACE) return next(six.iteritems(obj))
[ "Loading", "of", "client_secrets", "JSON", "file", "optionally", "backed", "by", "a", "cache", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/clientsecrets.py#L129-L173
[ "def", "loadfile", "(", "filename", ",", "cache", "=", "None", ")", ":", "_SECRET_NAMESPACE", "=", "'oauth2client:secrets#ns'", "if", "not", "cache", ":", "return", "_loadfile", "(", "filename", ")", "obj", "=", "cache", ".", "get", "(", "filename", ",", "namespace", "=", "_SECRET_NAMESPACE", ")", "if", "obj", "is", "None", ":", "client_type", ",", "client_info", "=", "_loadfile", "(", "filename", ")", "obj", "=", "{", "client_type", ":", "client_info", "}", "cache", ".", "set", "(", "filename", ",", "obj", ",", "namespace", "=", "_SECRET_NAMESPACE", ")", "return", "next", "(", "six", ".", "iteritems", "(", "obj", ")", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
_SendRecv
Communicate with the Developer Shell server socket.
oauth2client/contrib/devshell.py
def _SendRecv(): """Communicate with the Developer Shell server socket.""" port = int(os.getenv(DEVSHELL_ENV, 0)) if port == 0: raise NoDevshellServer() sock = socket.socket() sock.connect(('localhost', port)) data = CREDENTIAL_INFO_REQUEST_JSON msg = '{0}\n{1}'.format(len(data), data) sock.sendall(_helpers._to_bytes(msg, encoding='utf-8')) header = sock.recv(6).decode() if '\n' not in header: raise CommunicationError('saw no newline in the first 6 bytes') len_str, json_str = header.split('\n', 1) to_read = int(len_str) - len(json_str) if to_read > 0: json_str += sock.recv(to_read, socket.MSG_WAITALL).decode() return CredentialInfoResponse(json_str)
def _SendRecv(): """Communicate with the Developer Shell server socket.""" port = int(os.getenv(DEVSHELL_ENV, 0)) if port == 0: raise NoDevshellServer() sock = socket.socket() sock.connect(('localhost', port)) data = CREDENTIAL_INFO_REQUEST_JSON msg = '{0}\n{1}'.format(len(data), data) sock.sendall(_helpers._to_bytes(msg, encoding='utf-8')) header = sock.recv(6).decode() if '\n' not in header: raise CommunicationError('saw no newline in the first 6 bytes') len_str, json_str = header.split('\n', 1) to_read = int(len_str) - len(json_str) if to_read > 0: json_str += sock.recv(to_read, socket.MSG_WAITALL).decode() return CredentialInfoResponse(json_str)
[ "Communicate", "with", "the", "Developer", "Shell", "server", "socket", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/devshell.py#L72-L94
[ "def", "_SendRecv", "(", ")", ":", "port", "=", "int", "(", "os", ".", "getenv", "(", "DEVSHELL_ENV", ",", "0", ")", ")", "if", "port", "==", "0", ":", "raise", "NoDevshellServer", "(", ")", "sock", "=", "socket", ".", "socket", "(", ")", "sock", ".", "connect", "(", "(", "'localhost'", ",", "port", ")", ")", "data", "=", "CREDENTIAL_INFO_REQUEST_JSON", "msg", "=", "'{0}\\n{1}'", ".", "format", "(", "len", "(", "data", ")", ",", "data", ")", "sock", ".", "sendall", "(", "_helpers", ".", "_to_bytes", "(", "msg", ",", "encoding", "=", "'utf-8'", ")", ")", "header", "=", "sock", ".", "recv", "(", "6", ")", ".", "decode", "(", ")", "if", "'\\n'", "not", "in", "header", ":", "raise", "CommunicationError", "(", "'saw no newline in the first 6 bytes'", ")", "len_str", ",", "json_str", "=", "header", ".", "split", "(", "'\\n'", ",", "1", ")", "to_read", "=", "int", "(", "len_str", ")", "-", "len", "(", "json_str", ")", "if", "to_read", ">", "0", ":", "json_str", "+=", "sock", ".", "recv", "(", "to_read", ",", "socket", ".", "MSG_WAITALL", ")", ".", "decode", "(", ")", "return", "CredentialInfoResponse", "(", "json_str", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
DevshellCredentials._refresh
Refreshes the access token. Args: http: unused HTTP object
oauth2client/contrib/devshell.py
def _refresh(self, http): """Refreshes the access token. Args: http: unused HTTP object """ self.devshell_response = _SendRecv() self.access_token = self.devshell_response.access_token expires_in = self.devshell_response.expires_in if expires_in is not None: delta = datetime.timedelta(seconds=expires_in) self.token_expiry = client._UTCNOW() + delta else: self.token_expiry = None
def _refresh(self, http): """Refreshes the access token. Args: http: unused HTTP object """ self.devshell_response = _SendRecv() self.access_token = self.devshell_response.access_token expires_in = self.devshell_response.expires_in if expires_in is not None: delta = datetime.timedelta(seconds=expires_in) self.token_expiry = client._UTCNOW() + delta else: self.token_expiry = None
[ "Refreshes", "the", "access", "token", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/devshell.py#L121-L134
[ "def", "_refresh", "(", "self", ",", "http", ")", ":", "self", ".", "devshell_response", "=", "_SendRecv", "(", ")", "self", ".", "access_token", "=", "self", ".", "devshell_response", ".", "access_token", "expires_in", "=", "self", ".", "devshell_response", ".", "expires_in", "if", "expires_in", "is", "not", "None", ":", "delta", "=", "datetime", ".", "timedelta", "(", "seconds", "=", "expires_in", ")", "self", ".", "token_expiry", "=", "client", ".", "_UTCNOW", "(", ")", "+", "delta", "else", ":", "self", ".", "token_expiry", "=", "None" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
Storage.locked_get
Retrieve Credential from file. Returns: oauth2client.client.Credentials
oauth2client/contrib/keyring_storage.py
def locked_get(self): """Retrieve Credential from file. Returns: oauth2client.client.Credentials """ credentials = None content = keyring.get_password(self._service_name, self._user_name) if content is not None: try: credentials = client.Credentials.new_from_json(content) credentials.set_store(self) except ValueError: pass return credentials
def locked_get(self): """Retrieve Credential from file. Returns: oauth2client.client.Credentials """ credentials = None content = keyring.get_password(self._service_name, self._user_name) if content is not None: try: credentials = client.Credentials.new_from_json(content) credentials.set_store(self) except ValueError: pass return credentials
[ "Retrieve", "Credential", "from", "file", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/keyring_storage.py#L62-L78
[ "def", "locked_get", "(", "self", ")", ":", "credentials", "=", "None", "content", "=", "keyring", ".", "get_password", "(", "self", ".", "_service_name", ",", "self", ".", "_user_name", ")", "if", "content", "is", "not", "None", ":", "try", ":", "credentials", "=", "client", ".", "Credentials", ".", "new_from_json", "(", "content", ")", "credentials", ".", "set_store", "(", "self", ")", "except", "ValueError", ":", "pass", "return", "credentials" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
Storage.locked_put
Write Credentials to file. Args: credentials: Credentials, the credentials to store.
oauth2client/contrib/keyring_storage.py
def locked_put(self, credentials): """Write Credentials to file. Args: credentials: Credentials, the credentials to store. """ keyring.set_password(self._service_name, self._user_name, credentials.to_json())
def locked_put(self, credentials): """Write Credentials to file. Args: credentials: Credentials, the credentials to store. """ keyring.set_password(self._service_name, self._user_name, credentials.to_json())
[ "Write", "Credentials", "to", "file", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/keyring_storage.py#L80-L87
[ "def", "locked_put", "(", "self", ",", "credentials", ")", ":", "keyring", ".", "set_password", "(", "self", ".", "_service_name", ",", "self", ".", "_user_name", ",", "credentials", ".", "to_json", "(", ")", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
pkcs12_key_as_pem
Convert the contents of a PKCS#12 key to PEM using pyOpenSSL. Args: private_key_bytes: Bytes. PKCS#12 key in DER format. private_key_password: String. Password for PKCS#12 key. Returns: String. PEM contents of ``private_key_bytes``.
oauth2client/_openssl_crypt.py
def pkcs12_key_as_pem(private_key_bytes, private_key_password): """Convert the contents of a PKCS#12 key to PEM using pyOpenSSL. Args: private_key_bytes: Bytes. PKCS#12 key in DER format. private_key_password: String. Password for PKCS#12 key. Returns: String. PEM contents of ``private_key_bytes``. """ private_key_password = _helpers._to_bytes(private_key_password) pkcs12 = crypto.load_pkcs12(private_key_bytes, private_key_password) return crypto.dump_privatekey(crypto.FILETYPE_PEM, pkcs12.get_privatekey())
def pkcs12_key_as_pem(private_key_bytes, private_key_password): """Convert the contents of a PKCS#12 key to PEM using pyOpenSSL. Args: private_key_bytes: Bytes. PKCS#12 key in DER format. private_key_password: String. Password for PKCS#12 key. Returns: String. PEM contents of ``private_key_bytes``. """ private_key_password = _helpers._to_bytes(private_key_password) pkcs12 = crypto.load_pkcs12(private_key_bytes, private_key_password) return crypto.dump_privatekey(crypto.FILETYPE_PEM, pkcs12.get_privatekey())
[ "Convert", "the", "contents", "of", "a", "PKCS#12", "key", "to", "PEM", "using", "pyOpenSSL", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/_openssl_crypt.py#L123-L136
[ "def", "pkcs12_key_as_pem", "(", "private_key_bytes", ",", "private_key_password", ")", ":", "private_key_password", "=", "_helpers", ".", "_to_bytes", "(", "private_key_password", ")", "pkcs12", "=", "crypto", ".", "load_pkcs12", "(", "private_key_bytes", ",", "private_key_password", ")", "return", "crypto", ".", "dump_privatekey", "(", "crypto", ".", "FILETYPE_PEM", ",", "pkcs12", ".", "get_privatekey", "(", ")", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
OpenSSLVerifier.verify
Verifies a message against a signature. Args: message: string or bytes, The message to verify. If string, will be encoded to bytes as utf-8. signature: string or bytes, The signature on the message. If string, will be encoded to bytes as utf-8. Returns: True if message was signed by the private key associated with the public key that this object was constructed with.
oauth2client/_openssl_crypt.py
def verify(self, message, signature): """Verifies a message against a signature. Args: message: string or bytes, The message to verify. If string, will be encoded to bytes as utf-8. signature: string or bytes, The signature on the message. If string, will be encoded to bytes as utf-8. Returns: True if message was signed by the private key associated with the public key that this object was constructed with. """ message = _helpers._to_bytes(message, encoding='utf-8') signature = _helpers._to_bytes(signature, encoding='utf-8') try: crypto.verify(self._pubkey, signature, message, 'sha256') return True except crypto.Error: return False
def verify(self, message, signature): """Verifies a message against a signature. Args: message: string or bytes, The message to verify. If string, will be encoded to bytes as utf-8. signature: string or bytes, The signature on the message. If string, will be encoded to bytes as utf-8. Returns: True if message was signed by the private key associated with the public key that this object was constructed with. """ message = _helpers._to_bytes(message, encoding='utf-8') signature = _helpers._to_bytes(signature, encoding='utf-8') try: crypto.verify(self._pubkey, signature, message, 'sha256') return True except crypto.Error: return False
[ "Verifies", "a", "message", "against", "a", "signature", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/_openssl_crypt.py#L32-L51
[ "def", "verify", "(", "self", ",", "message", ",", "signature", ")", ":", "message", "=", "_helpers", ".", "_to_bytes", "(", "message", ",", "encoding", "=", "'utf-8'", ")", "signature", "=", "_helpers", ".", "_to_bytes", "(", "signature", ",", "encoding", "=", "'utf-8'", ")", "try", ":", "crypto", ".", "verify", "(", "self", ".", "_pubkey", ",", "signature", ",", "message", ",", "'sha256'", ")", "return", "True", "except", "crypto", ".", "Error", ":", "return", "False" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
OpenSSLVerifier.from_string
Construct a Verified instance from a string. Args: key_pem: string, public key in PEM format. is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it is expected to be an RSA key in PEM format. Returns: Verifier instance. Raises: OpenSSL.crypto.Error: if the key_pem can't be parsed.
oauth2client/_openssl_crypt.py
def from_string(key_pem, is_x509_cert): """Construct a Verified instance from a string. Args: key_pem: string, public key in PEM format. is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it is expected to be an RSA key in PEM format. Returns: Verifier instance. Raises: OpenSSL.crypto.Error: if the key_pem can't be parsed. """ key_pem = _helpers._to_bytes(key_pem) if is_x509_cert: pubkey = crypto.load_certificate(crypto.FILETYPE_PEM, key_pem) else: pubkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key_pem) return OpenSSLVerifier(pubkey)
def from_string(key_pem, is_x509_cert): """Construct a Verified instance from a string. Args: key_pem: string, public key in PEM format. is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it is expected to be an RSA key in PEM format. Returns: Verifier instance. Raises: OpenSSL.crypto.Error: if the key_pem can't be parsed. """ key_pem = _helpers._to_bytes(key_pem) if is_x509_cert: pubkey = crypto.load_certificate(crypto.FILETYPE_PEM, key_pem) else: pubkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key_pem) return OpenSSLVerifier(pubkey)
[ "Construct", "a", "Verified", "instance", "from", "a", "string", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/_openssl_crypt.py#L54-L73
[ "def", "from_string", "(", "key_pem", ",", "is_x509_cert", ")", ":", "key_pem", "=", "_helpers", ".", "_to_bytes", "(", "key_pem", ")", "if", "is_x509_cert", ":", "pubkey", "=", "crypto", ".", "load_certificate", "(", "crypto", ".", "FILETYPE_PEM", ",", "key_pem", ")", "else", ":", "pubkey", "=", "crypto", ".", "load_privatekey", "(", "crypto", ".", "FILETYPE_PEM", ",", "key_pem", ")", "return", "OpenSSLVerifier", "(", "pubkey", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
OpenSSLSigner.sign
Signs a message. Args: message: bytes, Message to be signed. Returns: string, The signature of the message for the given key.
oauth2client/_openssl_crypt.py
def sign(self, message): """Signs a message. Args: message: bytes, Message to be signed. Returns: string, The signature of the message for the given key. """ message = _helpers._to_bytes(message, encoding='utf-8') return crypto.sign(self._key, message, 'sha256')
def sign(self, message): """Signs a message. Args: message: bytes, Message to be signed. Returns: string, The signature of the message for the given key. """ message = _helpers._to_bytes(message, encoding='utf-8') return crypto.sign(self._key, message, 'sha256')
[ "Signs", "a", "message", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/_openssl_crypt.py#L87-L97
[ "def", "sign", "(", "self", ",", "message", ")", ":", "message", "=", "_helpers", ".", "_to_bytes", "(", "message", ",", "encoding", "=", "'utf-8'", ")", "return", "crypto", ".", "sign", "(", "self", ".", "_key", ",", "message", ",", "'sha256'", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
OpenSSLSigner.from_string
Construct a Signer instance from a string. Args: key: string, private key in PKCS12 or PEM format. password: string, password for the private key file. Returns: Signer instance. Raises: OpenSSL.crypto.Error if the key can't be parsed.
oauth2client/_openssl_crypt.py
def from_string(key, password=b'notasecret'): """Construct a Signer instance from a string. Args: key: string, private key in PKCS12 or PEM format. password: string, password for the private key file. Returns: Signer instance. Raises: OpenSSL.crypto.Error if the key can't be parsed. """ key = _helpers._to_bytes(key) parsed_pem_key = _helpers._parse_pem_key(key) if parsed_pem_key: pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, parsed_pem_key) else: password = _helpers._to_bytes(password, encoding='utf-8') pkey = crypto.load_pkcs12(key, password).get_privatekey() return OpenSSLSigner(pkey)
def from_string(key, password=b'notasecret'): """Construct a Signer instance from a string. Args: key: string, private key in PKCS12 or PEM format. password: string, password for the private key file. Returns: Signer instance. Raises: OpenSSL.crypto.Error if the key can't be parsed. """ key = _helpers._to_bytes(key) parsed_pem_key = _helpers._parse_pem_key(key) if parsed_pem_key: pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, parsed_pem_key) else: password = _helpers._to_bytes(password, encoding='utf-8') pkey = crypto.load_pkcs12(key, password).get_privatekey() return OpenSSLSigner(pkey)
[ "Construct", "a", "Signer", "instance", "from", "a", "string", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/_openssl_crypt.py#L100-L120
[ "def", "from_string", "(", "key", ",", "password", "=", "b'notasecret'", ")", ":", "key", "=", "_helpers", ".", "_to_bytes", "(", "key", ")", "parsed_pem_key", "=", "_helpers", ".", "_parse_pem_key", "(", "key", ")", "if", "parsed_pem_key", ":", "pkey", "=", "crypto", ".", "load_privatekey", "(", "crypto", ".", "FILETYPE_PEM", ",", "parsed_pem_key", ")", "else", ":", "password", "=", "_helpers", ".", "_to_bytes", "(", "password", ",", "encoding", "=", "'utf-8'", ")", "pkey", "=", "crypto", ".", "load_pkcs12", "(", "key", ",", "password", ")", ".", "get_privatekey", "(", ")", "return", "OpenSSLSigner", "(", "pkey", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
PyCryptoVerifier.verify
Verifies a message against a signature. Args: message: string or bytes, The message to verify. If string, will be encoded to bytes as utf-8. signature: string or bytes, The signature on the message. Returns: True if message was signed by the private key associated with the public key that this object was constructed with.
oauth2client/_pycrypto_crypt.py
def verify(self, message, signature): """Verifies a message against a signature. Args: message: string or bytes, The message to verify. If string, will be encoded to bytes as utf-8. signature: string or bytes, The signature on the message. Returns: True if message was signed by the private key associated with the public key that this object was constructed with. """ message = _helpers._to_bytes(message, encoding='utf-8') return PKCS1_v1_5.new(self._pubkey).verify( SHA256.new(message), signature)
def verify(self, message, signature): """Verifies a message against a signature. Args: message: string or bytes, The message to verify. If string, will be encoded to bytes as utf-8. signature: string or bytes, The signature on the message. Returns: True if message was signed by the private key associated with the public key that this object was constructed with. """ message = _helpers._to_bytes(message, encoding='utf-8') return PKCS1_v1_5.new(self._pubkey).verify( SHA256.new(message), signature)
[ "Verifies", "a", "message", "against", "a", "signature", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/_pycrypto_crypt.py#L36-L50
[ "def", "verify", "(", "self", ",", "message", ",", "signature", ")", ":", "message", "=", "_helpers", ".", "_to_bytes", "(", "message", ",", "encoding", "=", "'utf-8'", ")", "return", "PKCS1_v1_5", ".", "new", "(", "self", ".", "_pubkey", ")", ".", "verify", "(", "SHA256", ".", "new", "(", "message", ")", ",", "signature", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
PyCryptoVerifier.from_string
Construct a Verified instance from a string. Args: key_pem: string, public key in PEM format. is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it is expected to be an RSA key in PEM format. Returns: Verifier instance.
oauth2client/_pycrypto_crypt.py
def from_string(key_pem, is_x509_cert): """Construct a Verified instance from a string. Args: key_pem: string, public key in PEM format. is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it is expected to be an RSA key in PEM format. Returns: Verifier instance. """ if is_x509_cert: key_pem = _helpers._to_bytes(key_pem) pemLines = key_pem.replace(b' ', b'').split() certDer = _helpers._urlsafe_b64decode(b''.join(pemLines[1:-1])) certSeq = DerSequence() certSeq.decode(certDer) tbsSeq = DerSequence() tbsSeq.decode(certSeq[0]) pubkey = RSA.importKey(tbsSeq[6]) else: pubkey = RSA.importKey(key_pem) return PyCryptoVerifier(pubkey)
def from_string(key_pem, is_x509_cert): """Construct a Verified instance from a string. Args: key_pem: string, public key in PEM format. is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it is expected to be an RSA key in PEM format. Returns: Verifier instance. """ if is_x509_cert: key_pem = _helpers._to_bytes(key_pem) pemLines = key_pem.replace(b' ', b'').split() certDer = _helpers._urlsafe_b64decode(b''.join(pemLines[1:-1])) certSeq = DerSequence() certSeq.decode(certDer) tbsSeq = DerSequence() tbsSeq.decode(certSeq[0]) pubkey = RSA.importKey(tbsSeq[6]) else: pubkey = RSA.importKey(key_pem) return PyCryptoVerifier(pubkey)
[ "Construct", "a", "Verified", "instance", "from", "a", "string", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/_pycrypto_crypt.py#L53-L75
[ "def", "from_string", "(", "key_pem", ",", "is_x509_cert", ")", ":", "if", "is_x509_cert", ":", "key_pem", "=", "_helpers", ".", "_to_bytes", "(", "key_pem", ")", "pemLines", "=", "key_pem", ".", "replace", "(", "b' '", ",", "b''", ")", ".", "split", "(", ")", "certDer", "=", "_helpers", ".", "_urlsafe_b64decode", "(", "b''", ".", "join", "(", "pemLines", "[", "1", ":", "-", "1", "]", ")", ")", "certSeq", "=", "DerSequence", "(", ")", "certSeq", ".", "decode", "(", "certDer", ")", "tbsSeq", "=", "DerSequence", "(", ")", "tbsSeq", ".", "decode", "(", "certSeq", "[", "0", "]", ")", "pubkey", "=", "RSA", ".", "importKey", "(", "tbsSeq", "[", "6", "]", ")", "else", ":", "pubkey", "=", "RSA", ".", "importKey", "(", "key_pem", ")", "return", "PyCryptoVerifier", "(", "pubkey", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
PyCryptoSigner.sign
Signs a message. Args: message: string, Message to be signed. Returns: string, The signature of the message for the given key.
oauth2client/_pycrypto_crypt.py
def sign(self, message): """Signs a message. Args: message: string, Message to be signed. Returns: string, The signature of the message for the given key. """ message = _helpers._to_bytes(message, encoding='utf-8') return PKCS1_v1_5.new(self._key).sign(SHA256.new(message))
def sign(self, message): """Signs a message. Args: message: string, Message to be signed. Returns: string, The signature of the message for the given key. """ message = _helpers._to_bytes(message, encoding='utf-8') return PKCS1_v1_5.new(self._key).sign(SHA256.new(message))
[ "Signs", "a", "message", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/_pycrypto_crypt.py#L89-L99
[ "def", "sign", "(", "self", ",", "message", ")", ":", "message", "=", "_helpers", ".", "_to_bytes", "(", "message", ",", "encoding", "=", "'utf-8'", ")", "return", "PKCS1_v1_5", ".", "new", "(", "self", ".", "_key", ")", ".", "sign", "(", "SHA256", ".", "new", "(", "message", ")", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
PyCryptoSigner.from_string
Construct a Signer instance from a string. Args: key: string, private key in PEM format. password: string, password for private key file. Unused for PEM files. Returns: Signer instance. Raises: NotImplementedError if the key isn't in PEM format.
oauth2client/_pycrypto_crypt.py
def from_string(key, password='notasecret'): """Construct a Signer instance from a string. Args: key: string, private key in PEM format. password: string, password for private key file. Unused for PEM files. Returns: Signer instance. Raises: NotImplementedError if the key isn't in PEM format. """ parsed_pem_key = _helpers._parse_pem_key(_helpers._to_bytes(key)) if parsed_pem_key: pkey = RSA.importKey(parsed_pem_key) else: raise NotImplementedError( 'No key in PEM format was detected. This implementation ' 'can only use the PyCrypto library for keys in PEM ' 'format.') return PyCryptoSigner(pkey)
def from_string(key, password='notasecret'): """Construct a Signer instance from a string. Args: key: string, private key in PEM format. password: string, password for private key file. Unused for PEM files. Returns: Signer instance. Raises: NotImplementedError if the key isn't in PEM format. """ parsed_pem_key = _helpers._parse_pem_key(_helpers._to_bytes(key)) if parsed_pem_key: pkey = RSA.importKey(parsed_pem_key) else: raise NotImplementedError( 'No key in PEM format was detected. This implementation ' 'can only use the PyCrypto library for keys in PEM ' 'format.') return PyCryptoSigner(pkey)
[ "Construct", "a", "Signer", "instance", "from", "a", "string", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/_pycrypto_crypt.py#L102-L124
[ "def", "from_string", "(", "key", ",", "password", "=", "'notasecret'", ")", ":", "parsed_pem_key", "=", "_helpers", ".", "_parse_pem_key", "(", "_helpers", ".", "_to_bytes", "(", "key", ")", ")", "if", "parsed_pem_key", ":", "pkey", "=", "RSA", ".", "importKey", "(", "parsed_pem_key", ")", "else", ":", "raise", "NotImplementedError", "(", "'No key in PEM format was detected. This implementation '", "'can only use the PyCrypto library for keys in PEM '", "'format.'", ")", "return", "PyCryptoSigner", "(", "pkey", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
run_flow
Core code for a command-line application. The ``run()`` function is called from your application and runs through all the steps to obtain credentials. It takes a ``Flow`` argument and attempts to open an authorization server page in the user's default web browser. The server asks the user to grant your application access to the user's data. If the user grants access, the ``run()`` function returns new credentials. The new credentials are also stored in the ``storage`` argument, which updates the file associated with the ``Storage`` object. It presumes it is run from a command-line application and supports the following flags: ``--auth_host_name`` (string, default: ``localhost``) Host name to use when running a local web server to handle redirects during OAuth authorization. ``--auth_host_port`` (integer, default: ``[8080, 8090]``) Port to use when running a local web server to handle redirects during OAuth authorization. Repeat this option to specify a list of values. ``--[no]auth_local_webserver`` (boolean, default: ``True``) Run a local web server to handle redirects during OAuth authorization. The tools module defines an ``ArgumentParser`` the already contains the flag definitions that ``run()`` requires. You can pass that ``ArgumentParser`` to your ``ArgumentParser`` constructor:: parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, parents=[tools.argparser]) flags = parser.parse_args(argv) Args: flow: Flow, an OAuth 2.0 Flow to step through. storage: Storage, a ``Storage`` to store the credential in. flags: ``argparse.Namespace``, (Optional) The command-line flags. This is the object returned from calling ``parse_args()`` on ``argparse.ArgumentParser`` as described above. Defaults to ``argparser.parse_args()``. http: An instance of ``httplib2.Http.request`` or something that acts like it. Returns: Credentials, the obtained credential.
oauth2client/tools.py
def run_flow(flow, storage, flags=None, http=None): """Core code for a command-line application. The ``run()`` function is called from your application and runs through all the steps to obtain credentials. It takes a ``Flow`` argument and attempts to open an authorization server page in the user's default web browser. The server asks the user to grant your application access to the user's data. If the user grants access, the ``run()`` function returns new credentials. The new credentials are also stored in the ``storage`` argument, which updates the file associated with the ``Storage`` object. It presumes it is run from a command-line application and supports the following flags: ``--auth_host_name`` (string, default: ``localhost``) Host name to use when running a local web server to handle redirects during OAuth authorization. ``--auth_host_port`` (integer, default: ``[8080, 8090]``) Port to use when running a local web server to handle redirects during OAuth authorization. Repeat this option to specify a list of values. ``--[no]auth_local_webserver`` (boolean, default: ``True``) Run a local web server to handle redirects during OAuth authorization. The tools module defines an ``ArgumentParser`` the already contains the flag definitions that ``run()`` requires. You can pass that ``ArgumentParser`` to your ``ArgumentParser`` constructor:: parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, parents=[tools.argparser]) flags = parser.parse_args(argv) Args: flow: Flow, an OAuth 2.0 Flow to step through. storage: Storage, a ``Storage`` to store the credential in. flags: ``argparse.Namespace``, (Optional) The command-line flags. This is the object returned from calling ``parse_args()`` on ``argparse.ArgumentParser`` as described above. Defaults to ``argparser.parse_args()``. http: An instance of ``httplib2.Http.request`` or something that acts like it. Returns: Credentials, the obtained credential. """ if flags is None: flags = argparser.parse_args() logging.getLogger().setLevel(getattr(logging, flags.logging_level)) if not flags.noauth_local_webserver: success = False port_number = 0 for port in flags.auth_host_port: port_number = port try: httpd = ClientRedirectServer((flags.auth_host_name, port), ClientRedirectHandler) except socket.error: pass else: success = True break flags.noauth_local_webserver = not success if not success: print(_FAILED_START_MESSAGE) if not flags.noauth_local_webserver: oauth_callback = 'http://{host}:{port}/'.format( host=flags.auth_host_name, port=port_number) else: oauth_callback = client.OOB_CALLBACK_URN flow.redirect_uri = oauth_callback authorize_url = flow.step1_get_authorize_url() if not flags.noauth_local_webserver: import webbrowser webbrowser.open(authorize_url, new=1, autoraise=True) print(_BROWSER_OPENED_MESSAGE.format(address=authorize_url)) else: print(_GO_TO_LINK_MESSAGE.format(address=authorize_url)) code = None if not flags.noauth_local_webserver: httpd.handle_request() if 'error' in httpd.query_params: sys.exit('Authentication request was rejected.') if 'code' in httpd.query_params: code = httpd.query_params['code'] else: print('Failed to find "code" in the query parameters ' 'of the redirect.') sys.exit('Try running with --noauth_local_webserver.') else: code = input('Enter verification code: ').strip() try: credential = flow.step2_exchange(code, http=http) except client.FlowExchangeError as e: sys.exit('Authentication has failed: {0}'.format(e)) storage.put(credential) credential.set_store(storage) print('Authentication successful.') return credential
def run_flow(flow, storage, flags=None, http=None): """Core code for a command-line application. The ``run()`` function is called from your application and runs through all the steps to obtain credentials. It takes a ``Flow`` argument and attempts to open an authorization server page in the user's default web browser. The server asks the user to grant your application access to the user's data. If the user grants access, the ``run()`` function returns new credentials. The new credentials are also stored in the ``storage`` argument, which updates the file associated with the ``Storage`` object. It presumes it is run from a command-line application and supports the following flags: ``--auth_host_name`` (string, default: ``localhost``) Host name to use when running a local web server to handle redirects during OAuth authorization. ``--auth_host_port`` (integer, default: ``[8080, 8090]``) Port to use when running a local web server to handle redirects during OAuth authorization. Repeat this option to specify a list of values. ``--[no]auth_local_webserver`` (boolean, default: ``True``) Run a local web server to handle redirects during OAuth authorization. The tools module defines an ``ArgumentParser`` the already contains the flag definitions that ``run()`` requires. You can pass that ``ArgumentParser`` to your ``ArgumentParser`` constructor:: parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter, parents=[tools.argparser]) flags = parser.parse_args(argv) Args: flow: Flow, an OAuth 2.0 Flow to step through. storage: Storage, a ``Storage`` to store the credential in. flags: ``argparse.Namespace``, (Optional) The command-line flags. This is the object returned from calling ``parse_args()`` on ``argparse.ArgumentParser`` as described above. Defaults to ``argparser.parse_args()``. http: An instance of ``httplib2.Http.request`` or something that acts like it. Returns: Credentials, the obtained credential. """ if flags is None: flags = argparser.parse_args() logging.getLogger().setLevel(getattr(logging, flags.logging_level)) if not flags.noauth_local_webserver: success = False port_number = 0 for port in flags.auth_host_port: port_number = port try: httpd = ClientRedirectServer((flags.auth_host_name, port), ClientRedirectHandler) except socket.error: pass else: success = True break flags.noauth_local_webserver = not success if not success: print(_FAILED_START_MESSAGE) if not flags.noauth_local_webserver: oauth_callback = 'http://{host}:{port}/'.format( host=flags.auth_host_name, port=port_number) else: oauth_callback = client.OOB_CALLBACK_URN flow.redirect_uri = oauth_callback authorize_url = flow.step1_get_authorize_url() if not flags.noauth_local_webserver: import webbrowser webbrowser.open(authorize_url, new=1, autoraise=True) print(_BROWSER_OPENED_MESSAGE.format(address=authorize_url)) else: print(_GO_TO_LINK_MESSAGE.format(address=authorize_url)) code = None if not flags.noauth_local_webserver: httpd.handle_request() if 'error' in httpd.query_params: sys.exit('Authentication request was rejected.') if 'code' in httpd.query_params: code = httpd.query_params['code'] else: print('Failed to find "code" in the query parameters ' 'of the redirect.') sys.exit('Try running with --noauth_local_webserver.') else: code = input('Enter verification code: ').strip() try: credential = flow.step2_exchange(code, http=http) except client.FlowExchangeError as e: sys.exit('Authentication has failed: {0}'.format(e)) storage.put(credential) credential.set_store(storage) print('Authentication successful.') return credential
[ "Core", "code", "for", "a", "command", "-", "line", "application", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/tools.py#L142-L251
[ "def", "run_flow", "(", "flow", ",", "storage", ",", "flags", "=", "None", ",", "http", "=", "None", ")", ":", "if", "flags", "is", "None", ":", "flags", "=", "argparser", ".", "parse_args", "(", ")", "logging", ".", "getLogger", "(", ")", ".", "setLevel", "(", "getattr", "(", "logging", ",", "flags", ".", "logging_level", ")", ")", "if", "not", "flags", ".", "noauth_local_webserver", ":", "success", "=", "False", "port_number", "=", "0", "for", "port", "in", "flags", ".", "auth_host_port", ":", "port_number", "=", "port", "try", ":", "httpd", "=", "ClientRedirectServer", "(", "(", "flags", ".", "auth_host_name", ",", "port", ")", ",", "ClientRedirectHandler", ")", "except", "socket", ".", "error", ":", "pass", "else", ":", "success", "=", "True", "break", "flags", ".", "noauth_local_webserver", "=", "not", "success", "if", "not", "success", ":", "print", "(", "_FAILED_START_MESSAGE", ")", "if", "not", "flags", ".", "noauth_local_webserver", ":", "oauth_callback", "=", "'http://{host}:{port}/'", ".", "format", "(", "host", "=", "flags", ".", "auth_host_name", ",", "port", "=", "port_number", ")", "else", ":", "oauth_callback", "=", "client", ".", "OOB_CALLBACK_URN", "flow", ".", "redirect_uri", "=", "oauth_callback", "authorize_url", "=", "flow", ".", "step1_get_authorize_url", "(", ")", "if", "not", "flags", ".", "noauth_local_webserver", ":", "import", "webbrowser", "webbrowser", ".", "open", "(", "authorize_url", ",", "new", "=", "1", ",", "autoraise", "=", "True", ")", "print", "(", "_BROWSER_OPENED_MESSAGE", ".", "format", "(", "address", "=", "authorize_url", ")", ")", "else", ":", "print", "(", "_GO_TO_LINK_MESSAGE", ".", "format", "(", "address", "=", "authorize_url", ")", ")", "code", "=", "None", "if", "not", "flags", ".", "noauth_local_webserver", ":", "httpd", ".", "handle_request", "(", ")", "if", "'error'", "in", "httpd", ".", "query_params", ":", "sys", ".", "exit", "(", "'Authentication request was rejected.'", ")", "if", "'code'", "in", "httpd", ".", "query_params", ":", "code", "=", "httpd", ".", "query_params", "[", "'code'", "]", "else", ":", "print", "(", "'Failed to find \"code\" in the query parameters '", "'of the redirect.'", ")", "sys", ".", "exit", "(", "'Try running with --noauth_local_webserver.'", ")", "else", ":", "code", "=", "input", "(", "'Enter verification code: '", ")", ".", "strip", "(", ")", "try", ":", "credential", "=", "flow", ".", "step2_exchange", "(", "code", ",", "http", "=", "http", ")", "except", "client", ".", "FlowExchangeError", "as", "e", ":", "sys", ".", "exit", "(", "'Authentication has failed: {0}'", ".", "format", "(", "e", ")", ")", "storage", ".", "put", "(", "credential", ")", "credential", ".", "set_store", "(", "storage", ")", "print", "(", "'Authentication successful.'", ")", "return", "credential" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
ClientRedirectHandler.do_GET
Handle a GET request. Parses the query parameters and prints a message if the flow has completed. Note that we can't detect if an error occurred.
oauth2client/tools.py
def do_GET(self): """Handle a GET request. Parses the query parameters and prints a message if the flow has completed. Note that we can't detect if an error occurred. """ self.send_response(http_client.OK) self.send_header('Content-type', 'text/html') self.end_headers() parts = urllib.parse.urlparse(self.path) query = _helpers.parse_unique_urlencoded(parts.query) self.server.query_params = query self.wfile.write( b'<html><head><title>Authentication Status</title></head>') self.wfile.write( b'<body><p>The authentication flow has completed.</p>') self.wfile.write(b'</body></html>')
def do_GET(self): """Handle a GET request. Parses the query parameters and prints a message if the flow has completed. Note that we can't detect if an error occurred. """ self.send_response(http_client.OK) self.send_header('Content-type', 'text/html') self.end_headers() parts = urllib.parse.urlparse(self.path) query = _helpers.parse_unique_urlencoded(parts.query) self.server.query_params = query self.wfile.write( b'<html><head><title>Authentication Status</title></head>') self.wfile.write( b'<body><p>The authentication flow has completed.</p>') self.wfile.write(b'</body></html>')
[ "Handle", "a", "GET", "request", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/tools.py#L118-L135
[ "def", "do_GET", "(", "self", ")", ":", "self", ".", "send_response", "(", "http_client", ".", "OK", ")", "self", ".", "send_header", "(", "'Content-type'", ",", "'text/html'", ")", "self", ".", "end_headers", "(", ")", "parts", "=", "urllib", ".", "parse", ".", "urlparse", "(", "self", ".", "path", ")", "query", "=", "_helpers", ".", "parse_unique_urlencoded", "(", "parts", ".", "query", ")", "self", ".", "server", ".", "query_params", "=", "query", "self", ".", "wfile", ".", "write", "(", "b'<html><head><title>Authentication Status</title></head>'", ")", "self", ".", "wfile", ".", "write", "(", "b'<body><p>The authentication flow has completed.</p>'", ")", "self", ".", "wfile", ".", "write", "(", "b'</body></html>'", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
oauth_required
Decorator to require OAuth2 credentials for a view. .. code-block:: python :caption: views.py :name: views_required_2 from oauth2client.django_util.decorators import oauth_required @oauth_required def requires_default_scopes(request): email = request.credentials.id_token['email'] service = build(serviceName='calendar', version='v3', http=request.oauth.http, developerKey=API_KEY) events = service.events().list( calendarId='primary').execute()['items'] return HttpResponse( "email: {0}, calendar: {1}".format(email, str(events))) Args: decorated_function: View function to decorate, must have the Django request object as the first argument. scopes: Scopes to require, will default. decorator_kwargs: Can include ``return_url`` to specify the URL to return to after OAuth2 authorization is complete. Returns: An OAuth2 Authorize view if credentials are not found or if the credentials are missing the required scopes. Otherwise, the decorated view.
oauth2client/contrib/django_util/decorators.py
def oauth_required(decorated_function=None, scopes=None, **decorator_kwargs): """ Decorator to require OAuth2 credentials for a view. .. code-block:: python :caption: views.py :name: views_required_2 from oauth2client.django_util.decorators import oauth_required @oauth_required def requires_default_scopes(request): email = request.credentials.id_token['email'] service = build(serviceName='calendar', version='v3', http=request.oauth.http, developerKey=API_KEY) events = service.events().list( calendarId='primary').execute()['items'] return HttpResponse( "email: {0}, calendar: {1}".format(email, str(events))) Args: decorated_function: View function to decorate, must have the Django request object as the first argument. scopes: Scopes to require, will default. decorator_kwargs: Can include ``return_url`` to specify the URL to return to after OAuth2 authorization is complete. Returns: An OAuth2 Authorize view if credentials are not found or if the credentials are missing the required scopes. Otherwise, the decorated view. """ def curry_wrapper(wrapped_function): @wraps(wrapped_function) def required_wrapper(request, *args, **kwargs): if not (django_util.oauth2_settings.storage_model is None or request.user.is_authenticated()): redirect_str = '{0}?next={1}'.format( django.conf.settings.LOGIN_URL, parse.quote(request.path)) return shortcuts.redirect(redirect_str) return_url = decorator_kwargs.pop('return_url', request.get_full_path()) user_oauth = django_util.UserOAuth2(request, scopes, return_url) if not user_oauth.has_credentials(): return shortcuts.redirect(user_oauth.get_authorize_redirect()) setattr(request, django_util.oauth2_settings.request_prefix, user_oauth) return wrapped_function(request, *args, **kwargs) return required_wrapper if decorated_function: return curry_wrapper(decorated_function) else: return curry_wrapper
def oauth_required(decorated_function=None, scopes=None, **decorator_kwargs): """ Decorator to require OAuth2 credentials for a view. .. code-block:: python :caption: views.py :name: views_required_2 from oauth2client.django_util.decorators import oauth_required @oauth_required def requires_default_scopes(request): email = request.credentials.id_token['email'] service = build(serviceName='calendar', version='v3', http=request.oauth.http, developerKey=API_KEY) events = service.events().list( calendarId='primary').execute()['items'] return HttpResponse( "email: {0}, calendar: {1}".format(email, str(events))) Args: decorated_function: View function to decorate, must have the Django request object as the first argument. scopes: Scopes to require, will default. decorator_kwargs: Can include ``return_url`` to specify the URL to return to after OAuth2 authorization is complete. Returns: An OAuth2 Authorize view if credentials are not found or if the credentials are missing the required scopes. Otherwise, the decorated view. """ def curry_wrapper(wrapped_function): @wraps(wrapped_function) def required_wrapper(request, *args, **kwargs): if not (django_util.oauth2_settings.storage_model is None or request.user.is_authenticated()): redirect_str = '{0}?next={1}'.format( django.conf.settings.LOGIN_URL, parse.quote(request.path)) return shortcuts.redirect(redirect_str) return_url = decorator_kwargs.pop('return_url', request.get_full_path()) user_oauth = django_util.UserOAuth2(request, scopes, return_url) if not user_oauth.has_credentials(): return shortcuts.redirect(user_oauth.get_authorize_redirect()) setattr(request, django_util.oauth2_settings.request_prefix, user_oauth) return wrapped_function(request, *args, **kwargs) return required_wrapper if decorated_function: return curry_wrapper(decorated_function) else: return curry_wrapper
[ "Decorator", "to", "require", "OAuth2", "credentials", "for", "a", "view", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/django_util/decorators.py#L36-L94
[ "def", "oauth_required", "(", "decorated_function", "=", "None", ",", "scopes", "=", "None", ",", "*", "*", "decorator_kwargs", ")", ":", "def", "curry_wrapper", "(", "wrapped_function", ")", ":", "@", "wraps", "(", "wrapped_function", ")", "def", "required_wrapper", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "(", "django_util", ".", "oauth2_settings", ".", "storage_model", "is", "None", "or", "request", ".", "user", ".", "is_authenticated", "(", ")", ")", ":", "redirect_str", "=", "'{0}?next={1}'", ".", "format", "(", "django", ".", "conf", ".", "settings", ".", "LOGIN_URL", ",", "parse", ".", "quote", "(", "request", ".", "path", ")", ")", "return", "shortcuts", ".", "redirect", "(", "redirect_str", ")", "return_url", "=", "decorator_kwargs", ".", "pop", "(", "'return_url'", ",", "request", ".", "get_full_path", "(", ")", ")", "user_oauth", "=", "django_util", ".", "UserOAuth2", "(", "request", ",", "scopes", ",", "return_url", ")", "if", "not", "user_oauth", ".", "has_credentials", "(", ")", ":", "return", "shortcuts", ".", "redirect", "(", "user_oauth", ".", "get_authorize_redirect", "(", ")", ")", "setattr", "(", "request", ",", "django_util", ".", "oauth2_settings", ".", "request_prefix", ",", "user_oauth", ")", "return", "wrapped_function", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "required_wrapper", "if", "decorated_function", ":", "return", "curry_wrapper", "(", "decorated_function", ")", "else", ":", "return", "curry_wrapper" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
oauth_enabled
Decorator to enable OAuth Credentials if authorized, and setup the oauth object on the request object to provide helper functions to start the flow otherwise. .. code-block:: python :caption: views.py :name: views_enabled3 from oauth2client.django_util.decorators import oauth_enabled @oauth_enabled def optional_oauth2(request): if request.oauth.has_credentials(): # this could be passed into a view # request.oauth.http is also initialized return HttpResponse("User email: {0}".format( request.oauth.credentials.id_token['email']) else: return HttpResponse('Here is an OAuth Authorize link: <a href="{0}">Authorize</a>'.format( request.oauth.get_authorize_redirect())) Args: decorated_function: View function to decorate. scopes: Scopes to require, will default. decorator_kwargs: Can include ``return_url`` to specify the URL to return to after OAuth2 authorization is complete. Returns: The decorated view function.
oauth2client/contrib/django_util/decorators.py
def oauth_enabled(decorated_function=None, scopes=None, **decorator_kwargs): """ Decorator to enable OAuth Credentials if authorized, and setup the oauth object on the request object to provide helper functions to start the flow otherwise. .. code-block:: python :caption: views.py :name: views_enabled3 from oauth2client.django_util.decorators import oauth_enabled @oauth_enabled def optional_oauth2(request): if request.oauth.has_credentials(): # this could be passed into a view # request.oauth.http is also initialized return HttpResponse("User email: {0}".format( request.oauth.credentials.id_token['email']) else: return HttpResponse('Here is an OAuth Authorize link: <a href="{0}">Authorize</a>'.format( request.oauth.get_authorize_redirect())) Args: decorated_function: View function to decorate. scopes: Scopes to require, will default. decorator_kwargs: Can include ``return_url`` to specify the URL to return to after OAuth2 authorization is complete. Returns: The decorated view function. """ def curry_wrapper(wrapped_function): @wraps(wrapped_function) def enabled_wrapper(request, *args, **kwargs): return_url = decorator_kwargs.pop('return_url', request.get_full_path()) user_oauth = django_util.UserOAuth2(request, scopes, return_url) setattr(request, django_util.oauth2_settings.request_prefix, user_oauth) return wrapped_function(request, *args, **kwargs) return enabled_wrapper if decorated_function: return curry_wrapper(decorated_function) else: return curry_wrapper
def oauth_enabled(decorated_function=None, scopes=None, **decorator_kwargs): """ Decorator to enable OAuth Credentials if authorized, and setup the oauth object on the request object to provide helper functions to start the flow otherwise. .. code-block:: python :caption: views.py :name: views_enabled3 from oauth2client.django_util.decorators import oauth_enabled @oauth_enabled def optional_oauth2(request): if request.oauth.has_credentials(): # this could be passed into a view # request.oauth.http is also initialized return HttpResponse("User email: {0}".format( request.oauth.credentials.id_token['email']) else: return HttpResponse('Here is an OAuth Authorize link: <a href="{0}">Authorize</a>'.format( request.oauth.get_authorize_redirect())) Args: decorated_function: View function to decorate. scopes: Scopes to require, will default. decorator_kwargs: Can include ``return_url`` to specify the URL to return to after OAuth2 authorization is complete. Returns: The decorated view function. """ def curry_wrapper(wrapped_function): @wraps(wrapped_function) def enabled_wrapper(request, *args, **kwargs): return_url = decorator_kwargs.pop('return_url', request.get_full_path()) user_oauth = django_util.UserOAuth2(request, scopes, return_url) setattr(request, django_util.oauth2_settings.request_prefix, user_oauth) return wrapped_function(request, *args, **kwargs) return enabled_wrapper if decorated_function: return curry_wrapper(decorated_function) else: return curry_wrapper
[ "Decorator", "to", "enable", "OAuth", "Credentials", "if", "authorized", "and", "setup", "the", "oauth", "object", "on", "the", "request", "object", "to", "provide", "helper", "functions", "to", "start", "the", "flow", "otherwise", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/django_util/decorators.py#L97-L145
[ "def", "oauth_enabled", "(", "decorated_function", "=", "None", ",", "scopes", "=", "None", ",", "*", "*", "decorator_kwargs", ")", ":", "def", "curry_wrapper", "(", "wrapped_function", ")", ":", "@", "wraps", "(", "wrapped_function", ")", "def", "enabled_wrapper", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return_url", "=", "decorator_kwargs", ".", "pop", "(", "'return_url'", ",", "request", ".", "get_full_path", "(", ")", ")", "user_oauth", "=", "django_util", ".", "UserOAuth2", "(", "request", ",", "scopes", ",", "return_url", ")", "setattr", "(", "request", ",", "django_util", ".", "oauth2_settings", ".", "request_prefix", ",", "user_oauth", ")", "return", "wrapped_function", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "enabled_wrapper", "if", "decorated_function", ":", "return", "curry_wrapper", "(", "decorated_function", ")", "else", ":", "return", "curry_wrapper" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
code_verifier
Generates a 'code_verifier' as described in section 4.1 of RFC 7636. This is a 'high-entropy cryptographic random string' that will be impractical for an attacker to guess. Args: n_bytes: integer between 31 and 96, inclusive. default: 64 number of bytes of entropy to include in verifier. Returns: Bytestring, representing urlsafe base64-encoded random data.
oauth2client/_pkce.py
def code_verifier(n_bytes=64): """ Generates a 'code_verifier' as described in section 4.1 of RFC 7636. This is a 'high-entropy cryptographic random string' that will be impractical for an attacker to guess. Args: n_bytes: integer between 31 and 96, inclusive. default: 64 number of bytes of entropy to include in verifier. Returns: Bytestring, representing urlsafe base64-encoded random data. """ verifier = base64.urlsafe_b64encode(os.urandom(n_bytes)).rstrip(b'=') # https://tools.ietf.org/html/rfc7636#section-4.1 # minimum length of 43 characters and a maximum length of 128 characters. if len(verifier) < 43: raise ValueError("Verifier too short. n_bytes must be > 30.") elif len(verifier) > 128: raise ValueError("Verifier too long. n_bytes must be < 97.") else: return verifier
def code_verifier(n_bytes=64): """ Generates a 'code_verifier' as described in section 4.1 of RFC 7636. This is a 'high-entropy cryptographic random string' that will be impractical for an attacker to guess. Args: n_bytes: integer between 31 and 96, inclusive. default: 64 number of bytes of entropy to include in verifier. Returns: Bytestring, representing urlsafe base64-encoded random data. """ verifier = base64.urlsafe_b64encode(os.urandom(n_bytes)).rstrip(b'=') # https://tools.ietf.org/html/rfc7636#section-4.1 # minimum length of 43 characters and a maximum length of 128 characters. if len(verifier) < 43: raise ValueError("Verifier too short. n_bytes must be > 30.") elif len(verifier) > 128: raise ValueError("Verifier too long. n_bytes must be < 97.") else: return verifier
[ "Generates", "a", "code_verifier", "as", "described", "in", "section", "4", ".", "1", "of", "RFC", "7636", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/_pkce.py#L27-L49
[ "def", "code_verifier", "(", "n_bytes", "=", "64", ")", ":", "verifier", "=", "base64", ".", "urlsafe_b64encode", "(", "os", ".", "urandom", "(", "n_bytes", ")", ")", ".", "rstrip", "(", "b'='", ")", "# https://tools.ietf.org/html/rfc7636#section-4.1", "# minimum length of 43 characters and a maximum length of 128 characters.", "if", "len", "(", "verifier", ")", "<", "43", ":", "raise", "ValueError", "(", "\"Verifier too short. n_bytes must be > 30.\"", ")", "elif", "len", "(", "verifier", ")", ">", "128", ":", "raise", "ValueError", "(", "\"Verifier too long. n_bytes must be < 97.\"", ")", "else", ":", "return", "verifier" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
code_challenge
Creates a 'code_challenge' as described in section 4.2 of RFC 7636 by taking the sha256 hash of the verifier and then urlsafe base64-encoding it. Args: verifier: bytestring, representing a code_verifier as generated by code_verifier(). Returns: Bytestring, representing a urlsafe base64-encoded sha256 hash digest, without '=' padding.
oauth2client/_pkce.py
def code_challenge(verifier): """ Creates a 'code_challenge' as described in section 4.2 of RFC 7636 by taking the sha256 hash of the verifier and then urlsafe base64-encoding it. Args: verifier: bytestring, representing a code_verifier as generated by code_verifier(). Returns: Bytestring, representing a urlsafe base64-encoded sha256 hash digest, without '=' padding. """ digest = hashlib.sha256(verifier).digest() return base64.urlsafe_b64encode(digest).rstrip(b'=')
def code_challenge(verifier): """ Creates a 'code_challenge' as described in section 4.2 of RFC 7636 by taking the sha256 hash of the verifier and then urlsafe base64-encoding it. Args: verifier: bytestring, representing a code_verifier as generated by code_verifier(). Returns: Bytestring, representing a urlsafe base64-encoded sha256 hash digest, without '=' padding. """ digest = hashlib.sha256(verifier).digest() return base64.urlsafe_b64encode(digest).rstrip(b'=')
[ "Creates", "a", "code_challenge", "as", "described", "in", "section", "4", ".", "2", "of", "RFC", "7636", "by", "taking", "the", "sha256", "hash", "of", "the", "verifier", "and", "then", "urlsafe", "base64", "-", "encoding", "it", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/_pkce.py#L52-L67
[ "def", "code_challenge", "(", "verifier", ")", ":", "digest", "=", "hashlib", ".", "sha256", "(", "verifier", ")", ".", "digest", "(", ")", "return", "base64", ".", "urlsafe_b64encode", "(", "digest", ")", ".", "rstrip", "(", "b'='", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
AppAssertionCredentials._retrieve_info
Retrieves service account info for invalid credentials. Args: http: an object to be used to make HTTP requests.
oauth2client/contrib/gce.py
def _retrieve_info(self, http): """Retrieves service account info for invalid credentials. Args: http: an object to be used to make HTTP requests. """ if self.invalid: info = _metadata.get_service_account_info( http, service_account=self.service_account_email or 'default') self.invalid = False self.service_account_email = info['email'] self.scopes = info['scopes']
def _retrieve_info(self, http): """Retrieves service account info for invalid credentials. Args: http: an object to be used to make HTTP requests. """ if self.invalid: info = _metadata.get_service_account_info( http, service_account=self.service_account_email or 'default') self.invalid = False self.service_account_email = info['email'] self.scopes = info['scopes']
[ "Retrieves", "service", "account", "info", "for", "invalid", "credentials", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/gce.py#L102-L114
[ "def", "_retrieve_info", "(", "self", ",", "http", ")", ":", "if", "self", ".", "invalid", ":", "info", "=", "_metadata", ".", "get_service_account_info", "(", "http", ",", "service_account", "=", "self", ".", "service_account_email", "or", "'default'", ")", "self", ".", "invalid", "=", "False", "self", ".", "service_account_email", "=", "info", "[", "'email'", "]", "self", ".", "scopes", "=", "info", "[", "'scopes'", "]" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
AppAssertionCredentials._refresh
Refreshes the access token. Skip all the storage hoops and just refresh using the API. Args: http: an object to be used to make HTTP requests. Raises: HttpAccessTokenRefreshError: When the refresh fails.
oauth2client/contrib/gce.py
def _refresh(self, http): """Refreshes the access token. Skip all the storage hoops and just refresh using the API. Args: http: an object to be used to make HTTP requests. Raises: HttpAccessTokenRefreshError: When the refresh fails. """ try: self._retrieve_info(http) self.access_token, self.token_expiry = _metadata.get_token( http, service_account=self.service_account_email) except http_client.HTTPException as err: raise client.HttpAccessTokenRefreshError(str(err))
def _refresh(self, http): """Refreshes the access token. Skip all the storage hoops and just refresh using the API. Args: http: an object to be used to make HTTP requests. Raises: HttpAccessTokenRefreshError: When the refresh fails. """ try: self._retrieve_info(http) self.access_token, self.token_expiry = _metadata.get_token( http, service_account=self.service_account_email) except http_client.HTTPException as err: raise client.HttpAccessTokenRefreshError(str(err))
[ "Refreshes", "the", "access", "token", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/gce.py#L116-L132
[ "def", "_refresh", "(", "self", ",", "http", ")", ":", "try", ":", "self", ".", "_retrieve_info", "(", "http", ")", "self", ".", "access_token", ",", "self", ".", "token_expiry", "=", "_metadata", ".", "get_token", "(", "http", ",", "service_account", "=", "self", ".", "service_account_email", ")", "except", "http_client", ".", "HTTPException", "as", "err", ":", "raise", "client", ".", "HttpAccessTokenRefreshError", "(", "str", "(", "err", ")", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
DjangoORMStorage.locked_get
Retrieve stored credential from the Django ORM. Returns: oauth2client.Credentials retrieved from the Django ORM, associated with the ``model``, ``key_value``->``key_name`` pair used to query for the model, and ``property_name`` identifying the ``CredentialsProperty`` field, all of which are defined in the constructor for this Storage object.
oauth2client/contrib/django_util/storage.py
def locked_get(self): """Retrieve stored credential from the Django ORM. Returns: oauth2client.Credentials retrieved from the Django ORM, associated with the ``model``, ``key_value``->``key_name`` pair used to query for the model, and ``property_name`` identifying the ``CredentialsProperty`` field, all of which are defined in the constructor for this Storage object. """ query = {self.key_name: self.key_value} entities = self.model_class.objects.filter(**query) if len(entities) > 0: credential = getattr(entities[0], self.property_name) if getattr(credential, 'set_store', None) is not None: credential.set_store(self) return credential else: return None
def locked_get(self): """Retrieve stored credential from the Django ORM. Returns: oauth2client.Credentials retrieved from the Django ORM, associated with the ``model``, ``key_value``->``key_name`` pair used to query for the model, and ``property_name`` identifying the ``CredentialsProperty`` field, all of which are defined in the constructor for this Storage object. """ query = {self.key_name: self.key_value} entities = self.model_class.objects.filter(**query) if len(entities) > 0: credential = getattr(entities[0], self.property_name) if getattr(credential, 'set_store', None) is not None: credential.set_store(self) return credential else: return None
[ "Retrieve", "stored", "credential", "from", "the", "Django", "ORM", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/django_util/storage.py#L45-L64
[ "def", "locked_get", "(", "self", ")", ":", "query", "=", "{", "self", ".", "key_name", ":", "self", ".", "key_value", "}", "entities", "=", "self", ".", "model_class", ".", "objects", ".", "filter", "(", "*", "*", "query", ")", "if", "len", "(", "entities", ")", ">", "0", ":", "credential", "=", "getattr", "(", "entities", "[", "0", "]", ",", "self", ".", "property_name", ")", "if", "getattr", "(", "credential", ",", "'set_store'", ",", "None", ")", "is", "not", "None", ":", "credential", ".", "set_store", "(", "self", ")", "return", "credential", "else", ":", "return", "None" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
DjangoORMStorage.locked_put
Write a Credentials to the Django datastore. Args: credentials: Credentials, the credentials to store.
oauth2client/contrib/django_util/storage.py
def locked_put(self, credentials): """Write a Credentials to the Django datastore. Args: credentials: Credentials, the credentials to store. """ entity, _ = self.model_class.objects.get_or_create( **{self.key_name: self.key_value}) setattr(entity, self.property_name, credentials) entity.save()
def locked_put(self, credentials): """Write a Credentials to the Django datastore. Args: credentials: Credentials, the credentials to store. """ entity, _ = self.model_class.objects.get_or_create( **{self.key_name: self.key_value}) setattr(entity, self.property_name, credentials) entity.save()
[ "Write", "a", "Credentials", "to", "the", "Django", "datastore", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/django_util/storage.py#L66-L76
[ "def", "locked_put", "(", "self", ",", "credentials", ")", ":", "entity", ",", "_", "=", "self", ".", "model_class", ".", "objects", ".", "get_or_create", "(", "*", "*", "{", "self", ".", "key_name", ":", "self", ".", "key_value", "}", ")", "setattr", "(", "entity", ",", "self", ".", "property_name", ",", "credentials", ")", "entity", ".", "save", "(", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
DjangoORMStorage.locked_delete
Delete Credentials from the datastore.
oauth2client/contrib/django_util/storage.py
def locked_delete(self): """Delete Credentials from the datastore.""" query = {self.key_name: self.key_value} self.model_class.objects.filter(**query).delete()
def locked_delete(self): """Delete Credentials from the datastore.""" query = {self.key_name: self.key_value} self.model_class.objects.filter(**query).delete()
[ "Delete", "Credentials", "from", "the", "datastore", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/django_util/storage.py#L78-L81
[ "def", "locked_delete", "(", "self", ")", ":", "query", "=", "{", "self", ".", "key_name", ":", "self", ".", "key_value", "}", "self", ".", "model_class", ".", "objects", ".", "filter", "(", "*", "*", "query", ")", ".", "delete", "(", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
DictionaryStorage.locked_get
Retrieve the credentials from the dictionary, if they exist. Returns: A :class:`oauth2client.client.OAuth2Credentials` instance.
oauth2client/contrib/dictionary_storage.py
def locked_get(self): """Retrieve the credentials from the dictionary, if they exist. Returns: A :class:`oauth2client.client.OAuth2Credentials` instance. """ serialized = self._dictionary.get(self._key) if serialized is None: return None credentials = client.OAuth2Credentials.from_json(serialized) credentials.set_store(self) return credentials
def locked_get(self): """Retrieve the credentials from the dictionary, if they exist. Returns: A :class:`oauth2client.client.OAuth2Credentials` instance. """ serialized = self._dictionary.get(self._key) if serialized is None: return None credentials = client.OAuth2Credentials.from_json(serialized) credentials.set_store(self) return credentials
[ "Retrieve", "the", "credentials", "from", "the", "dictionary", "if", "they", "exist", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/dictionary_storage.py#L38-L51
[ "def", "locked_get", "(", "self", ")", ":", "serialized", "=", "self", ".", "_dictionary", ".", "get", "(", "self", ".", "_key", ")", "if", "serialized", "is", "None", ":", "return", "None", "credentials", "=", "client", ".", "OAuth2Credentials", ".", "from_json", "(", "serialized", ")", "credentials", ".", "set_store", "(", "self", ")", "return", "credentials" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
DictionaryStorage.locked_put
Save the credentials to the dictionary. Args: credentials: A :class:`oauth2client.client.OAuth2Credentials` instance.
oauth2client/contrib/dictionary_storage.py
def locked_put(self, credentials): """Save the credentials to the dictionary. Args: credentials: A :class:`oauth2client.client.OAuth2Credentials` instance. """ serialized = credentials.to_json() self._dictionary[self._key] = serialized
def locked_put(self, credentials): """Save the credentials to the dictionary. Args: credentials: A :class:`oauth2client.client.OAuth2Credentials` instance. """ serialized = credentials.to_json() self._dictionary[self._key] = serialized
[ "Save", "the", "credentials", "to", "the", "dictionary", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/dictionary_storage.py#L53-L61
[ "def", "locked_put", "(", "self", ",", "credentials", ")", ":", "serialized", "=", "credentials", ".", "to_json", "(", ")", "self", ".", "_dictionary", "[", "self", ".", "_key", "]", "=", "serialized" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
FlowNDBProperty._validate
Validates a value as a proper Flow object. Args: value: A value to be set on the property. Raises: TypeError if the value is not an instance of Flow.
oauth2client/contrib/_appengine_ndb.py
def _validate(self, value): """Validates a value as a proper Flow object. Args: value: A value to be set on the property. Raises: TypeError if the value is not an instance of Flow. """ _LOGGER.info('validate: Got type %s', type(value)) if value is not None and not isinstance(value, client.Flow): raise TypeError( 'Property {0} must be convertible to a flow ' 'instance; received: {1}.'.format(self._name, value))
def _validate(self, value): """Validates a value as a proper Flow object. Args: value: A value to be set on the property. Raises: TypeError if the value is not an instance of Flow. """ _LOGGER.info('validate: Got type %s', type(value)) if value is not None and not isinstance(value, client.Flow): raise TypeError( 'Property {0} must be convertible to a flow ' 'instance; received: {1}.'.format(self._name, value))
[ "Validates", "a", "value", "as", "a", "proper", "Flow", "object", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/_appengine_ndb.py#L68-L81
[ "def", "_validate", "(", "self", ",", "value", ")", ":", "_LOGGER", ".", "info", "(", "'validate: Got type %s'", ",", "type", "(", "value", ")", ")", "if", "value", "is", "not", "None", "and", "not", "isinstance", "(", "value", ",", "client", ".", "Flow", ")", ":", "raise", "TypeError", "(", "'Property {0} must be convertible to a flow '", "'instance; received: {1}.'", ".", "format", "(", "self", ".", "_name", ",", "value", ")", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
CredentialsNDBProperty._from_base_type
Converts our stored JSON string back to the desired type. Args: value: A value from the datastore to be converted to the desired type. Returns: A deserialized Credentials (or subclass) object, else None if the value can't be parsed.
oauth2client/contrib/_appengine_ndb.py
def _from_base_type(self, value): """Converts our stored JSON string back to the desired type. Args: value: A value from the datastore to be converted to the desired type. Returns: A deserialized Credentials (or subclass) object, else None if the value can't be parsed. """ if not value: return None try: # Uses the from_json method of the implied class of value credentials = client.Credentials.new_from_json(value) except ValueError: credentials = None return credentials
def _from_base_type(self, value): """Converts our stored JSON string back to the desired type. Args: value: A value from the datastore to be converted to the desired type. Returns: A deserialized Credentials (or subclass) object, else None if the value can't be parsed. """ if not value: return None try: # Uses the from_json method of the implied class of value credentials = client.Credentials.new_from_json(value) except ValueError: credentials = None return credentials
[ "Converts", "our", "stored", "JSON", "string", "back", "to", "the", "desired", "type", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/_appengine_ndb.py#L126-L144
[ "def", "_from_base_type", "(", "self", ",", "value", ")", ":", "if", "not", "value", ":", "return", "None", "try", ":", "# Uses the from_json method of the implied class of value", "credentials", "=", "client", ".", "Credentials", ".", "new_from_json", "(", "value", ")", "except", "ValueError", ":", "credentials", "=", "None", "return", "credentials" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
_make_flow
Creates a Web Server Flow Args: request: A Django request object. scopes: the request oauth2 scopes. return_url: The URL to return to after the flow is complete. Defaults to the path of the current request. Returns: An OAuth2 flow object that has been stored in the session.
oauth2client/contrib/django_util/views.py
def _make_flow(request, scopes, return_url=None): """Creates a Web Server Flow Args: request: A Django request object. scopes: the request oauth2 scopes. return_url: The URL to return to after the flow is complete. Defaults to the path of the current request. Returns: An OAuth2 flow object that has been stored in the session. """ # Generate a CSRF token to prevent malicious requests. csrf_token = hashlib.sha256(os.urandom(1024)).hexdigest() request.session[_CSRF_KEY] = csrf_token state = json.dumps({ 'csrf_token': csrf_token, 'return_url': return_url, }) flow = client.OAuth2WebServerFlow( client_id=django_util.oauth2_settings.client_id, client_secret=django_util.oauth2_settings.client_secret, scope=scopes, state=state, redirect_uri=request.build_absolute_uri( urlresolvers.reverse("google_oauth:callback"))) flow_key = _FLOW_KEY.format(csrf_token) request.session[flow_key] = jsonpickle.encode(flow) return flow
def _make_flow(request, scopes, return_url=None): """Creates a Web Server Flow Args: request: A Django request object. scopes: the request oauth2 scopes. return_url: The URL to return to after the flow is complete. Defaults to the path of the current request. Returns: An OAuth2 flow object that has been stored in the session. """ # Generate a CSRF token to prevent malicious requests. csrf_token = hashlib.sha256(os.urandom(1024)).hexdigest() request.session[_CSRF_KEY] = csrf_token state = json.dumps({ 'csrf_token': csrf_token, 'return_url': return_url, }) flow = client.OAuth2WebServerFlow( client_id=django_util.oauth2_settings.client_id, client_secret=django_util.oauth2_settings.client_secret, scope=scopes, state=state, redirect_uri=request.build_absolute_uri( urlresolvers.reverse("google_oauth:callback"))) flow_key = _FLOW_KEY.format(csrf_token) request.session[flow_key] = jsonpickle.encode(flow) return flow
[ "Creates", "a", "Web", "Server", "Flow" ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/django_util/views.py#L44-L76
[ "def", "_make_flow", "(", "request", ",", "scopes", ",", "return_url", "=", "None", ")", ":", "# Generate a CSRF token to prevent malicious requests.", "csrf_token", "=", "hashlib", ".", "sha256", "(", "os", ".", "urandom", "(", "1024", ")", ")", ".", "hexdigest", "(", ")", "request", ".", "session", "[", "_CSRF_KEY", "]", "=", "csrf_token", "state", "=", "json", ".", "dumps", "(", "{", "'csrf_token'", ":", "csrf_token", ",", "'return_url'", ":", "return_url", ",", "}", ")", "flow", "=", "client", ".", "OAuth2WebServerFlow", "(", "client_id", "=", "django_util", ".", "oauth2_settings", ".", "client_id", ",", "client_secret", "=", "django_util", ".", "oauth2_settings", ".", "client_secret", ",", "scope", "=", "scopes", ",", "state", "=", "state", ",", "redirect_uri", "=", "request", ".", "build_absolute_uri", "(", "urlresolvers", ".", "reverse", "(", "\"google_oauth:callback\"", ")", ")", ")", "flow_key", "=", "_FLOW_KEY", ".", "format", "(", "csrf_token", ")", "request", ".", "session", "[", "flow_key", "]", "=", "jsonpickle", ".", "encode", "(", "flow", ")", "return", "flow" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
_get_flow_for_token
Looks up the flow in session to recover information about requested scopes. Args: csrf_token: The token passed in the callback request that should match the one previously generated and stored in the request on the initial authorization view. Returns: The OAuth2 Flow object associated with this flow based on the CSRF token.
oauth2client/contrib/django_util/views.py
def _get_flow_for_token(csrf_token, request): """ Looks up the flow in session to recover information about requested scopes. Args: csrf_token: The token passed in the callback request that should match the one previously generated and stored in the request on the initial authorization view. Returns: The OAuth2 Flow object associated with this flow based on the CSRF token. """ flow_pickle = request.session.get(_FLOW_KEY.format(csrf_token), None) return None if flow_pickle is None else jsonpickle.decode(flow_pickle)
def _get_flow_for_token(csrf_token, request): """ Looks up the flow in session to recover information about requested scopes. Args: csrf_token: The token passed in the callback request that should match the one previously generated and stored in the request on the initial authorization view. Returns: The OAuth2 Flow object associated with this flow based on the CSRF token. """ flow_pickle = request.session.get(_FLOW_KEY.format(csrf_token), None) return None if flow_pickle is None else jsonpickle.decode(flow_pickle)
[ "Looks", "up", "the", "flow", "in", "session", "to", "recover", "information", "about", "requested", "scopes", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/django_util/views.py#L79-L93
[ "def", "_get_flow_for_token", "(", "csrf_token", ",", "request", ")", ":", "flow_pickle", "=", "request", ".", "session", ".", "get", "(", "_FLOW_KEY", ".", "format", "(", "csrf_token", ")", ",", "None", ")", "return", "None", "if", "flow_pickle", "is", "None", "else", "jsonpickle", ".", "decode", "(", "flow_pickle", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
oauth2_callback
View that handles the user's return from OAuth2 provider. This view verifies the CSRF state and OAuth authorization code, and on success stores the credentials obtained in the storage provider, and redirects to the return_url specified in the authorize view and stored in the session. Args: request: Django request. Returns: A redirect response back to the return_url.
oauth2client/contrib/django_util/views.py
def oauth2_callback(request): """ View that handles the user's return from OAuth2 provider. This view verifies the CSRF state and OAuth authorization code, and on success stores the credentials obtained in the storage provider, and redirects to the return_url specified in the authorize view and stored in the session. Args: request: Django request. Returns: A redirect response back to the return_url. """ if 'error' in request.GET: reason = request.GET.get( 'error_description', request.GET.get('error', '')) reason = html.escape(reason) return http.HttpResponseBadRequest( 'Authorization failed {0}'.format(reason)) try: encoded_state = request.GET['state'] code = request.GET['code'] except KeyError: return http.HttpResponseBadRequest( 'Request missing state or authorization code') try: server_csrf = request.session[_CSRF_KEY] except KeyError: return http.HttpResponseBadRequest( 'No existing session for this flow.') try: state = json.loads(encoded_state) client_csrf = state['csrf_token'] return_url = state['return_url'] except (ValueError, KeyError): return http.HttpResponseBadRequest('Invalid state parameter.') if client_csrf != server_csrf: return http.HttpResponseBadRequest('Invalid CSRF token.') flow = _get_flow_for_token(client_csrf, request) if not flow: return http.HttpResponseBadRequest('Missing Oauth2 flow.') try: credentials = flow.step2_exchange(code) except client.FlowExchangeError as exchange_error: return http.HttpResponseBadRequest( 'An error has occurred: {0}'.format(exchange_error)) get_storage(request).put(credentials) signals.oauth2_authorized.send(sender=signals.oauth2_authorized, request=request, credentials=credentials) return shortcuts.redirect(return_url)
def oauth2_callback(request): """ View that handles the user's return from OAuth2 provider. This view verifies the CSRF state and OAuth authorization code, and on success stores the credentials obtained in the storage provider, and redirects to the return_url specified in the authorize view and stored in the session. Args: request: Django request. Returns: A redirect response back to the return_url. """ if 'error' in request.GET: reason = request.GET.get( 'error_description', request.GET.get('error', '')) reason = html.escape(reason) return http.HttpResponseBadRequest( 'Authorization failed {0}'.format(reason)) try: encoded_state = request.GET['state'] code = request.GET['code'] except KeyError: return http.HttpResponseBadRequest( 'Request missing state or authorization code') try: server_csrf = request.session[_CSRF_KEY] except KeyError: return http.HttpResponseBadRequest( 'No existing session for this flow.') try: state = json.loads(encoded_state) client_csrf = state['csrf_token'] return_url = state['return_url'] except (ValueError, KeyError): return http.HttpResponseBadRequest('Invalid state parameter.') if client_csrf != server_csrf: return http.HttpResponseBadRequest('Invalid CSRF token.') flow = _get_flow_for_token(client_csrf, request) if not flow: return http.HttpResponseBadRequest('Missing Oauth2 flow.') try: credentials = flow.step2_exchange(code) except client.FlowExchangeError as exchange_error: return http.HttpResponseBadRequest( 'An error has occurred: {0}'.format(exchange_error)) get_storage(request).put(credentials) signals.oauth2_authorized.send(sender=signals.oauth2_authorized, request=request, credentials=credentials) return shortcuts.redirect(return_url)
[ "View", "that", "handles", "the", "user", "s", "return", "from", "OAuth2", "provider", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/django_util/views.py#L96-L156
[ "def", "oauth2_callback", "(", "request", ")", ":", "if", "'error'", "in", "request", ".", "GET", ":", "reason", "=", "request", ".", "GET", ".", "get", "(", "'error_description'", ",", "request", ".", "GET", ".", "get", "(", "'error'", ",", "''", ")", ")", "reason", "=", "html", ".", "escape", "(", "reason", ")", "return", "http", ".", "HttpResponseBadRequest", "(", "'Authorization failed {0}'", ".", "format", "(", "reason", ")", ")", "try", ":", "encoded_state", "=", "request", ".", "GET", "[", "'state'", "]", "code", "=", "request", ".", "GET", "[", "'code'", "]", "except", "KeyError", ":", "return", "http", ".", "HttpResponseBadRequest", "(", "'Request missing state or authorization code'", ")", "try", ":", "server_csrf", "=", "request", ".", "session", "[", "_CSRF_KEY", "]", "except", "KeyError", ":", "return", "http", ".", "HttpResponseBadRequest", "(", "'No existing session for this flow.'", ")", "try", ":", "state", "=", "json", ".", "loads", "(", "encoded_state", ")", "client_csrf", "=", "state", "[", "'csrf_token'", "]", "return_url", "=", "state", "[", "'return_url'", "]", "except", "(", "ValueError", ",", "KeyError", ")", ":", "return", "http", ".", "HttpResponseBadRequest", "(", "'Invalid state parameter.'", ")", "if", "client_csrf", "!=", "server_csrf", ":", "return", "http", ".", "HttpResponseBadRequest", "(", "'Invalid CSRF token.'", ")", "flow", "=", "_get_flow_for_token", "(", "client_csrf", ",", "request", ")", "if", "not", "flow", ":", "return", "http", ".", "HttpResponseBadRequest", "(", "'Missing Oauth2 flow.'", ")", "try", ":", "credentials", "=", "flow", ".", "step2_exchange", "(", "code", ")", "except", "client", ".", "FlowExchangeError", "as", "exchange_error", ":", "return", "http", ".", "HttpResponseBadRequest", "(", "'An error has occurred: {0}'", ".", "format", "(", "exchange_error", ")", ")", "get_storage", "(", "request", ")", ".", "put", "(", "credentials", ")", "signals", ".", "oauth2_authorized", ".", "send", "(", "sender", "=", "signals", ".", "oauth2_authorized", ",", "request", "=", "request", ",", "credentials", "=", "credentials", ")", "return", "shortcuts", ".", "redirect", "(", "return_url", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
oauth2_authorize
View to start the OAuth2 Authorization flow. This view starts the OAuth2 authorization flow. If scopes is passed in as a GET URL parameter, it will authorize those scopes, otherwise the default scopes specified in settings. The return_url can also be specified as a GET parameter, otherwise the referer header will be checked, and if that isn't found it will return to the root path. Args: request: The Django request object. Returns: A redirect to Google OAuth2 Authorization.
oauth2client/contrib/django_util/views.py
def oauth2_authorize(request): """ View to start the OAuth2 Authorization flow. This view starts the OAuth2 authorization flow. If scopes is passed in as a GET URL parameter, it will authorize those scopes, otherwise the default scopes specified in settings. The return_url can also be specified as a GET parameter, otherwise the referer header will be checked, and if that isn't found it will return to the root path. Args: request: The Django request object. Returns: A redirect to Google OAuth2 Authorization. """ return_url = request.GET.get('return_url', None) if not return_url: return_url = request.META.get('HTTP_REFERER', '/') scopes = request.GET.getlist('scopes', django_util.oauth2_settings.scopes) # Model storage (but not session storage) requires a logged in user if django_util.oauth2_settings.storage_model: if not request.user.is_authenticated(): return redirect('{0}?next={1}'.format( settings.LOGIN_URL, parse.quote(request.get_full_path()))) # This checks for the case where we ended up here because of a logged # out user but we had credentials for it in the first place else: user_oauth = django_util.UserOAuth2(request, scopes, return_url) if user_oauth.has_credentials(): return redirect(return_url) flow = _make_flow(request=request, scopes=scopes, return_url=return_url) auth_url = flow.step1_get_authorize_url() return shortcuts.redirect(auth_url)
def oauth2_authorize(request): """ View to start the OAuth2 Authorization flow. This view starts the OAuth2 authorization flow. If scopes is passed in as a GET URL parameter, it will authorize those scopes, otherwise the default scopes specified in settings. The return_url can also be specified as a GET parameter, otherwise the referer header will be checked, and if that isn't found it will return to the root path. Args: request: The Django request object. Returns: A redirect to Google OAuth2 Authorization. """ return_url = request.GET.get('return_url', None) if not return_url: return_url = request.META.get('HTTP_REFERER', '/') scopes = request.GET.getlist('scopes', django_util.oauth2_settings.scopes) # Model storage (but not session storage) requires a logged in user if django_util.oauth2_settings.storage_model: if not request.user.is_authenticated(): return redirect('{0}?next={1}'.format( settings.LOGIN_URL, parse.quote(request.get_full_path()))) # This checks for the case where we ended up here because of a logged # out user but we had credentials for it in the first place else: user_oauth = django_util.UserOAuth2(request, scopes, return_url) if user_oauth.has_credentials(): return redirect(return_url) flow = _make_flow(request=request, scopes=scopes, return_url=return_url) auth_url = flow.step1_get_authorize_url() return shortcuts.redirect(auth_url)
[ "View", "to", "start", "the", "OAuth2", "Authorization", "flow", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/django_util/views.py#L159-L193
[ "def", "oauth2_authorize", "(", "request", ")", ":", "return_url", "=", "request", ".", "GET", ".", "get", "(", "'return_url'", ",", "None", ")", "if", "not", "return_url", ":", "return_url", "=", "request", ".", "META", ".", "get", "(", "'HTTP_REFERER'", ",", "'/'", ")", "scopes", "=", "request", ".", "GET", ".", "getlist", "(", "'scopes'", ",", "django_util", ".", "oauth2_settings", ".", "scopes", ")", "# Model storage (but not session storage) requires a logged in user", "if", "django_util", ".", "oauth2_settings", ".", "storage_model", ":", "if", "not", "request", ".", "user", ".", "is_authenticated", "(", ")", ":", "return", "redirect", "(", "'{0}?next={1}'", ".", "format", "(", "settings", ".", "LOGIN_URL", ",", "parse", ".", "quote", "(", "request", ".", "get_full_path", "(", ")", ")", ")", ")", "# This checks for the case where we ended up here because of a logged", "# out user but we had credentials for it in the first place", "else", ":", "user_oauth", "=", "django_util", ".", "UserOAuth2", "(", "request", ",", "scopes", ",", "return_url", ")", "if", "user_oauth", ".", "has_credentials", "(", ")", ":", "return", "redirect", "(", "return_url", ")", "flow", "=", "_make_flow", "(", "request", "=", "request", ",", "scopes", "=", "scopes", ",", "return_url", "=", "return_url", ")", "auth_url", "=", "flow", ".", "step1_get_authorize_url", "(", ")", "return", "shortcuts", ".", "redirect", "(", "auth_url", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
Storage.locked_get
Retrieve Credential from file. Returns: oauth2client.client.Credentials Raises: IOError if the file is a symbolic link.
oauth2client/file.py
def locked_get(self): """Retrieve Credential from file. Returns: oauth2client.client.Credentials Raises: IOError if the file is a symbolic link. """ credentials = None _helpers.validate_file(self._filename) try: f = open(self._filename, 'rb') content = f.read() f.close() except IOError: return credentials try: credentials = client.Credentials.new_from_json(content) credentials.set_store(self) except ValueError: pass return credentials
def locked_get(self): """Retrieve Credential from file. Returns: oauth2client.client.Credentials Raises: IOError if the file is a symbolic link. """ credentials = None _helpers.validate_file(self._filename) try: f = open(self._filename, 'rb') content = f.read() f.close() except IOError: return credentials try: credentials = client.Credentials.new_from_json(content) credentials.set_store(self) except ValueError: pass return credentials
[ "Retrieve", "Credential", "from", "file", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/file.py#L35-L59
[ "def", "locked_get", "(", "self", ")", ":", "credentials", "=", "None", "_helpers", ".", "validate_file", "(", "self", ".", "_filename", ")", "try", ":", "f", "=", "open", "(", "self", ".", "_filename", ",", "'rb'", ")", "content", "=", "f", ".", "read", "(", ")", "f", ".", "close", "(", ")", "except", "IOError", ":", "return", "credentials", "try", ":", "credentials", "=", "client", ".", "Credentials", ".", "new_from_json", "(", "content", ")", "credentials", ".", "set_store", "(", "self", ")", "except", "ValueError", ":", "pass", "return", "credentials" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
Storage._create_file_if_needed
Create an empty file if necessary. This method will not initialize the file. Instead it implements a simple version of "touch" to ensure the file has been created.
oauth2client/file.py
def _create_file_if_needed(self): """Create an empty file if necessary. This method will not initialize the file. Instead it implements a simple version of "touch" to ensure the file has been created. """ if not os.path.exists(self._filename): old_umask = os.umask(0o177) try: open(self._filename, 'a+b').close() finally: os.umask(old_umask)
def _create_file_if_needed(self): """Create an empty file if necessary. This method will not initialize the file. Instead it implements a simple version of "touch" to ensure the file has been created. """ if not os.path.exists(self._filename): old_umask = os.umask(0o177) try: open(self._filename, 'a+b').close() finally: os.umask(old_umask)
[ "Create", "an", "empty", "file", "if", "necessary", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/file.py#L61-L72
[ "def", "_create_file_if_needed", "(", "self", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "_filename", ")", ":", "old_umask", "=", "os", ".", "umask", "(", "0o177", ")", "try", ":", "open", "(", "self", ".", "_filename", ",", "'a+b'", ")", ".", "close", "(", ")", "finally", ":", "os", ".", "umask", "(", "old_umask", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
Storage.locked_put
Write Credentials to file. Args: credentials: Credentials, the credentials to store. Raises: IOError if the file is a symbolic link.
oauth2client/file.py
def locked_put(self, credentials): """Write Credentials to file. Args: credentials: Credentials, the credentials to store. Raises: IOError if the file is a symbolic link. """ self._create_file_if_needed() _helpers.validate_file(self._filename) f = open(self._filename, 'w') f.write(credentials.to_json()) f.close()
def locked_put(self, credentials): """Write Credentials to file. Args: credentials: Credentials, the credentials to store. Raises: IOError if the file is a symbolic link. """ self._create_file_if_needed() _helpers.validate_file(self._filename) f = open(self._filename, 'w') f.write(credentials.to_json()) f.close()
[ "Write", "Credentials", "to", "file", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/file.py#L74-L87
[ "def", "locked_put", "(", "self", ",", "credentials", ")", ":", "self", ".", "_create_file_if_needed", "(", ")", "_helpers", ".", "validate_file", "(", "self", ".", "_filename", ")", "f", "=", "open", "(", "self", ".", "_filename", ",", "'w'", ")", "f", ".", "write", "(", "credentials", ".", "to_json", "(", ")", ")", "f", ".", "close", "(", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
CredentialsField.to_python
Overrides ``models.Field`` method. This is used to convert bytes (from serialization etc) to an instance of this class
oauth2client/contrib/django_util/models.py
def to_python(self, value): """Overrides ``models.Field`` method. This is used to convert bytes (from serialization etc) to an instance of this class""" if value is None: return None elif isinstance(value, oauth2client.client.Credentials): return value else: try: return jsonpickle.decode( base64.b64decode(encoding.smart_bytes(value)).decode()) except ValueError: return pickle.loads( base64.b64decode(encoding.smart_bytes(value)))
def to_python(self, value): """Overrides ``models.Field`` method. This is used to convert bytes (from serialization etc) to an instance of this class""" if value is None: return None elif isinstance(value, oauth2client.client.Credentials): return value else: try: return jsonpickle.decode( base64.b64decode(encoding.smart_bytes(value)).decode()) except ValueError: return pickle.loads( base64.b64decode(encoding.smart_bytes(value)))
[ "Overrides", "models", ".", "Field", "method", ".", "This", "is", "used", "to", "convert", "bytes", "(", "from", "serialization", "etc", ")", "to", "an", "instance", "of", "this", "class" ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/django_util/models.py#L44-L57
[ "def", "to_python", "(", "self", ",", "value", ")", ":", "if", "value", "is", "None", ":", "return", "None", "elif", "isinstance", "(", "value", ",", "oauth2client", ".", "client", ".", "Credentials", ")", ":", "return", "value", "else", ":", "try", ":", "return", "jsonpickle", ".", "decode", "(", "base64", ".", "b64decode", "(", "encoding", ".", "smart_bytes", "(", "value", ")", ")", ".", "decode", "(", ")", ")", "except", "ValueError", ":", "return", "pickle", ".", "loads", "(", "base64", ".", "b64decode", "(", "encoding", ".", "smart_bytes", "(", "value", ")", ")", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
CredentialsField.get_prep_value
Overrides ``models.Field`` method. This is used to convert the value from an instances of this class to bytes that can be inserted into the database.
oauth2client/contrib/django_util/models.py
def get_prep_value(self, value): """Overrides ``models.Field`` method. This is used to convert the value from an instances of this class to bytes that can be inserted into the database. """ if value is None: return None else: return encoding.smart_text( base64.b64encode(jsonpickle.encode(value).encode()))
def get_prep_value(self, value): """Overrides ``models.Field`` method. This is used to convert the value from an instances of this class to bytes that can be inserted into the database. """ if value is None: return None else: return encoding.smart_text( base64.b64encode(jsonpickle.encode(value).encode()))
[ "Overrides", "models", ".", "Field", "method", ".", "This", "is", "used", "to", "convert", "the", "value", "from", "an", "instances", "of", "this", "class", "to", "bytes", "that", "can", "be", "inserted", "into", "the", "database", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/django_util/models.py#L59-L68
[ "def", "get_prep_value", "(", "self", ",", "value", ")", ":", "if", "value", "is", "None", ":", "return", "None", "else", ":", "return", "encoding", ".", "smart_text", "(", "base64", ".", "b64encode", "(", "jsonpickle", ".", "encode", "(", "value", ")", ".", "encode", "(", ")", ")", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
CredentialsField.value_to_string
Convert the field value from the provided model to a string. Used during model serialization. Args: obj: db.Model, model object Returns: string, the serialized field value
oauth2client/contrib/django_util/models.py
def value_to_string(self, obj): """Convert the field value from the provided model to a string. Used during model serialization. Args: obj: db.Model, model object Returns: string, the serialized field value """ value = self._get_val_from_obj(obj) return self.get_prep_value(value)
def value_to_string(self, obj): """Convert the field value from the provided model to a string. Used during model serialization. Args: obj: db.Model, model object Returns: string, the serialized field value """ value = self._get_val_from_obj(obj) return self.get_prep_value(value)
[ "Convert", "the", "field", "value", "from", "the", "provided", "model", "to", "a", "string", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/django_util/models.py#L70-L82
[ "def", "value_to_string", "(", "self", ",", "obj", ")", ":", "value", "=", "self", ".", "_get_val_from_obj", "(", "obj", ")", "return", "self", ".", "get_prep_value", "(", "value", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
make_signed_jwt
Make a signed JWT. See http://self-issued.info/docs/draft-jones-json-web-token.html. Args: signer: crypt.Signer, Cryptographic signer. payload: dict, Dictionary of data to convert to JSON and then sign. key_id: string, (Optional) Key ID header. Returns: string, The JWT for the payload.
oauth2client/crypt.py
def make_signed_jwt(signer, payload, key_id=None): """Make a signed JWT. See http://self-issued.info/docs/draft-jones-json-web-token.html. Args: signer: crypt.Signer, Cryptographic signer. payload: dict, Dictionary of data to convert to JSON and then sign. key_id: string, (Optional) Key ID header. Returns: string, The JWT for the payload. """ header = {'typ': 'JWT', 'alg': 'RS256'} if key_id is not None: header['kid'] = key_id segments = [ _helpers._urlsafe_b64encode(_helpers._json_encode(header)), _helpers._urlsafe_b64encode(_helpers._json_encode(payload)), ] signing_input = b'.'.join(segments) signature = signer.sign(signing_input) segments.append(_helpers._urlsafe_b64encode(signature)) logger.debug(str(segments)) return b'.'.join(segments)
def make_signed_jwt(signer, payload, key_id=None): """Make a signed JWT. See http://self-issued.info/docs/draft-jones-json-web-token.html. Args: signer: crypt.Signer, Cryptographic signer. payload: dict, Dictionary of data to convert to JSON and then sign. key_id: string, (Optional) Key ID header. Returns: string, The JWT for the payload. """ header = {'typ': 'JWT', 'alg': 'RS256'} if key_id is not None: header['kid'] = key_id segments = [ _helpers._urlsafe_b64encode(_helpers._json_encode(header)), _helpers._urlsafe_b64encode(_helpers._json_encode(payload)), ] signing_input = b'.'.join(segments) signature = signer.sign(signing_input) segments.append(_helpers._urlsafe_b64encode(signature)) logger.debug(str(segments)) return b'.'.join(segments)
[ "Make", "a", "signed", "JWT", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/crypt.py#L74-L102
[ "def", "make_signed_jwt", "(", "signer", ",", "payload", ",", "key_id", "=", "None", ")", ":", "header", "=", "{", "'typ'", ":", "'JWT'", ",", "'alg'", ":", "'RS256'", "}", "if", "key_id", "is", "not", "None", ":", "header", "[", "'kid'", "]", "=", "key_id", "segments", "=", "[", "_helpers", ".", "_urlsafe_b64encode", "(", "_helpers", ".", "_json_encode", "(", "header", ")", ")", ",", "_helpers", ".", "_urlsafe_b64encode", "(", "_helpers", ".", "_json_encode", "(", "payload", ")", ")", ",", "]", "signing_input", "=", "b'.'", ".", "join", "(", "segments", ")", "signature", "=", "signer", ".", "sign", "(", "signing_input", ")", "segments", ".", "append", "(", "_helpers", ".", "_urlsafe_b64encode", "(", "signature", ")", ")", "logger", ".", "debug", "(", "str", "(", "segments", ")", ")", "return", "b'.'", ".", "join", "(", "segments", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9
valid
_verify_signature
Verifies signed content using a list of certificates. Args: message: string or bytes, The message to verify. signature: string or bytes, The signature on the message. certs: iterable, certificates in PEM format. Raises: AppIdentityError: If none of the certificates can verify the message against the signature.
oauth2client/crypt.py
def _verify_signature(message, signature, certs): """Verifies signed content using a list of certificates. Args: message: string or bytes, The message to verify. signature: string or bytes, The signature on the message. certs: iterable, certificates in PEM format. Raises: AppIdentityError: If none of the certificates can verify the message against the signature. """ for pem in certs: verifier = Verifier.from_string(pem, is_x509_cert=True) if verifier.verify(message, signature): return # If we have not returned, no certificate confirms the signature. raise AppIdentityError('Invalid token signature')
def _verify_signature(message, signature, certs): """Verifies signed content using a list of certificates. Args: message: string or bytes, The message to verify. signature: string or bytes, The signature on the message. certs: iterable, certificates in PEM format. Raises: AppIdentityError: If none of the certificates can verify the message against the signature. """ for pem in certs: verifier = Verifier.from_string(pem, is_x509_cert=True) if verifier.verify(message, signature): return # If we have not returned, no certificate confirms the signature. raise AppIdentityError('Invalid token signature')
[ "Verifies", "signed", "content", "using", "a", "list", "of", "certificates", "." ]
googleapis/oauth2client
python
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/crypt.py#L105-L123
[ "def", "_verify_signature", "(", "message", ",", "signature", ",", "certs", ")", ":", "for", "pem", "in", "certs", ":", "verifier", "=", "Verifier", ".", "from_string", "(", "pem", ",", "is_x509_cert", "=", "True", ")", "if", "verifier", ".", "verify", "(", "message", ",", "signature", ")", ":", "return", "# If we have not returned, no certificate confirms the signature.", "raise", "AppIdentityError", "(", "'Invalid token signature'", ")" ]
50d20532a748f18e53f7d24ccbe6647132c979a9