desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Returns a list of all joystick event since the last call'
def read(self):
if (not self._f): raise Exception('Joystick device not opened') self._read_all_events() return [self.axes, self.buttons]
'Returns a dict with device_id as key and device name as value of all the detected devices (result is cached once one or more device are found).'
def devices(self):
if (len(self._devices) == 0): syspaths = glob.glob('/sys/class/input/js*') for path in syspaths: device_id = int(os.path.basename(path)[2:]) with open((path + '/device/name')) as namefile: name = namefile.read().strip() self._js[device_id] = _JS(de...
'Open the joystick device. The device_id is given by available_devices'
def open(self, device_id):
self._js[device_id].open()
'Open the joystick device'
def close(self, device_id):
self._js[device_id].close()
'Returns a list of all joystick event since the last call'
def read(self, device_id):
return self._js[device_id].read()
'Init app with Flask instance. You can also pass the instance of Flask later:: oauth = OAuth() oauth.init_app(app)'
def init_app(self, app):
self.app = app app.extensions = getattr(app, 'extensions', {}) app.extensions[self.state_key] = self
'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`.'
def remote_app(self, name, register=True, **kwargs):
remote = OAuthRemoteApp(self, name, **kwargs) if register: assert (name not in self.remote_apps) self.remote_apps[name] = remote return remote
'The status code of the response.'
@property def status(self):
return self._resp.code
'Sends a ``GET`` request. Accepts the same parameters as :meth:`request`.'
def get(self, *args, **kwargs):
kwargs['method'] = 'GET' return self.request(*args, **kwargs)
'Sends a ``POST`` request. Accepts the same parameters as :meth:`request`.'
def post(self, *args, **kwargs):
kwargs['method'] = 'POST' return self.request(*args, **kwargs)
'Sends a ``PUT`` request. Accepts the same parameters as :meth:`request`.'
def put(self, *args, **kwargs):
kwargs['method'] = 'PUT' return self.request(*args, **kwargs)
'Sends a ``DELETE`` request. Accepts the same parameters as :meth:`request`.'
def delete(self, *args, **kwargs):
kwargs['method'] = 'DELETE' return self.request(*args, **kwargs)
'Sends a ``PATCH`` request. Accepts the same parameters as :meth:`post`.'
def patch(self, *args, **kwargs):
kwargs['method'] = 'PATCH' return self.request(*args, **kwargs)
'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. :para...
def request(self, url, data=None, headers=None, format='urlencoded', method='GET', content_type=None, token=None):
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 = No...
'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 pai...
def authorize(self, callback=None, state=None, **kwargs):
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(p...
'Register a function as token getter.'
def tokengetter(self, f):
self._tokengetter = f return f
'Handles an oauth1 authorization response.'
def handle_oauth1_response(self):
client = self.make_client() client.verifier = request.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] cl...
'Handles an oauth2 authorization response.'
def handle_oauth2_response(self):
client = self.make_client() remote_args = {'code': request.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 = c...
'Handles a unknown authorization response.'
def handle_unknown_response(self):
return None
'Handles authorization response smartly.'
def authorized_response(self):
if ('oauth_verifier' in request.args): data = self.handle_oauth1_response() elif ('code' in request.args): data = self.handle_oauth2_response() else: data = self.handle_unknown_response() session.pop(('%s_oauthtok' % self.name), None) session.pop(('%s_oauthredir' % self.name)...
'Handles an OAuth callback. .. versionchanged:: 0.7 @authorized_handler is deprecated in favor of authorized_response.'
def authorized_handler(self, f):
@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
'This callback can be used to initialize an application for the oauth provider instance.'
def init_app(self, app):
self.app = app app.extensions = getattr(app, 'extensions', {}) app.extensions['oauthlib.provider.oauth2'] = 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\''
@cached_property def error_uri(self):
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. 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_...
@cached_property def server(self):
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...
'Register functions to be invoked before accessing the resource. The function accepts nothing as parameters, but you can get information from `Flask.request` object. It is usually useful for setting limitation on the client request:: @oauth.before_request def limit_client_request(): client_id = request.values.get(\'cli...
def before_request(self, f):
self._before_request_funcs.append(f) return f
'Register functions to be invoked after accessing the resource. The function accepts ``valid`` and ``request`` as parameters, and it should return a tuple of them:: @oauth.after_request def valid_after_request(valid, oauth): if oauth.user in black_list: return False, oauth return valid, oauth'
def after_request(self, f):
self._after_request_funcs.append(f) return f
'Register a function for responsing with invalid request. When an invalid request proceeds to :meth:`require_oauth`, we can handle the request with the registered function. The function accepts one parameter, which is an oauthlib Request object:: @oauth.invalid_response def invalid_require_oauth(req): return jsonify(me...
def invalid_response(self, f):
self._invalid_response = f return f
'Register a function as the client getter. The function accepts one parameter `client_id`, and it returns a client object with at least these information: - client_id: A random string - client_secret: A random string - is_confidential: A bool represents if it is confidential - redirect_uris: A list of redirect uris - d...
def clientgetter(self, f):
self._clientgetter = f return f
'Register a function as the user getter. This decorator is only required for **password credential** authorization:: @oauth.usergetter def get_user(username, password, client, request, *args, **kwargs): # client: current request client if not client.has_password_credential_permission: return None user = User.get_user_b...
def usergetter(self, f):
self._usergetter = f return f
'Register a function as the token getter. The function accepts an `access_token` or `refresh_token` parameters, and it returns a token object with at least these information: - access_token: A string token - refresh_token: A string token - client_id: ID of the client - scopes: A list of scopes - expires: A `datetime.da...
def tokengetter(self, f):
self._tokengetter = f return f
'Register a function to save the bearer token. The setter accepts two parameters at least, one is token, the other is request:: @oauth.tokensetter def set_token(token, request, *args, **kwargs): save_token(token, request.client, request.user) The parameter token is a dict, that looks like:: u\'access_token\': u\'6JwgO7...
def tokensetter(self, f):
self._tokensetter = f return f
'Register a function as the grant getter. The function accepts `client_id`, `code` and more:: @oauth.grantgetter def grant(client_id, code): return get_grant(client_id, code) It returns a grant object with at least these information: - delete: A function to delete itself'
def grantgetter(self, f):
self._grantgetter = f return f
'Register a function to save the grant code. The function accepts `client_id`, `code`, `request` and more:: @oauth.grantsetter def set_grant(client_id, code, request, *args, **kwargs): save_grant(client_id, code, request.user, request.scopes)'
def grantsetter(self, f):
self._grantsetter = f return 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 authorizat...
def authorize_handler(self, f):
@wraps(f) def decorated(*args, **kwargs): 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.', re...
'When consumer confirm the authorization.'
def confirm_authorization_request(self):
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)) ...
'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\')'
def verify_request(self, scopes):
(uri, http_method, body, headers) = extract_params() return self.server.verify_request(uri, http_method, body, headers, scopes)
'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\']) @oau...
def token_handler(self, f):
@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_meth...
'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=[\'...
def revoke_handler(self, f):
@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 ...
'Protect resource with specified scopes.'
def require_oauth(self, *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) ...
'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, ...
def _get_client_creds_from_request(self, request):
if (request.client_id is not None): return (request.client_id, request.client_secret) auth = request.headers.get('Authorization') if isinstance(auth, dict): return (auth['username'], auth['password']) return (None, None)
'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....
def client_authentication_required(self, request, *args, **kwargs):
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', 'authorizatio...
'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'
def authenticate_client(self, request, *args, **kwargs):
(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...
'Authenticate a non-confidential client. :param client_id: Client ID of the non-confidential client :param request: The Request object passed by oauthlib'
def authenticate_client_id(self, client_id, request, *args, **kwargs):
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.') ...
'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.'
def confirm_redirect_uri(self, client_id, code, redirect_uri, client, *args, **kwargs):
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 Fals...
'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 get_original_scopes(self, refresh_token, request, *args, **kwargs):
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. DEPRECATION NOTE: This method will cease to be used in oauthlib>0.4.2, future versions of ``oauthlib`` use the validator method `...
def confirm_scopes(self, refresh_token, scopes, request, *args, **kwargs):
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(scop...
'Default redirect_uri for the given client.'
def get_default_redirect_uri(self, client_id, request, *args, **kwargs):
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):
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. We keep the temporary code in a grant, which has a `delete` function to destroy itself.'
def invalidate_authorization_code(self, client_id, code, request, *args, **kwargs):
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):
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):
log.debug('Save bearer token %r', token) self._tokensetter(token, request, *args, **kwargs) return request.client.default_redirect_uri
'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'
def validate_bearer_token(self, token, scopes, request):
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 if ((tok.expires is not None) and (datetime.datetime.utcnow() >...
'Ensure client_id belong to a valid and active client.'
def validate_client_id(self, client_id, request, *args, **kwargs):
log.debug('Validate client %r', client_id) client = (request.client or self._clientgetter(client_id)) if client: request.client = client return True return False
'Ensure the grant code is valid.'
def validate_code(self, client_id, code, client, request, *args, **kwargs):
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 (h...
'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` shoul...
def validate_grant_type(self, client_id, grant_type, client, request, *args, **kwargs):
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') if hasattr(client, 'allowed_grant_types'): ...
'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.'
def validate_redirect_uri(self, client_id, redirect_uri, request, *args, **kwargs):
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 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.'
def validate_refresh_token(self, refresh_token, client, request, *args, **kwargs):
token = self._tokengetter(refresh_token=refresh_token) if (token and (token.client_id == client.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. It will allow any of the two (`code`, `token`) response types by default. Implemented `allowed_response_types` for client object to authorize the request.'
def validate_response_type(self, client_id, response_type, client, request, *args, **kwargs):
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):
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. Attach user object on request for later using.'
def validate_user(self, username, password, client, request, *args, **kwargs):
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('Pass...
'Revoke an access or refresh token.'
def revoke_token(self, token, token_type_hint, request, *args, **kwargs):
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 t...
'This callback can be used to initialize an application for the oauth provider instance.'
def init_app(self, app):
self.app = app app.extensions = getattr(app, 'extensions', {}) app.extensions['oauthlib.provider.oauth1'] = 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:: OAUTH1_PROVIDER_ERROR_URI = \'/error\' You can also define the error page by a named endpoint:: OAUTH1_PROVIDER_ERROR_ENDPOINT = \'oauth.error\''
@cached_property def error_uri(self):
error_uri = self.app.config.get('OAUTH1_PROVIDER_ERROR_URI') if error_uri: return error_uri error_endpoint = self.app.config.get('OAUTH1_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.'
@cached_property def server(self):
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') an...
'Register functions to be invoked before accessing the resource. The function accepts nothing as parameters, but you can get information from `Flask.request` object. It is usually useful for setting limitation on the client request:: @oauth.before_request def limit_client_request(): client_key = request.values.get(\'cl...
def before_request(self, f):
self._before_request_funcs.append(f) return f
'Register functions to be invoked after accessing the resource. The function accepts ``valid`` and ``request`` as parameters, and it should return a tuple of them:: @oauth.after_request def valid_after_request(valid, oauth): if oauth.user in black_list: return False, oauth return valid, oauth'
def after_request(self, f):
self._after_request_funcs.append(f) return f
'Register a function as the client getter. The function accepts one parameter `client_key`, and it returns a client object with at least these information: - client_key: A random string - client_secret: A random string - redirect_uris: A list of redirect uris - default_realms: Default scopes of the client The client ma...
def clientgetter(self, f):
self._clientgetter = f return f
'Register a function as the access token getter. The function accepts `client_key` and `token` parameters, and it returns an access token object contains: - client: Client associated with this token - user: User associated with this token - token: Access token - secret: Access token secret - realms: Realms with this ac...
def tokengetter(self, f):
self._tokengetter = f return f
'Register a function as the access token setter. The setter accepts two parameters at least, one is token, the other is request:: @oauth.tokensetter def save_access_token(token, request): access_token = AccessToken( client=request.client, user=request.user, token=token[\'oauth_token\'], secret=token[\'oauth_token_secre...
def tokensetter(self, f):
self._tokensetter = f return f
'Register a function as the request token getter. The function accepts a `token` parameter, and it returns an request token object contains: - client: Client associated with this token - token: Access token - secret: Access token secret - realms: Realms with this access token - redirect_uri: A URI for redirecting Imple...
def grantgetter(self, f):
self._grantgetter = f return f
'Register a function as the request token setter. The setter accepts a token and request parameters:: @oauth.grantsetter def save_request_token(token, request): data = RequestToken( token=token[\'oauth_token\'], secret=token[\'oauth_token_secret\'], client=request.client, redirect_uri=oauth.redirect_uri, realms=request...
def grantsetter(self, f):
self._grantsetter = f return f
'Register a function as the nonce and timestamp getter. The function accepts parameters: - client_key: The client/consure key - timestamp: The ``oauth_timestamp`` parameter - nonce: The ``oauth_nonce`` parameter - request_token: Request token string, if any - access_token: Access token string, if any A nonce and timest...
def noncegetter(self, f):
self._noncegetter = f return f
'Register a function as the nonce and timestamp setter. The parameters are the same with :meth:`noncegetter`:: @oauth.noncegetter def save_nonce(client_key, timestamp, nonce, request_token, access_token): data = Nonce("...") return data.save() The timestamp will be expired in 60s, it would be a better design if you put...
def noncesetter(self, f):
self._noncesetter = f return f
'Register a function as the verifier getter. The return verifier object should at least contain a user object which is the current user. The implemented code looks like:: @oauth.verifiergetter def load_verifier(verifier, token): data = Verifier.get(verifier) if data.request_token == token: # check verifier for safety r...
def verifiergetter(self, f):
self._verifiergetter = f return f
'Register a function as the verifier setter. A verifier is better together with request token, but it is not required. A verifier is used together with request token for exchanging access token, it has an expire time, in this case, it would be a better design if you put them in a cache. The implemented code looks like:...
def verifiersetter(self, f):
self._verifiersetter = f return 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 authorizat...
def authorize_handler(self, f):
@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 = s...
'When consumer confirm the authrozation.'
def confirm_authorization_request(self):
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) ...
'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...
def request_token_handler(self, f):
@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...
'Access 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/access_token\') @oauth.access_token_handler def access_token(): return {}'...
def access_token_handler(self, f):
@wraps(f) def decorated(*args, **kwargs): server = self.server (uri, http_method, body, headers) = extract_params() credentials = f(*args, **kwargs) try: ret = server.create_access_token_response(uri, http_method, body, headers, credentials) return create_...
'Protect resource with specified scopes.'
def require_oauth(self, *realms, **kwargs):
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,...
'Allowed signature methods. Default value: SIGNATURE_HMAC and SIGNATURE_RSA. You can customize with Flask Config: - OAUTH1_PROVIDER_SIGNATURE_METHODS'
@property def allowed_signature_methods(self):
return self._config.get('OAUTH1_PROVIDER_SIGNATURE_METHODS', SIGNATURE_METHODS)
'Enforce SSL request. Default is True. You can customize with: - OAUTH1_PROVIDER_ENFORCE_SSL'
@property def enforce_ssl(self):
return self._config.get('OAUTH1_PROVIDER_ENFORCE_SSL', True)
'Get client secret. The client object must has ``client_secret`` attribute.'
def get_client_secret(self, client_key, request):
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. The request token object should a ``secret`` attribute.'
def get_request_token_secret(self, client_key, token, request):
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. The access token object should a ``secret`` attribute.'
def get_access_token_secret(self, client_key, token, request):
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):
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):
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):
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):
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):
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):
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):
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):
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=...
'Validate if the redirect_uri is allowed by the client.'
def validate_redirect_uri(self, client_key, redirect_uri, request):
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 ...
'Check if the token has permission on those realms.'
def validate_realms(self, client_key, token, request, uri=None, realms=None):
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).is...
'Validate verifier exists.'
def validate_verifier(self, client_key, token, verifier, request):
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....
'Verify if the request token is existed.'
def verify_request_token(self, token, request):
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):
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')): return True return (set(tok.realms) == set(realms))
'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...
def save_access_token(self, token, request):
log.debug('Save access token %r', token) self._tokensetter(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(...
def save_request_token(self, token, request):
log.debug('Save request token %r', token) self._grantsetter(token, request)