Search is not available for this dataset
text stringlengths 75 104k |
|---|
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... |
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, *... |
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=bod... |
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::
@... |
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... |
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)
... |
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._g... |
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._tokeng... |
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_re... |
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'):
... |
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 |
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 N... |
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
... |
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 ... |
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,
tok... |
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)
... |
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)
... |
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:
... |
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,... |
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 F... |
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... |
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,
... |
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'],
... |
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).... |
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::
... |
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`::
clas... |
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, *... |
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=reques... |
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... |
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 t... |
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... |
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.o... |
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 enc... |
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`_... |
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_r... |
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, _ =... |
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 ... |
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.
... |
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: T... |
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', redirec... |
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 |
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... |
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.... |
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 |
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 availab... |
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
... |
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(... |
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_tok... |
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_... |
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 ... |
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... |
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).iss... |
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._usergette... |
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:
... |
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 speci... |
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 |
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()) |
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
... |
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) |
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) |
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 += '?' + ... |
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... |
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 |
def decode_base64(text, encoding='utf-8'):
"""Decode base64 string."""
text = to_bytes(text, encoding)
return to_unicode(base64.b64decode(text), encoding) |
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 |
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) |
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) |
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),... |
def _filesystem(self, **kwargs):
"""Returns a :class:`FileSystemCache` instance"""
kwargs.update(dict(
threshold=self._config('threshold', 500),
))
return FileSystemCache(self._config('dir', None), **kwargs) |
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 |
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 mo... |
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... |
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 |
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()
... |
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") |
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_... |
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, se... |
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() |
def check_X509_REVOKED_dup(self):
"""
Copy an empty Revoked object repeatedly. The copy is not garbage
collected, therefore it needs to be manually freed.
"""
for i in xrange(self.iterations * 100):
revoked_copy = _X509_REVOKED_dup(Revoked()._revoked)
_lib... |
def check_to_EC_KEY(self):
"""
Repeatedly create an EC_KEY* from an :py:obj:`_EllipticCurve`. The
structure should be automatically garbage collected.
"""
curves = get_elliptic_curves()
if curves:
curve = next(iter(curves))
for i in xrange(self.it... |
def main():
"""
Connect to an SNI-enabled server and request a specific hostname, specified
by argv[1], of it.
"""
if len(argv) < 2:
print('Usage: %s <hostname>' % (argv[0],))
return 1
client = socket()
print('Connecting...', end="")
stdout.flush()
client.connect(('... |
def createKeyPair(type, bits):
"""
Create a public/private key pair.
Arguments: type - Key type, must be one of TYPE_RSA and TYPE_DSA
bits - Number of bits to use in the key
Returns: The public/private key pair in a PKey object
"""
pkey = crypto.PKey()
pkey.generate_key(typ... |
def createCertRequest(pkey, digest="sha256", **name):
"""
Create a certificate request.
Arguments: pkey - The key to associate with the request
digest - Digestion method to use for signing, default is sha256
**name - The name of the subject of the request, possible
... |
def createCertificate(req, issuerCertKey, serial, validityPeriod,
digest="sha256"):
"""
Generate a certificate given a certificate request.
Arguments: req - Certificate request to use
issuerCert - The certificate of the issuer
issuerKey - The priv... |
def _make_requires(flag, error):
"""
Builds a decorator that ensures that functions that rely on OpenSSL
functions that are not present in this build raise NotImplementedError,
rather than AttributeError coming out of cryptography.
:param flag: A cryptography flag that guards the functions, e.g.
... |
def load_verify_locations(self, cafile, capath=None):
"""
Let SSL know where we can find trusted certificates for the certificate
chain. Note that the certificates have to be in PEM format.
If capath is passed, it must be a directory prepared using the
``c_rehash`` tool include... |
def set_passwd_cb(self, callback, userdata=None):
"""
Set the passphrase callback. This function will be called
when a private key with a passphrase is loaded.
:param callback: The Python callback to use. This must accept three
positional arguments. First, an integer givi... |
def set_default_verify_paths(self):
"""
Specify that the platform provided CA certificates are to be used for
verification purposes. This method has some caveats related to the
binary wheels that cryptography (pyOpenSSL's primary dependency) ships:
* macOS will only load certi... |
def _check_env_vars_set(self, dir_env_var, file_env_var):
"""
Check to see if the default cert dir/file environment vars are present.
:return: bool
"""
return (
os.environ.get(file_env_var) is not None or
os.environ.get(dir_env_var) is not None
) |
def _fallback_default_verify_paths(self, file_path, dir_path):
"""
Default verify paths are based on the compiled version of OpenSSL.
However, when pyca/cryptography is compiled as a manylinux1 wheel
that compiled location can potentially be wrong. So, like Go, we
will try a pred... |
def use_certificate_chain_file(self, certfile):
"""
Load a certificate chain from a file.
:param certfile: The name of the certificate chain file (``bytes`` or
``unicode``). Must be PEM encoded.
:return: None
"""
certfile = _path_string(certfile)
r... |
def use_certificate_file(self, certfile, filetype=FILETYPE_PEM):
"""
Load a certificate from a file
:param certfile: The name of the certificate file (``bytes`` or
``unicode``).
:param filetype: (optional) The encoding of the file, which is either
:const:`FILETYP... |
def use_certificate(self, cert):
"""
Load a certificate from a X509 object
:param cert: The X509 object
:return: None
"""
if not isinstance(cert, X509):
raise TypeError("cert must be an X509 instance")
use_result = _lib.SSL_CTX_use_certificate(self._... |
def add_extra_chain_cert(self, certobj):
"""
Add certificate to chain
:param certobj: The X509 certificate object to add to the chain
:return: None
"""
if not isinstance(certobj, X509):
raise TypeError("certobj must be an X509 instance")
copy = _lib.... |
def use_privatekey_file(self, keyfile, filetype=_UNSPECIFIED):
"""
Load a private key from a file
:param keyfile: The name of the key file (``bytes`` or ``unicode``)
:param filetype: (optional) The encoding of the file, which is either
:const:`FILETYPE_PEM` or :const:`FILETY... |
def use_privatekey(self, pkey):
"""
Load a private key from a PKey object
:param pkey: The PKey object
:return: None
"""
if not isinstance(pkey, PKey):
raise TypeError("pkey must be a PKey instance")
use_result = _lib.SSL_CTX_use_PrivateKey(self._con... |
def load_client_ca(self, cafile):
"""
Load the trusted certificates that will be sent to the client. Does
not actually imply any of the certificates are trusted; that must be
configured separately.
:param bytes cafile: The path to a certificates file in PEM format.
:ret... |
def set_session_id(self, buf):
"""
Set the session id to *buf* within which a session can be reused for
this Context object. This is needed when doing session resumption,
because there is no way for a stored session to know which Context
object it is associated with.
:p... |
def set_session_cache_mode(self, mode):
"""
Set the behavior of the session cache used by all connections using
this Context. The previously set mode is returned. See
:const:`SESS_CACHE_*` for details about particular modes.
:param mode: One or more of the SESS_CACHE_* flags (... |
def set_verify(self, mode, callback):
"""
et the verification flags for this Context object to *mode* and specify
that *callback* should be used for verification callbacks.
:param mode: The verify mode, this should be one of
:const:`VERIFY_NONE` and :const:`VERIFY_PEER`. If
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.