INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Removes itself from the cache
def delete(self): """Removes itself from the cache Note: This is required by the oauthlib """ log.debug( "Deleting grant %s for client %s" % (self.code, self.client_id) ) self._cache.delete(self.key) return None
Determines which method of getting the query object for use
def query(self): """Determines which method of getting the query object for use""" if hasattr(self.model, 'query'): return self.model.query else: return self.session.query(self.model)
Returns the User object
def get(self, username, password, *args, **kwargs): """Returns the User object Returns None if the user isn't found or the passwords don't match :param username: username of the user :param password: password of the user """ user = self.query.filter_by(username=username).first() if user and user.check_password(password): return user return None
returns a Token object with the given access token or refresh token
def get(self, access_token=None, refresh_token=None): """returns a Token object with the given access token or refresh token :param access_token: User's access token :param refresh_token: User's refresh token """ if access_token: return self.query.filter_by(access_token=access_token).first() elif refresh_token: return self.query.filter_by(refresh_token=refresh_token).first() return None
Creates a Token object and removes all expired tokens that belong to the user
def set(self, token, request, *args, **kwargs): """Creates a Token object and removes all expired tokens that belong to the user :param token: token object :param request: OAuthlib request object """ if hasattr(request, 'user') and request.user: user = request.user elif self.current_user: # for implicit token user = self.current_user() client = request.client tokens = self.query.filter_by( client_id=client.client_id, user_id=user.id).all() if tokens: for tk in tokens: self.session.delete(tk) self.session.commit() expires_in = token.get('expires_in') expires = datetime.utcnow() + timedelta(seconds=expires_in) tok = self.model(**token) tok.expires = expires tok.client_id = client.client_id tok.user_id = user.id self.session.add(tok) self.session.commit() return tok
Creates Grant object with the given params
def set(self, client_id, code, request, *args, **kwargs): """Creates Grant object with the given params :param client_id: ID of the client :param code: :param request: OAuthlib request object """ expires = datetime.utcnow() + timedelta(seconds=100) grant = self.model( client_id=request.client.client_id, code=code['code'], redirect_uri=request.redirect_uri, scope=' '.join(request.scopes), user=self.current_user(), expires=expires ) self.session.add(grant) self.session.commit()
Get the Grant object with the given client ID and code
def get(self, client_id, code): """Get the Grant object with the given client ID and code :param client_id: ID of the client :param code: """ return self.query.filter_by(client_id=client_id, code=code).first()
Parse the response returned by: meth: OAuthRemoteApp. http_request.
def parse_response(resp, content, strict=False, content_type=None): """Parse the response returned by :meth:`OAuthRemoteApp.http_request`. :param resp: response of http_request :param content: content of the response :param strict: strict mode for form urlencoded content :param content_type: assign a content type manually """ if not content_type: content_type = resp.headers.get('content-type', 'application/json') ct, options = parse_options_header(content_type) if ct in ('application/json', 'text/javascript'): if not content: return {} return json.loads(content) if ct in ('application/xml', 'text/xml'): return get_etree().fromstring(content) if ct != 'application/x-www-form-urlencoded' and strict: return content charset = options.get('charset', 'utf-8') return url_decode(content, charset=charset).to_dict()
Make request parameters right.
def prepare_request(uri, headers=None, data=None, method=None): """Make request parameters right.""" if headers is None: headers = {} if data and not method: method = 'POST' elif not method: method = 'GET' if method == 'GET' and data: uri = add_params_to_uri(uri, data) data = None return uri, headers, data, method
Init app with Flask instance.
def init_app(self, app): """Init app with Flask instance. You can also pass the instance of Flask later:: oauth = OAuth() oauth.init_app(app) """ self.app = app app.extensions = getattr(app, 'extensions', {}) app.extensions[self.state_key] = self
Registers a new remote application.
def remote_app(self, name, register=True, **kwargs): """Registers a new remote application. :param name: the name of the remote application :param register: whether the remote app will be registered Find more parameters from :class:`OAuthRemoteApp`. """ remote = OAuthRemoteApp(self, name, **kwargs) if register: assert name not in self.remote_apps self.remote_apps[name] = remote return remote
Sends a request to the remote server with OAuth tokens attached.
def request(self, url, data=None, headers=None, format='urlencoded', method='GET', content_type=None, token=None): """ Sends a request to the remote server with OAuth tokens attached. :param data: the data to be sent to the server. :param headers: an optional dictionary of headers. :param format: the format for the `data`. Can be `urlencoded` for URL encoded data or `json` for JSON. :param method: the HTTP request method to use. :param content_type: an optional content type. If a content type is provided, the data is passed as it, and the `format` is ignored. :param token: an optional token to pass, if it is None, token will be generated by tokengetter. """ headers = dict(headers or {}) if token is None: token = self.get_request_token() client = self.make_client(token) url = self.expand_url(url) if method == 'GET': assert format == 'urlencoded' if data: url = add_params_to_uri(url, data) data = None else: if content_type is None: data, content_type = encode_request_data(data, format) if content_type is not None: headers['Content-Type'] = content_type if self.request_token_url: # oauth1 uri, headers, body = client.sign( url, http_method=method, body=data, headers=headers ) else: # oauth2 uri, headers, body = client.add_token( url, http_method=method, body=data, headers=headers ) if hasattr(self, 'pre_request'): # This is designed for some rubbish services like weibo. # Since they don't follow the standards, we need to # change the uri, headers, or body. uri, headers, body = self.pre_request(uri, headers, body) if body: data = to_bytes(body, self.encoding) else: data = None resp, content = self.http_request( uri, headers, data=to_bytes(body, self.encoding), method=method ) return OAuthResponse(resp, content, self.content_type)
Returns a redirect response to the remote authorization URL with the signed callback given.
def authorize(self, callback=None, state=None, **kwargs): """ Returns a redirect response to the remote authorization URL with the signed callback given. :param callback: a redirect url for the callback :param state: an optional value to embed in the OAuth request. Use this if you want to pass around application state (e.g. CSRF tokens). :param kwargs: add optional key/value pairs to the query string """ params = dict(self.request_token_params) or {} params.update(**kwargs) if self.request_token_url: token = self.generate_request_token(callback)[0] url = '%s?oauth_token=%s' % ( self.expand_url(self.authorize_url), url_quote(token) ) if params: url += '&' + url_encode(params) else: assert callback is not None, 'Callback is required for OAuth2' client = self.make_client() if 'scope' in params: scope = params.pop('scope') else: scope = None if isinstance(scope, str): # oauthlib need unicode scope = _encode(scope, self.encoding) if 'state' in params: if not state: state = params.pop('state') else: # remove state in params params.pop('state') if callable(state): # state can be function for generate a random string state = state() session['%s_oauthredir' % self.name] = callback url = client.prepare_request_uri( self.expand_url(self.authorize_url), redirect_uri=callback, scope=scope, state=state, **params ) return redirect(url)
Handles an oauth1 authorization response.
def handle_oauth1_response(self, args): """Handles an oauth1 authorization response.""" client = self.make_client() client.verifier = args.get('oauth_verifier') tup = session.get('%s_oauthtok' % self.name) if not tup: raise OAuthException( 'Token not found, maybe you disabled cookie', type='token_not_found' ) client.resource_owner_key = tup[0] client.resource_owner_secret = tup[1] uri, headers, data = client.sign( self.expand_url(self.access_token_url), _encode(self.access_token_method) ) headers.update(self._access_token_headers) resp, content = self.http_request( uri, headers, to_bytes(data, self.encoding), method=self.access_token_method ) data = parse_response(resp, content) if resp.code not in (200, 201): raise OAuthException( 'Invalid response from %s' % self.name, type='invalid_response', data=data ) return data
Handles an oauth2 authorization response.
def handle_oauth2_response(self, args): """Handles an oauth2 authorization response.""" client = self.make_client() remote_args = { 'code': args.get('code'), 'client_secret': self.consumer_secret, 'redirect_uri': session.get('%s_oauthredir' % self.name) } log.debug('Prepare oauth2 remote args %r', remote_args) remote_args.update(self.access_token_params) headers = copy(self._access_token_headers) if self.access_token_method == 'POST': headers.update({'Content-Type': 'application/x-www-form-urlencoded'}) body = client.prepare_request_body(**remote_args) resp, content = self.http_request( self.expand_url(self.access_token_url), headers=headers, data=to_bytes(body, self.encoding), method=self.access_token_method, ) elif self.access_token_method == 'GET': qs = client.prepare_request_body(**remote_args) url = self.expand_url(self.access_token_url) url += ('?' in url and '&' or '?') + qs resp, content = self.http_request( url, headers=headers, method=self.access_token_method, ) else: raise OAuthException( 'Unsupported access_token_method: %s' % self.access_token_method ) data = parse_response(resp, content, content_type=self.content_type) if resp.code not in (200, 201): raise OAuthException( 'Invalid response from %s' % self.name, type='invalid_response', data=data ) return data
Handles authorization response smartly.
def authorized_response(self, args=None): """Handles authorization response smartly.""" if args is None: args = request.args if 'oauth_verifier' in args: data = self.handle_oauth1_response(args) elif 'code' in args: data = self.handle_oauth2_response(args) else: data = self.handle_unknown_response() # free request token session.pop('%s_oauthtok' % self.name, None) session.pop('%s_oauthredir' % self.name, None) return data
Handles an OAuth callback.
def authorized_handler(self, f): """Handles an OAuth callback. .. versionchanged:: 0.7 @authorized_handler is deprecated in favor of authorized_response. """ @wraps(f) def decorated(*args, **kwargs): log.warn( '@authorized_handler is deprecated in favor of ' 'authorized_response' ) data = self.authorized_response() return f(*((data,) + args), **kwargs) return decorated
Creates a hashable object for given token then we could use it as a dictionary key.
def _hash_token(application, token): """Creates a hashable object for given token then we could use it as a dictionary key. """ if isinstance(token, dict): hashed_token = tuple(sorted(token.items())) elif isinstance(token, tuple): hashed_token = token else: raise TypeError('%r is unknown type of token' % token) return (application.__class__.__name__, application.name, hashed_token)
The lazy - created OAuth session with the return value of: meth: tokengetter.
def client(self): """The lazy-created OAuth session with the return value of :meth:`tokengetter`. :returns: The OAuth session instance or ``None`` while token missing. """ token = self.obtain_token() if token is None: raise AccessTokenNotFound return self._make_client_with_token(token)
Uses cached client or create new one with specific token.
def _make_client_with_token(self, token): """Uses cached client or create new one with specific token.""" cached_clients = getattr(self, 'clients', None) hashed_token = _hash_token(self, token) if cached_clients and hashed_token in cached_clients: return cached_clients[hashed_token] client = self.make_client(token) # implemented in subclasses if cached_clients: cached_clients[hashed_token] = client return client
Creates a client with specific access token pair.
def make_client(self, token): """Creates a client with specific access token pair. :param token: a tuple of access token pair ``(token, token_secret)`` or a dictionary of access token response. :returns: a :class:`requests_oauthlib.oauth1_session.OAuth1Session` object. """ if isinstance(token, dict): access_token = token['oauth_token'] access_token_secret = token['oauth_token_secret'] else: access_token, access_token_secret = token return self.make_oauth_session( resource_owner_key=access_token, resource_owner_secret=access_token_secret)
Creates a context to enable the oauthlib environment variable in order to debug with insecure transport.
def insecure_transport(self): """Creates a context to enable the oauthlib environment variable in order to debug with insecure transport. """ origin = os.environ.get('OAUTHLIB_INSECURE_TRANSPORT') if current_app.debug or current_app.testing: try: os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' yield finally: if origin: os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = origin else: os.environ.pop('OAUTHLIB_INSECURE_TRANSPORT', None) else: if origin: warnings.warn( 'OAUTHLIB_INSECURE_TRANSPORT has been found in os.environ ' 'but the app is not running in debug mode or testing mode.' ' It may put you in danger of the Man-in-the-middle attack' ' while using OAuth 2.', RuntimeWarning) yield
All in one endpoints. This property is created automaticly if you have implemented all the getters and setters.
def server(self): """ All in one endpoints. This property is created automaticly if you have implemented all the getters and setters. """ if hasattr(self, '_validator'): return Server(self._validator) if hasattr(self, '_clientgetter') and \ hasattr(self, '_tokengetter') and \ hasattr(self, '_tokensetter') and \ hasattr(self, '_noncegetter') and \ hasattr(self, '_noncesetter') and \ hasattr(self, '_grantgetter') and \ hasattr(self, '_grantsetter') and \ hasattr(self, '_verifiergetter') and \ hasattr(self, '_verifiersetter'): validator = OAuth1RequestValidator( clientgetter=self._clientgetter, tokengetter=self._tokengetter, tokensetter=self._tokensetter, grantgetter=self._grantgetter, grantsetter=self._grantsetter, noncegetter=self._noncegetter, noncesetter=self._noncesetter, verifiergetter=self._verifiergetter, verifiersetter=self._verifiersetter, config=self.app.config, ) self._validator = validator server = Server(validator) if self.app.testing: # It will always be false, since the redirect_uri # didn't match when doing the testing server._check_signature = lambda *args, **kwargs: True return server raise RuntimeError( 'application not bound to required getters and setters' )
Authorization handler decorator.
def authorize_handler(self, f): """Authorization handler decorator. This decorator will sort the parameters and headers out, and pre validate everything:: @app.route('/oauth/authorize', methods=['GET', 'POST']) @oauth.authorize_handler def authorize(*args, **kwargs): if request.method == 'GET': # render a page for user to confirm the authorization return render_template('oauthorize.html') confirm = request.form.get('confirm', 'no') return confirm == 'yes' """ @wraps(f) def decorated(*args, **kwargs): if request.method == 'POST': if not f(*args, **kwargs): uri = add_params_to_uri( self.error_uri, [('error', 'denied')] ) return redirect(uri) return self.confirm_authorization_request() server = self.server uri, http_method, body, headers = extract_params() try: realms, credentials = server.get_realms_and_credentials( uri, http_method=http_method, body=body, headers=headers ) kwargs['realms'] = realms kwargs.update(credentials) return f(*args, **kwargs) except errors.OAuth1Error as e: return redirect(e.in_uri(self.error_uri)) except errors.InvalidClientError as e: return redirect(e.in_uri(self.error_uri)) return decorated
When consumer confirm the authrozation.
def confirm_authorization_request(self): """When consumer confirm the authrozation.""" server = self.server uri, http_method, body, headers = extract_params() try: realms, credentials = server.get_realms_and_credentials( uri, http_method=http_method, body=body, headers=headers ) ret = server.create_authorization_response( uri, http_method, body, headers, realms, credentials ) log.debug('Authorization successful.') return create_response(*ret) except errors.OAuth1Error as e: return redirect(e.in_uri(self.error_uri)) except errors.InvalidClientError as e: return redirect(e.in_uri(self.error_uri))
Request token handler decorator.
def request_token_handler(self, f): """Request token handler decorator. The decorated function should return an dictionary or None as the extra credentials for creating the token response. If you don't need to add any extra credentials, it could be as simple as:: @app.route('/oauth/request_token') @oauth.request_token_handler def request_token(): return {} """ @wraps(f) def decorated(*args, **kwargs): server = self.server uri, http_method, body, headers = extract_params() credentials = f(*args, **kwargs) try: ret = server.create_request_token_response( uri, http_method, body, headers, credentials) return create_response(*ret) except errors.OAuth1Error as e: return _error_response(e) return decorated
Protect resource with specified scopes.
def require_oauth(self, *realms, **kwargs): """Protect resource with specified scopes.""" def wrapper(f): @wraps(f) def decorated(*args, **kwargs): for func in self._before_request_funcs: func() if hasattr(request, 'oauth') and request.oauth: return f(*args, **kwargs) server = self.server uri, http_method, body, headers = extract_params() try: valid, req = server.validate_protected_resource_request( uri, http_method, body, headers, realms ) except Exception as e: log.warn('Exception: %r', e) e.urlencoded = urlencode([('error', 'unknown')]) e.status_code = 400 return _error_response(e) for func in self._after_request_funcs: valid, req = func(valid, req) if not valid: return abort(401) # alias user for convenience req.user = req.access_token.user request.oauth = req return f(*args, **kwargs) return decorated return wrapper
Get client secret.
def get_client_secret(self, client_key, request): """Get client secret. The client object must has ``client_secret`` attribute. """ log.debug('Get client secret of %r', client_key) if not request.client: request.client = self._clientgetter(client_key=client_key) if request.client: return request.client.client_secret return None
Get request token secret.
def get_request_token_secret(self, client_key, token, request): """Get request token secret. The request token object should a ``secret`` attribute. """ log.debug('Get request token secret of %r for %r', token, client_key) tok = request.request_token or self._grantgetter(token=token) if tok and tok.client_key == client_key: request.request_token = tok return tok.secret return None
Get access token secret.
def get_access_token_secret(self, client_key, token, request): """Get access token secret. The access token object should a ``secret`` attribute. """ log.debug('Get access token secret of %r for %r', token, client_key) tok = request.access_token or self._tokengetter( client_key=client_key, token=token, ) if tok: request.access_token = tok return tok.secret return None
Default realms of the client.
def get_default_realms(self, client_key, request): """Default realms of the client.""" log.debug('Get realms for %r', client_key) if not request.client: request.client = self._clientgetter(client_key=client_key) client = request.client if hasattr(client, 'default_realms'): return client.default_realms return []
Realms for this request token.
def get_realms(self, token, request): """Realms for this request token.""" log.debug('Get realms of %r', token) tok = request.request_token or self._grantgetter(token=token) if not tok: return [] request.request_token = tok if hasattr(tok, 'realms'): return tok.realms or [] return []
Redirect uri for this request token.
def get_redirect_uri(self, token, request): """Redirect uri for this request token.""" log.debug('Get redirect uri of %r', token) tok = request.request_token or self._grantgetter(token=token) return tok.redirect_uri
Retrieves a previously stored client provided RSA key.
def get_rsa_key(self, client_key, request): """Retrieves a previously stored client provided RSA key.""" if not request.client: request.client = self._clientgetter(client_key=client_key) if hasattr(request.client, 'rsa_key'): return request.client.rsa_key return None
Validates that supplied client key.
def validate_client_key(self, client_key, request): """Validates that supplied client key.""" log.debug('Validate client key for %r', client_key) if not request.client: request.client = self._clientgetter(client_key=client_key) if request.client: return True return False
Validates request token is available for client.
def validate_request_token(self, client_key, token, request): """Validates request token is available for client.""" log.debug('Validate request token %r for %r', token, client_key) tok = request.request_token or self._grantgetter(token=token) if tok and tok.client_key == client_key: request.request_token = tok return True return False
Validates access token is available for client.
def validate_access_token(self, client_key, token, request): """Validates access token is available for client.""" log.debug('Validate access token %r for %r', token, client_key) tok = request.access_token or self._tokengetter( client_key=client_key, token=token, ) if tok: request.access_token = tok return True return False
Validate the timestamp and nonce is used or not.
def validate_timestamp_and_nonce(self, client_key, timestamp, nonce, request, request_token=None, access_token=None): """Validate the timestamp and nonce is used or not.""" log.debug('Validate timestamp and nonce %r', client_key) nonce_exists = self._noncegetter( client_key=client_key, timestamp=timestamp, nonce=nonce, request_token=request_token, access_token=access_token ) if nonce_exists: return False self._noncesetter( client_key=client_key, timestamp=timestamp, nonce=nonce, request_token=request_token, access_token=access_token ) return True
Validate if the redirect_uri is allowed by the client.
def validate_redirect_uri(self, client_key, redirect_uri, request): """Validate if the redirect_uri is allowed by the client.""" log.debug('Validate redirect_uri %r for %r', redirect_uri, client_key) if not request.client: request.client = self._clientgetter(client_key=client_key) if not request.client: return False if not request.client.redirect_uris and redirect_uri is None: return True request.redirect_uri = redirect_uri return redirect_uri in request.client.redirect_uris
Check if the token has permission on those realms.
def validate_realms(self, client_key, token, request, uri=None, realms=None): """Check if the token has permission on those realms.""" log.debug('Validate realms %r for %r', realms, client_key) if request.access_token: tok = request.access_token else: tok = self._tokengetter(client_key=client_key, token=token) request.access_token = tok if not tok: return False return set(tok.realms).issuperset(set(realms))
Validate verifier exists.
def validate_verifier(self, client_key, token, verifier, request): """Validate verifier exists.""" log.debug('Validate verifier %r for %r', verifier, client_key) data = self._verifiergetter(verifier=verifier, token=token) if not data: return False if not hasattr(data, 'user'): log.debug('Verifier should has user attribute') return False request.user = data.user if hasattr(data, 'client_key'): return data.client_key == client_key return True
Verify if the request token is existed.
def verify_request_token(self, token, request): """Verify if the request token is existed.""" log.debug('Verify request token %r', token) tok = request.request_token or self._grantgetter(token=token) if tok: request.request_token = tok return True return False
Verify if the realms match the requested realms.
def verify_realms(self, token, realms, request): """Verify if the realms match the requested realms.""" log.debug('Verify realms %r', realms) tok = request.request_token or self._grantgetter(token=token) if not tok: return False request.request_token = tok if not hasattr(tok, 'realms'): # realms not enabled return True return set(tok.realms) == set(realms)
Save access token to database.
def save_access_token(self, token, request): """Save access token to database. A tokensetter is required, which accepts a token and request parameters:: def tokensetter(token, request): access_token = Token( client=request.client, user=request.user, token=token['oauth_token'], secret=token['oauth_token_secret'], realms=token['oauth_authorized_realms'], ) return access_token.save() """ log.debug('Save access token %r', token) self._tokensetter(token, request)
Save request token to database.
def save_request_token(self, token, request): """Save request token to database. A grantsetter is required, which accepts a token and request parameters:: def grantsetter(token, request): grant = Grant( token=token['oauth_token'], secret=token['oauth_token_secret'], client=request.client, redirect_uri=oauth.redirect_uri, realms=request.realms, ) return grant.save() """ log.debug('Save request token %r', token) self._grantsetter(token, request)
Save verifier to database.
def save_verifier(self, token, verifier, request): """Save verifier to database. A verifiersetter is required. It would be better to combine request token and verifier together:: def verifiersetter(token, verifier, request): tok = Grant.query.filter_by(token=token).first() tok.verifier = verifier['oauth_verifier'] tok.user = get_current_user() return tok.save() .. admonition:: Note: A user is required on verifier, remember to attach current user to verifier. """ log.debug('Save verifier %r for %r', verifier, token) self._verifiersetter( token=token, verifier=verifier, request=request )
The error page URI.
def error_uri(self): """The error page URI. When something turns error, it will redirect to this error page. You can configure the error page URI with Flask config:: OAUTH2_PROVIDER_ERROR_URI = '/error' You can also define the error page by a named endpoint:: OAUTH2_PROVIDER_ERROR_ENDPOINT = 'oauth.error' """ error_uri = self.app.config.get('OAUTH2_PROVIDER_ERROR_URI') if error_uri: return error_uri error_endpoint = self.app.config.get('OAUTH2_PROVIDER_ERROR_ENDPOINT') if error_endpoint: return url_for(error_endpoint) return '/oauth/errors'
All in one endpoints. This property is created automaticly if you have implemented all the getters and setters.
def server(self): """ All in one endpoints. This property is created automaticly if you have implemented all the getters and setters. However, if you are not satisfied with the getter and setter, you can create a validator with :class:`OAuth2RequestValidator`:: class MyValidator(OAuth2RequestValidator): def validate_client_id(self, client_id): # do something return True And assign the validator for the provider:: oauth._validator = MyValidator() """ expires_in = self.app.config.get('OAUTH2_PROVIDER_TOKEN_EXPIRES_IN') token_generator = self.app.config.get( 'OAUTH2_PROVIDER_TOKEN_GENERATOR', None ) if token_generator and not callable(token_generator): token_generator = import_string(token_generator) refresh_token_generator = self.app.config.get( 'OAUTH2_PROVIDER_REFRESH_TOKEN_GENERATOR', None ) if refresh_token_generator and not callable(refresh_token_generator): refresh_token_generator = import_string(refresh_token_generator) if hasattr(self, '_validator'): return Server( self._validator, token_expires_in=expires_in, token_generator=token_generator, refresh_token_generator=refresh_token_generator, ) if hasattr(self, '_clientgetter') and \ hasattr(self, '_tokengetter') and \ hasattr(self, '_tokensetter') and \ hasattr(self, '_grantgetter') and \ hasattr(self, '_grantsetter'): usergetter = None if hasattr(self, '_usergetter'): usergetter = self._usergetter validator_class = self._validator_class if validator_class is None: validator_class = OAuth2RequestValidator validator = validator_class( clientgetter=self._clientgetter, tokengetter=self._tokengetter, grantgetter=self._grantgetter, usergetter=usergetter, tokensetter=self._tokensetter, grantsetter=self._grantsetter, ) self._validator = validator return Server( validator, token_expires_in=expires_in, token_generator=token_generator, refresh_token_generator=refresh_token_generator, ) raise RuntimeError('application not bound to required getters')
Authorization handler decorator.
def authorize_handler(self, f): """Authorization handler decorator. This decorator will sort the parameters and headers out, and pre validate everything:: @app.route('/oauth/authorize', methods=['GET', 'POST']) @oauth.authorize_handler def authorize(*args, **kwargs): if request.method == 'GET': # render a page for user to confirm the authorization return render_template('oauthorize.html') confirm = request.form.get('confirm', 'no') return confirm == 'yes' """ @wraps(f) def decorated(*args, **kwargs): # raise if server not implemented server = self.server uri, http_method, body, headers = extract_params() if request.method in ('GET', 'HEAD'): redirect_uri = request.args.get('redirect_uri', self.error_uri) log.debug('Found redirect_uri %s.', redirect_uri) try: ret = server.validate_authorization_request( uri, http_method, body, headers ) scopes, credentials = ret kwargs['scopes'] = scopes kwargs.update(credentials) except oauth2.FatalClientError as e: log.debug('Fatal client error %r', e, exc_info=True) return self._on_exception(e, e.in_uri(self.error_uri)) except oauth2.OAuth2Error as e: log.debug('OAuth2Error: %r', e, exc_info=True) # on auth error, we should preserve state if it's present according to RFC 6749 state = request.values.get('state') if state and not e.state: e.state = state # set e.state so e.in_uri() can add the state query parameter to redirect uri return self._on_exception(e, e.in_uri(redirect_uri)) except Exception as e: log.exception(e) return self._on_exception(e, add_params_to_uri( self.error_uri, {'error': str(e)} )) else: redirect_uri = request.values.get( 'redirect_uri', self.error_uri ) try: rv = f(*args, **kwargs) except oauth2.FatalClientError as e: log.debug('Fatal client error %r', e, exc_info=True) return self._on_exception(e, e.in_uri(self.error_uri)) except oauth2.OAuth2Error as e: log.debug('OAuth2Error: %r', e, exc_info=True) # on auth error, we should preserve state if it's present according to RFC 6749 state = request.values.get('state') if state and not e.state: e.state = state # set e.state so e.in_uri() can add the state query parameter to redirect uri return self._on_exception(e, e.in_uri(redirect_uri)) if not isinstance(rv, bool): # if is a response or redirect return rv if not rv: # denied by user e = oauth2.AccessDeniedError(state=request.values.get('state')) return self._on_exception(e, e.in_uri(redirect_uri)) return self.confirm_authorization_request() return decorated
When consumer confirm the authorization.
def confirm_authorization_request(self): """When consumer confirm the authorization.""" server = self.server scope = request.values.get('scope') or '' scopes = scope.split() credentials = dict( client_id=request.values.get('client_id'), redirect_uri=request.values.get('redirect_uri', None), response_type=request.values.get('response_type', None), state=request.values.get('state', None) ) log.debug('Fetched credentials from request %r.', credentials) redirect_uri = credentials.get('redirect_uri') log.debug('Found redirect_uri %s.', redirect_uri) uri, http_method, body, headers = extract_params() try: ret = server.create_authorization_response( uri, http_method, body, headers, scopes, credentials) log.debug('Authorization successful.') return create_response(*ret) except oauth2.FatalClientError as e: log.debug('Fatal client error %r', e, exc_info=True) return self._on_exception(e, e.in_uri(self.error_uri)) except oauth2.OAuth2Error as e: log.debug('OAuth2Error: %r', e, exc_info=True) # on auth error, we should preserve state if it's present according to RFC 6749 state = request.values.get('state') if state and not e.state: e.state = state # set e.state so e.in_uri() can add the state query parameter to redirect uri return self._on_exception(e, e.in_uri(redirect_uri or self.error_uri)) except Exception as e: log.exception(e) return self._on_exception(e, add_params_to_uri( self.error_uri, {'error': str(e)} ))
Verify current request get the oauth data.
def verify_request(self, scopes): """Verify current request, get the oauth data. If you can't use the ``require_oauth`` decorator, you can fetch the data in your request body:: def your_handler(): valid, req = oauth.verify_request(['email']) if valid: return jsonify(user=req.user) return jsonify(status='error') """ uri, http_method, body, headers = extract_params() return self.server.verify_request( uri, http_method, body, headers, scopes )
Access/ refresh token handler decorator.
def token_handler(self, f): """Access/refresh token handler decorator. The decorated function should return an dictionary or None as the extra credentials for creating the token response. You can control the access method with standard flask route mechanism. If you only allow the `POST` method:: @app.route('/oauth/token', methods=['POST']) @oauth.token_handler def access_token(): return None """ @wraps(f) def decorated(*args, **kwargs): server = self.server uri, http_method, body, headers = extract_params() credentials = f(*args, **kwargs) or {} log.debug('Fetched extra credentials, %r.', credentials) ret = server.create_token_response( uri, http_method, body, headers, credentials ) return create_response(*ret) return decorated
Access/ refresh token revoke decorator.
def revoke_handler(self, f): """Access/refresh token revoke decorator. Any return value by the decorated function will get discarded as defined in [`RFC7009`_]. You can control the access method with the standard flask routing mechanism, as per [`RFC7009`_] it is recommended to only allow the `POST` method:: @app.route('/oauth/revoke', methods=['POST']) @oauth.revoke_handler def revoke_token(): pass .. _`RFC7009`: http://tools.ietf.org/html/rfc7009 """ @wraps(f) def decorated(*args, **kwargs): server = self.server token = request.values.get('token') request.token_type_hint = request.values.get('token_type_hint') if token: request.token = token uri, http_method, body, headers = extract_params() ret = server.create_revocation_response( uri, headers=headers, body=body, http_method=http_method) return create_response(*ret) return decorated
Protect resource with specified scopes.
def require_oauth(self, *scopes): """Protect resource with specified scopes.""" def wrapper(f): @wraps(f) def decorated(*args, **kwargs): for func in self._before_request_funcs: func() if hasattr(request, 'oauth') and request.oauth: return f(*args, **kwargs) valid, req = self.verify_request(scopes) for func in self._after_request_funcs: valid, req = func(valid, req) if not valid: if self._invalid_response: return self._invalid_response(req) return abort(401) request.oauth = req return f(*args, **kwargs) return decorated return wrapper
Return client credentials based on the current request.
def _get_client_creds_from_request(self, request): """Return client credentials based on the current request. According to the rfc6749, client MAY use the HTTP Basic authentication scheme as defined in [RFC2617] to authenticate with the authorization server. The client identifier is encoded using the "application/x-www-form-urlencoded" encoding algorithm per Appendix B, and the encoded value is used as the username; the client password is encoded using the same algorithm and used as the password. The authorization server MUST support the HTTP Basic authentication scheme for authenticating clients that were issued a client password. See `Section 2.3.1`_. .. _`Section 2.3.1`: https://tools.ietf.org/html/rfc6749#section-2.3.1 """ if request.client_id is not None: return request.client_id, request.client_secret auth = request.headers.get('Authorization') # If Werkzeug successfully parsed the Authorization header, # `extract_params` helper will replace the header with a parsed dict, # otherwise, there is nothing useful in the header and we just skip it. if isinstance(auth, dict): return auth['username'], auth['password'] return None, None
Determine if client authentication is required for current request.
def client_authentication_required(self, request, *args, **kwargs): """Determine if client authentication is required for current request. According to the rfc6749, client authentication is required in the following cases: Resource Owner Password Credentials Grant: see `Section 4.3.2`_. Authorization Code Grant: see `Section 4.1.3`_. Refresh Token Grant: see `Section 6`_. .. _`Section 4.3.2`: http://tools.ietf.org/html/rfc6749#section-4.3.2 .. _`Section 4.1.3`: http://tools.ietf.org/html/rfc6749#section-4.1.3 .. _`Section 6`: http://tools.ietf.org/html/rfc6749#section-6 """ def is_confidential(client): if hasattr(client, 'is_confidential'): return client.is_confidential client_type = getattr(client, 'client_type', None) if client_type: return client_type == 'confidential' return True grant_types = ('password', 'authorization_code', 'refresh_token') client_id, _ = self._get_client_creds_from_request(request) if client_id and request.grant_type in grant_types: client = self._clientgetter(client_id) if client: return is_confidential(client) return False
Authenticate itself in other means.
def authenticate_client(self, request, *args, **kwargs): """Authenticate itself in other means. Other means means is described in `Section 3.2.1`_. .. _`Section 3.2.1`: http://tools.ietf.org/html/rfc6749#section-3.2.1 """ client_id, client_secret = self._get_client_creds_from_request(request) log.debug('Authenticate client %r', client_id) client = self._clientgetter(client_id) if not client: log.debug('Authenticate client failed, client not found.') return False request.client = client # http://tools.ietf.org/html/rfc6749#section-2 # The client MAY omit the parameter if the client secret is an empty string. if hasattr(client, 'client_secret') and client.client_secret != client_secret: log.debug('Authenticate client failed, secret not match.') return False log.debug('Authenticate client success.') return True
Authenticate a non - confidential client.
def authenticate_client_id(self, client_id, request, *args, **kwargs): """Authenticate a non-confidential client. :param client_id: Client ID of the non-confidential client :param request: The Request object passed by oauthlib """ if client_id is None: client_id, _ = self._get_client_creds_from_request(request) log.debug('Authenticate client %r.', client_id) client = request.client or self._clientgetter(client_id) if not client: log.debug('Authenticate failed, client not found.') return False # attach client on request for convenience request.client = client return True
Ensure client is authorized to redirect to the redirect_uri.
def confirm_redirect_uri(self, client_id, code, redirect_uri, client, *args, **kwargs): """Ensure client is authorized to redirect to the redirect_uri. This method is used in the authorization code grant flow. It will compare redirect_uri and the one in grant token strictly, you can add a `validate_redirect_uri` function on grant for a customized validation. """ client = client or self._clientgetter(client_id) log.debug('Confirm redirect uri for client %r and code %r.', client.client_id, code) grant = self._grantgetter(client_id=client.client_id, code=code) if not grant: log.debug('Grant not found.') return False if hasattr(grant, 'validate_redirect_uri'): return grant.validate_redirect_uri(redirect_uri) log.debug('Compare redirect uri for grant %r and %r.', grant.redirect_uri, redirect_uri) testing = 'OAUTHLIB_INSECURE_TRANSPORT' in os.environ if testing and redirect_uri is None: # For testing return True return grant.redirect_uri == redirect_uri
Get the list of scopes associated with the refresh token.
def get_original_scopes(self, refresh_token, request, *args, **kwargs): """Get the list of scopes associated with the refresh token. This method is used in the refresh token grant flow. We return the scope of the token to be refreshed so it can be applied to the new access token. """ log.debug('Obtaining scope of refreshed token.') tok = self._tokengetter(refresh_token=refresh_token) return tok.scopes
Ensures the requested scope matches the scope originally granted by the resource owner. If the scope is omitted it is treated as equal to the scope originally granted by the resource owner.
def confirm_scopes(self, refresh_token, scopes, request, *args, **kwargs): """Ensures the requested scope matches the scope originally granted by the resource owner. If the scope is omitted it is treated as equal to the scope originally granted by the resource owner. DEPRECATION NOTE: This method will cease to be used in oauthlib>0.4.2, future versions of ``oauthlib`` use the validator method ``get_original_scopes`` to determine the scope of the refreshed token. """ if not scopes: log.debug('Scope omitted for refresh token %r', refresh_token) return True log.debug('Confirm scopes %r for refresh token %r', scopes, refresh_token) tok = self._tokengetter(refresh_token=refresh_token) return set(tok.scopes) == set(scopes)
Default redirect_uri for the given client.
def get_default_redirect_uri(self, client_id, request, *args, **kwargs): """Default redirect_uri for the given client.""" request.client = request.client or self._clientgetter(client_id) redirect_uri = request.client.default_redirect_uri log.debug('Found default redirect uri %r', redirect_uri) return redirect_uri
Default scopes for the given client.
def get_default_scopes(self, client_id, request, *args, **kwargs): """Default scopes for the given client.""" request.client = request.client or self._clientgetter(client_id) scopes = request.client.default_scopes log.debug('Found default scopes %r', scopes) return scopes
Invalidate an authorization code after use.
def invalidate_authorization_code(self, client_id, code, request, *args, **kwargs): """Invalidate an authorization code after use. We keep the temporary code in a grant, which has a `delete` function to destroy itself. """ log.debug('Destroy grant token for client %r, %r', client_id, code) grant = self._grantgetter(client_id=client_id, code=code) if grant: grant.delete()
Persist the authorization code.
def save_authorization_code(self, client_id, code, request, *args, **kwargs): """Persist the authorization code.""" log.debug( 'Persist authorization code %r for client %r', code, client_id ) request.client = request.client or self._clientgetter(client_id) self._grantsetter(client_id, code, request, *args, **kwargs) return request.client.default_redirect_uri
Persist the Bearer token.
def save_bearer_token(self, token, request, *args, **kwargs): """Persist the Bearer token.""" log.debug('Save bearer token %r', token) self._tokensetter(token, request, *args, **kwargs) return request.client.default_redirect_uri
Validate access token.
def validate_bearer_token(self, token, scopes, request): """Validate access token. :param token: A string of random characters :param scopes: A list of scopes :param request: The Request object passed by oauthlib The validation validates: 1) if the token is available 2) if the token has expired 3) if the scopes are available """ log.debug('Validate bearer token %r', token) tok = self._tokengetter(access_token=token) if not tok: msg = 'Bearer token not found.' request.error_message = msg log.debug(msg) return False # validate expires if tok.expires is not None and \ datetime.datetime.utcnow() > tok.expires: msg = 'Bearer token is expired.' request.error_message = msg log.debug(msg) return False # validate scopes if scopes and not set(tok.scopes) & set(scopes): msg = 'Bearer token scope not valid.' request.error_message = msg log.debug(msg) return False request.access_token = tok request.user = tok.user request.scopes = scopes if hasattr(tok, 'client'): request.client = tok.client elif hasattr(tok, 'client_id'): request.client = self._clientgetter(tok.client_id) return True
Ensure client_id belong to a valid and active client.
def validate_client_id(self, client_id, request, *args, **kwargs): """Ensure client_id belong to a valid and active client.""" log.debug('Validate client %r', client_id) client = request.client or self._clientgetter(client_id) if client: # attach client to request object request.client = client return True return False
Ensure the grant code is valid.
def validate_code(self, client_id, code, client, request, *args, **kwargs): """Ensure the grant code is valid.""" client = client or self._clientgetter(client_id) log.debug( 'Validate code for client %r and code %r', client.client_id, code ) grant = self._grantgetter(client_id=client.client_id, code=code) if not grant: log.debug('Grant not found.') return False if hasattr(grant, 'expires') and \ datetime.datetime.utcnow() > grant.expires: log.debug('Grant is expired.') return False request.state = kwargs.get('state') request.user = grant.user request.scopes = grant.scopes return True
Ensure the client is authorized to use the grant type requested.
def validate_grant_type(self, client_id, grant_type, client, request, *args, **kwargs): """Ensure the client is authorized to use the grant type requested. It will allow any of the four grant types (`authorization_code`, `password`, `client_credentials`, `refresh_token`) by default. Implemented `allowed_grant_types` for client object to authorize the request. It is suggested that `allowed_grant_types` should contain at least `authorization_code` and `refresh_token`. """ if self._usergetter is None and grant_type == 'password': log.debug('Password credential authorization is disabled.') return False default_grant_types = ( 'authorization_code', 'password', 'client_credentials', 'refresh_token', ) # Grant type is allowed if it is part of the 'allowed_grant_types' # of the selected client or if it is one of the default grant types if hasattr(client, 'allowed_grant_types'): if grant_type not in client.allowed_grant_types: return False else: if grant_type not in default_grant_types: return False if grant_type == 'client_credentials': if not hasattr(client, 'user'): log.debug('Client should have a user property') return False request.user = client.user return True
Ensure client is authorized to redirect to the redirect_uri.
def validate_redirect_uri(self, client_id, redirect_uri, request, *args, **kwargs): """Ensure client is authorized to redirect to the redirect_uri. This method is used in the authorization code grant flow and also in implicit grant flow. It will detect if redirect_uri in client's redirect_uris strictly, you can add a `validate_redirect_uri` function on grant for a customized validation. """ request.client = request.client or self._clientgetter(client_id) client = request.client if hasattr(client, 'validate_redirect_uri'): return client.validate_redirect_uri(redirect_uri) return redirect_uri in client.redirect_uris
Ensure the token is valid and belongs to the client
def validate_refresh_token(self, refresh_token, client, request, *args, **kwargs): """Ensure the token is valid and belongs to the client This method is used by the authorization code grant indirectly by issuing refresh tokens, resource owner password credentials grant (also indirectly) and the refresh token grant. """ token = self._tokengetter(refresh_token=refresh_token) if token and token.client_id == client.client_id: # Make sure the request object contains user and client_id request.client_id = token.client_id request.user = token.user return True return False
Ensure client is authorized to use the response type requested.
def validate_response_type(self, client_id, response_type, client, request, *args, **kwargs): """Ensure client is authorized to use the response type requested. It will allow any of the two (`code`, `token`) response types by default. Implemented `allowed_response_types` for client object to authorize the request. """ if response_type not in ('code', 'token'): return False if hasattr(client, 'allowed_response_types'): return response_type in client.allowed_response_types return True
Ensure the client is authorized access to requested scopes.
def validate_scopes(self, client_id, scopes, client, request, *args, **kwargs): """Ensure the client is authorized access to requested scopes.""" if hasattr(client, 'validate_scopes'): return client.validate_scopes(scopes) return set(client.default_scopes).issuperset(set(scopes))
Ensure the username and password is valid.
def validate_user(self, username, password, client, request, *args, **kwargs): """Ensure the username and password is valid. Attach user object on request for later using. """ log.debug('Validating username %r and its password', username) if self._usergetter is not None: user = self._usergetter( username, password, client, request, *args, **kwargs ) if user: request.user = user return True return False log.debug('Password credential authorization is disabled.') return False
Revoke an access or refresh token.
def revoke_token(self, token, token_type_hint, request, *args, **kwargs): """Revoke an access or refresh token. """ if token_type_hint: tok = self._tokengetter(**{token_type_hint: token}) else: tok = self._tokengetter(access_token=token) if not tok: tok = self._tokengetter(refresh_token=token) if tok: request.client_id = tok.client_id request.user = tok.user tok.delete() return True msg = 'Invalid token supplied.' log.debug(msg) request.error_message = msg return False
OAuthResponse class can t parse the JSON data with content - type - text/ html and because of a rubbish api we can t just tell flask - oauthlib to treat it as json.
def json_to_dict(x): '''OAuthResponse class can't parse the JSON data with content-type - text/html and because of a rubbish api, we can't just tell flask-oauthlib to treat it as json.''' if x.find(b'callback') > -1: # the rubbish api (https://graph.qq.com/oauth2.0/authorize) is handled here as special case pos_lb = x.find(b'{') pos_rb = x.find(b'}') x = x[pos_lb:pos_rb + 1] try: if type(x) != str: # Py3k x = x.decode('utf-8') return json.loads(x, encoding='utf-8') except: return x
Update some required parameters for OAuth2. 0 API calls
def update_qq_api_request_data(data={}): '''Update some required parameters for OAuth2.0 API calls''' defaults = { 'openid': session.get('qq_openid'), 'access_token': session.get('qq_token')[0], 'oauth_consumer_key': QQ_APP_ID, } defaults.update(data) return defaults
Recursively converts dictionary keys to strings.
def convert_keys_to_string(dictionary): '''Recursively converts dictionary keys to strings.''' if not isinstance(dictionary, dict): return dictionary return dict((str(k), convert_keys_to_string(v)) for k, v in dictionary.items())
Since weibo is a rubbish server it does not follow the standard we need to change the authorization header for it.
def change_weibo_header(uri, headers, body): """Since weibo is a rubbish server, it does not follow the standard, we need to change the authorization header for it.""" auth = headers.get('Authorization') if auth: auth = auth.replace('Bearer', 'OAuth2') headers['Authorization'] = auth return uri, headers, body
Creates a remote app and registers it.
def register_to(self, oauth, name=None, **kwargs): """Creates a remote app and registers it.""" kwargs = self._process_kwargs( name=(name or self.default_name), **kwargs) return oauth.remote_app(**kwargs)
Creates a remote app only.
def create(self, oauth, **kwargs): """Creates a remote app only.""" kwargs = self._process_kwargs( name=self.default_name, register=False, **kwargs) return oauth.remote_app(**kwargs)
The uri returned from request. uri is not properly urlencoded ( sometimes it s partially urldecoded ) This is a weird hack to get werkzeug to return the proper urlencoded string uri
def _get_uri_from_request(request): """ The uri returned from request.uri is not properly urlencoded (sometimes it's partially urldecoded) This is a weird hack to get werkzeug to return the proper urlencoded string uri """ uri = request.base_url if request.query_string: uri += '?' + request.query_string.decode('utf-8') return uri
Extract request params.
def extract_params(): """Extract request params.""" uri = _get_uri_from_request(request) http_method = request.method headers = dict(request.headers) if 'wsgi.input' in headers: del headers['wsgi.input'] if 'wsgi.errors' in headers: del headers['wsgi.errors'] # Werkzeug, and subsequently Flask provide a safe Authorization header # parsing, so we just replace the Authorization header with the extraced # info if it was successfully parsed. if request.authorization: headers['Authorization'] = request.authorization body = request.form.to_dict() return uri, http_method, body, headers
Make sure text is bytes type.
def to_bytes(text, encoding='utf-8'): """Make sure text is bytes type.""" if not text: return text if not isinstance(text, bytes_type): text = text.encode(encoding) return text
Decode base64 string.
def decode_base64(text, encoding='utf-8'): """Decode base64 string.""" text = to_bytes(text, encoding) return to_unicode(base64.b64decode(text), encoding)
Create response class for Flask.
def create_response(headers, body, status): """Create response class for Flask.""" response = Response(body or '') for k, v in headers.items(): response.headers[str(k)] = v response.status_code = status return response
Returns a: class: SimpleCache instance
def _simple(self, **kwargs): """Returns a :class:`SimpleCache` instance .. warning:: This cache system might not be thread safe. Use with caution. """ kwargs.update(dict(threshold=self._config('threshold', 500))) return SimpleCache(**kwargs)
Returns a: class: MemcachedCache instance
def _memcache(self, **kwargs): """Returns a :class:`MemcachedCache` instance""" kwargs.update(dict( servers=self._config('MEMCACHED_SERVERS', None), key_prefix=self._config('key_prefix', None), )) return MemcachedCache(**kwargs)
Returns a: class: RedisCache instance
def _redis(self, **kwargs): """Returns a :class:`RedisCache` instance""" kwargs.update(dict( host=self._config('REDIS_HOST', 'localhost'), port=self._config('REDIS_PORT', 6379), password=self._config('REDIS_PASSWORD', None), db=self._config('REDIS_DB', 0), key_prefix=self._config('KEY_PREFIX', None), )) return RedisCache(**kwargs)
Returns a: class: FileSystemCache instance
def _filesystem(self, **kwargs): """Returns a :class:`FileSystemCache` instance""" kwargs.update(dict( threshold=self._config('threshold', 500), )) return FileSystemCache(self._config('dir', None), **kwargs)
Gets the cached clients dictionary in current context.
def get_cached_clients(): """Gets the cached clients dictionary in current context.""" if OAuth.state_key not in current_app.extensions: raise RuntimeError('%r is not initialized.' % current_app) state = current_app.extensions[OAuth.state_key] return state.cached_clients
Adds remote application and applies custom attributes on it.
def add_remote_app(self, remote_app, name=None, **kwargs): """Adds remote application and applies custom attributes on it. If the application instance's name is different from the argument provided name, or the keyword arguments is not empty, then the application instance will not be modified but be copied as a prototype. :param remote_app: the remote application instance. :type remote_app: the subclasses of :class:`BaseApplication` :params kwargs: the overriding attributes for the application instance. """ if name is None: name = remote_app.name if name != remote_app.name or kwargs: remote_app = copy.copy(remote_app) remote_app.name = name vars(remote_app).update(kwargs) if not hasattr(remote_app, 'clients'): remote_app.clients = cached_clients self.remote_apps[name] = remote_app return remote_app
Creates and adds new remote application.
def remote_app(self, name, version=None, **kwargs): """Creates and adds new remote application. :param name: the remote application's name. :param version: '1' or '2', the version code of OAuth protocol. :param kwargs: the attributes of remote application. """ if version is None: if 'request_token_url' in kwargs: version = '1' else: version = '2' if version == '1': remote_app = OAuth1Application(name, clients=cached_clients) elif version == '2': remote_app = OAuth2Application(name, clients=cached_clients) else: raise ValueError('unkonwn version %r' % version) return self.add_remote_app(remote_app, **kwargs)
Call the method repeatedly such that it will raise an exception.
def check_exception(self): """ Call the method repeatedly such that it will raise an exception. """ for i in xrange(self.iterations): cert = X509() try: cert.get_pubkey() except Error: pass
Call the method repeatedly such that it will return a PKey object.
def check_success(self): """ Call the method repeatedly such that it will return a PKey object. """ small = xrange(3) for i in xrange(self.iterations): key = PKey() key.generate_key(TYPE_DSA, 256) for i in small: cert = X509() cert.set_pubkey(key) for i in small: cert.get_pubkey()
Call the function with an encrypted PEM and a passphrase callback.
def check_load_privatekey_callback(self): """ Call the function with an encrypted PEM and a passphrase callback. """ for i in xrange(self.iterations * 10): load_privatekey( FILETYPE_PEM, self.ENCRYPTED_PEM, lambda *args: "hello, secret")
Call the function with an encrypted PEM and a passphrase callback which returns the wrong passphrase.
def check_load_privatekey_callback_incorrect(self): """ Call the function with an encrypted PEM and a passphrase callback which returns the wrong passphrase. """ for i in xrange(self.iterations * 10): try: load_privatekey( FILETYPE_PEM, self.ENCRYPTED_PEM, lambda *args: "hello, public") except Error: pass
Call the function with an encrypted PEM and a passphrase callback which returns a non - string.
def check_load_privatekey_callback_wrong_type(self): """ Call the function with an encrypted PEM and a passphrase callback which returns a non-string. """ for i in xrange(self.iterations * 10): try: load_privatekey( FILETYPE_PEM, self.ENCRYPTED_PEM, lambda *args: {}) except ValueError: pass
Create a CRL object with 100 Revoked objects then call the get_revoked method repeatedly.
def check_get_revoked(self): """ Create a CRL object with 100 Revoked objects, then call the get_revoked method repeatedly. """ crl = CRL() for i in xrange(100): crl.add_revoked(Revoked()) for i in xrange(self.iterations): crl.get_revoked()