partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
test
Grant.delete
Removes itself from the cache Note: This is required by the oauthlib
flask_oauthlib/contrib/oauth2.py
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
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
[ "Removes", "itself", "from", "the", "cache" ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/contrib/oauth2.py#L43-L52
[ "def", "delete", "(", "self", ")", ":", "log", ".", "debug", "(", "\"Deleting grant %s for client %s\"", "%", "(", "self", ".", "code", ",", "self", ".", "client_id", ")", ")", "self", ".", "_cache", ".", "delete", "(", "self", ".", "key", ")", "return", "None" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
BaseBinding.query
Determines which method of getting the query object for use
flask_oauthlib/contrib/oauth2.py
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)
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)
[ "Determines", "which", "method", "of", "getting", "the", "query", "object", "for", "use" ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/contrib/oauth2.py#L203-L208
[ "def", "query", "(", "self", ")", ":", "if", "hasattr", "(", "self", ".", "model", ",", "'query'", ")", ":", "return", "self", ".", "model", ".", "query", "else", ":", "return", "self", ".", "session", ".", "query", "(", "self", ".", "model", ")" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
UserBinding.get
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
flask_oauthlib/contrib/oauth2.py
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
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", "the", "User", "object" ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/contrib/oauth2.py#L214-L225
[ "def", "get", "(", "self", ",", "username", ",", "password", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "user", "=", "self", ".", "query", ".", "filter_by", "(", "username", "=", "username", ")", ".", "first", "(", ")", "if", "user", "and", "user", ".", "check_password", "(", "password", ")", ":", "return", "user", "return", "None" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
TokenBinding.get
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
flask_oauthlib/contrib/oauth2.py
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
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
[ "returns", "a", "Token", "object", "with", "the", "given", "access", "token", "or", "refresh", "token" ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/contrib/oauth2.py#L247-L257
[ "def", "get", "(", "self", ",", "access_token", "=", "None", ",", "refresh_token", "=", "None", ")", ":", "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" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
TokenBinding.set
Creates a Token object and removes all expired tokens that belong to the user :param token: token object :param request: OAuthlib request object
flask_oauthlib/contrib/oauth2.py
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
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", "a", "Token", "object", "and", "removes", "all", "expired", "tokens", "that", "belong", "to", "the", "user" ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/contrib/oauth2.py#L259-L292
[ "def", "set", "(", "self", ",", "token", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "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" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
GrantBinding.set
Creates Grant object with the given params :param client_id: ID of the client :param code: :param request: OAuthlib request object
flask_oauthlib/contrib/oauth2.py
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()
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()
[ "Creates", "Grant", "object", "with", "the", "given", "params" ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/contrib/oauth2.py#L304-L322
[ "def", "set", "(", "self", ",", "client_id", ",", "code", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "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", "(", ")" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
GrantBinding.get
Get the Grant object with the given client ID and code :param client_id: ID of the client :param code:
flask_oauthlib/contrib/oauth2.py
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()
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()
[ "Get", "the", "Grant", "object", "with", "the", "given", "client", "ID", "and", "code" ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/contrib/oauth2.py#L324-L330
[ "def", "get", "(", "self", ",", "client_id", ",", "code", ")", ":", "return", "self", ".", "query", ".", "filter_by", "(", "client_id", "=", "client_id", ",", "code", "=", "code", ")", ".", "first", "(", ")" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
parse_response
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
flask_oauthlib/client.py
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()
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()
[ "Parse", "the", "response", "returned", "by", ":", "meth", ":", "OAuthRemoteApp", ".", "http_request", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/client.py#L113-L136
[ "def", "parse_response", "(", "resp", ",", "content", ",", "strict", "=", "False", ",", "content_type", "=", "None", ")", ":", "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", "(", ")" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
prepare_request
Make request parameters right.
flask_oauthlib/client.py
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
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
[ "Make", "request", "parameters", "right", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/client.py#L139-L153
[ "def", "prepare_request", "(", "uri", ",", "headers", "=", "None", ",", "data", "=", "None", ",", "method", "=", "None", ")", ":", "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" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth.init_app
Init app with Flask instance. You can also pass the instance of Flask later:: oauth = OAuth() oauth.init_app(app)
flask_oauthlib/client.py
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
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
[ "Init", "app", "with", "Flask", "instance", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/client.py#L57-L67
[ "def", "init_app", "(", "self", ",", "app", ")", ":", "self", ".", "app", "=", "app", "app", ".", "extensions", "=", "getattr", "(", "app", ",", "'extensions'", ",", "{", "}", ")", "app", ".", "extensions", "[", "self", ".", "state_key", "]", "=", "self" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth.remote_app
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`.
flask_oauthlib/client.py
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
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
[ "Registers", "a", "new", "remote", "application", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/client.py#L69-L81
[ "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" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuthRemoteApp.request
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.
flask_oauthlib/client.py
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)
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)
[ "Sends", "a", "request", "to", "the", "remote", "server", "with", "OAuth", "tokens", "attached", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/client.py#L448-L506
[ "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", "=", "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", ")" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuthRemoteApp.authorize
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
flask_oauthlib/client.py
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)
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)
[ "Returns", "a", "redirect", "response", "to", "the", "remote", "authorization", "URL", "with", "the", "signed", "callback", "given", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/client.py#L508-L562
[ "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", "(", "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", ")" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuthRemoteApp.handle_oauth1_response
Handles an oauth1 authorization response.
flask_oauthlib/client.py
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
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", "oauth1", "authorization", "response", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/client.py#L621-L650
[ "def", "handle_oauth1_response", "(", "self", ",", "args", ")", ":", "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" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuthRemoteApp.handle_oauth2_response
Handles an oauth2 authorization response.
flask_oauthlib/client.py
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
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", "an", "oauth2", "authorization", "response", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/client.py#L652-L694
[ "def", "handle_oauth2_response", "(", "self", ",", "args", ")", ":", "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" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuthRemoteApp.authorized_response
Handles authorization response smartly.
flask_oauthlib/client.py
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
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", "authorization", "response", "smartly", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/client.py#L700-L714
[ "def", "authorized_response", "(", "self", ",", "args", "=", "None", ")", ":", "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" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuthRemoteApp.authorized_handler
Handles an OAuth callback. .. versionchanged:: 0.7 @authorized_handler is deprecated in favor of authorized_response.
flask_oauthlib/client.py
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
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
[ "Handles", "an", "OAuth", "callback", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/client.py#L716-L730
[ "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" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
_hash_token
Creates a hashable object for given token then we could use it as a dictionary key.
flask_oauthlib/contrib/client/application.py
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)
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)
[ "Creates", "a", "hashable", "object", "for", "given", "token", "then", "we", "could", "use", "it", "as", "a", "dictionary", "key", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/contrib/client/application.py#L328-L339
[ "def", "_hash_token", "(", "application", ",", "token", ")", ":", "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", ")" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
BaseApplication.client
The lazy-created OAuth session with the return value of :meth:`tokengetter`. :returns: The OAuth session instance or ``None`` while token missing.
flask_oauthlib/contrib/client/application.py
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)
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)
[ "The", "lazy", "-", "created", "OAuth", "session", "with", "the", "return", "value", "of", ":", "meth", ":", "tokengetter", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/contrib/client/application.py#L77-L86
[ "def", "client", "(", "self", ")", ":", "token", "=", "self", ".", "obtain_token", "(", ")", "if", "token", "is", "None", ":", "raise", "AccessTokenNotFound", "return", "self", ".", "_make_client_with_token", "(", "token", ")" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
BaseApplication._make_client_with_token
Uses cached client or create new one with specific token.
flask_oauthlib/contrib/client/application.py
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
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
[ "Uses", "cached", "client", "or", "create", "new", "one", "with", "specific", "token", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/contrib/client/application.py#L88-L100
[ "def", "_make_client_with_token", "(", "self", ",", "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" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth1Application.make_client
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.
flask_oauthlib/contrib/client/application.py
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)
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", "client", "with", "specific", "access", "token", "pair", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/contrib/client/application.py#L160-L175
[ "def", "make_client", "(", "self", ",", "token", ")", ":", "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", ")" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth2Application.insecure_transport
Creates a context to enable the oauthlib environment variable in order to debug with insecure transport.
flask_oauthlib/contrib/client/application.py
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
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
[ "Creates", "a", "context", "to", "enable", "the", "oauthlib", "environment", "variable", "in", "order", "to", "debug", "with", "insecure", "transport", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/contrib/client/application.py#L304-L325
[ "def", "insecure_transport", "(", "self", ")", ":", "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" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth1Provider.server
All in one endpoints. This property is created automaticly if you have implemented all the getters and setters.
flask_oauthlib/provider/oauth1.py
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' )
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' )
[ "All", "in", "one", "endpoints", ".", "This", "property", "is", "created", "automaticly", "if", "you", "have", "implemented", "all", "the", "getters", "and", "setters", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth1.py#L93-L133
[ "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'", ")", "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'", ")" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth1Provider.authorize_handler
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'
flask_oauthlib/provider/oauth1.py
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
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
[ "Authorization", "handler", "decorator", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth1.py#L371-L411
[ "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", "=", "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" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth1Provider.confirm_authorization_request
When consumer confirm the authrozation.
flask_oauthlib/provider/oauth1.py
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))
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))
[ "When", "consumer", "confirm", "the", "authrozation", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth1.py#L413-L430
[ "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", ")", "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", ")", ")" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth1Provider.request_token_handler
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 {}
flask_oauthlib/provider/oauth1.py
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
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
[ "Request", "token", "handler", "decorator", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth1.py#L432-L457
[ "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_response", "(", "*", "ret", ")", "except", "errors", ".", "OAuth1Error", "as", "e", ":", "return", "_error_response", "(", "e", ")", "return", "decorated" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth1Provider.require_oauth
Protect resource with specified scopes.
flask_oauthlib/provider/oauth1.py
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
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
[ "Protect", "resource", "with", "specified", "scopes", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth1.py#L486-L518
[ "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", ",", "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" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth1RequestValidator.get_client_secret
Get client secret. The client object must has ``client_secret`` attribute.
flask_oauthlib/provider/oauth1.py
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
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", "client", "secret", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth1.py#L632-L642
[ "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" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth1RequestValidator.get_request_token_secret
Get request token secret. The request token object should a ``secret`` attribute.
flask_oauthlib/provider/oauth1.py
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
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", "request", "token", "secret", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth1.py#L644-L655
[ "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" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth1RequestValidator.get_access_token_secret
Get access token secret. The access token object should a ``secret`` attribute.
flask_oauthlib/provider/oauth1.py
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
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
[ "Get", "access", "token", "secret", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth1.py#L657-L671
[ "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" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth1RequestValidator.get_default_realms
Default realms of the client.
flask_oauthlib/provider/oauth1.py
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 []
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 []
[ "Default", "realms", "of", "the", "client", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth1.py#L673-L683
[ "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", "[", "]" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth1RequestValidator.get_realms
Realms for this request token.
flask_oauthlib/provider/oauth1.py
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 []
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 []
[ "Realms", "for", "this", "request", "token", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth1.py#L685-L694
[ "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", "[", "]" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth1RequestValidator.get_redirect_uri
Redirect uri for this request token.
flask_oauthlib/provider/oauth1.py
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_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
[ "Redirect", "uri", "for", "this", "request", "token", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth1.py#L696-L700
[ "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" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth1RequestValidator.get_rsa_key
Retrieves a previously stored client provided RSA key.
flask_oauthlib/provider/oauth1.py
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
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
[ "Retrieves", "a", "previously", "stored", "client", "provided", "RSA", "key", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth1.py#L702-L708
[ "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" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth1RequestValidator.validate_client_key
Validates that supplied client key.
flask_oauthlib/provider/oauth1.py
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
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", "that", "supplied", "client", "key", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth1.py#L714-L721
[ "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" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth1RequestValidator.validate_request_token
Validates request token is available for client.
flask_oauthlib/provider/oauth1.py
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
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", "request", "token", "is", "available", "for", "client", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth1.py#L723-L731
[ "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" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth1RequestValidator.validate_access_token
Validates access token is available for client.
flask_oauthlib/provider/oauth1.py
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
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
[ "Validates", "access", "token", "is", "available", "for", "client", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth1.py#L733-L744
[ "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" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth1RequestValidator.validate_timestamp_and_nonce
Validate the timestamp and nonce is used or not.
flask_oauthlib/provider/oauth1.py
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
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", "the", "timestamp", "and", "nonce", "is", "used", "or", "not", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth1.py#L746-L763
[ "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", "=", "timestamp", ",", "nonce", "=", "nonce", ",", "request_token", "=", "request_token", ",", "access_token", "=", "access_token", ")", "return", "True" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth1RequestValidator.validate_redirect_uri
Validate if the redirect_uri is allowed by the client.
flask_oauthlib/provider/oauth1.py
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
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
[ "Validate", "if", "the", "redirect_uri", "is", "allowed", "by", "the", "client", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth1.py#L765-L775
[ "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", "True", "request", ".", "redirect_uri", "=", "redirect_uri", "return", "redirect_uri", "in", "request", ".", "client", ".", "redirect_uris" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth1RequestValidator.validate_realms
Check if the token has permission on those realms.
flask_oauthlib/provider/oauth1.py
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))
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))
[ "Check", "if", "the", "token", "has", "permission", "on", "those", "realms", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth1.py#L792-L803
[ "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", ")", ".", "issuperset", "(", "set", "(", "realms", ")", ")" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth1RequestValidator.validate_verifier
Validate verifier exists.
flask_oauthlib/provider/oauth1.py
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
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
[ "Validate", "verifier", "exists", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth1.py#L805-L817
[ "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", ".", "user", "=", "data", ".", "user", "if", "hasattr", "(", "data", ",", "'client_key'", ")", ":", "return", "data", ".", "client_key", "==", "client_key", "return", "True" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth1RequestValidator.verify_request_token
Verify if the request token is existed.
flask_oauthlib/provider/oauth1.py
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
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", "request", "token", "is", "existed", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth1.py#L819-L826
[ "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" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth1RequestValidator.verify_realms
Verify if the realms match the requested realms.
flask_oauthlib/provider/oauth1.py
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)
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)
[ "Verify", "if", "the", "realms", "match", "the", "requested", "realms", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth1.py#L828-L839
[ "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'", ")", ":", "# realms not enabled", "return", "True", "return", "set", "(", "tok", ".", "realms", ")", "==", "set", "(", "realms", ")" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth1RequestValidator.save_access_token
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()
flask_oauthlib/provider/oauth1.py
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)
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", "access", "token", "to", "database", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth1.py#L841-L858
[ "def", "save_access_token", "(", "self", ",", "token", ",", "request", ")", ":", "log", ".", "debug", "(", "'Save access token %r'", ",", "token", ")", "self", ".", "_tokensetter", "(", "token", ",", "request", ")" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth1RequestValidator.save_request_token
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()
flask_oauthlib/provider/oauth1.py
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)
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", "request", "token", "to", "database", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth1.py#L860-L877
[ "def", "save_request_token", "(", "self", ",", "token", ",", "request", ")", ":", "log", ".", "debug", "(", "'Save request token %r'", ",", "token", ")", "self", ".", "_grantsetter", "(", "token", ",", "request", ")" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth1RequestValidator.save_verifier
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.
flask_oauthlib/provider/oauth1.py
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 )
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 )
[ "Save", "verifier", "to", "database", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth1.py#L879-L899
[ "def", "save_verifier", "(", "self", ",", "token", ",", "verifier", ",", "request", ")", ":", "log", ".", "debug", "(", "'Save verifier %r for %r'", ",", "verifier", ",", "token", ")", "self", ".", "_verifiersetter", "(", "token", "=", "token", ",", "verifier", "=", "verifier", ",", "request", "=", "request", ")" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth2Provider.error_uri
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'
flask_oauthlib/provider/oauth2.py
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'
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'
[ "The", "error", "page", "URI", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth2.py#L98-L116
[ "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'" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth2Provider.server
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()
flask_oauthlib/provider/oauth2.py
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')
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')
[ "All", "in", "one", "endpoints", ".", "This", "property", "is", "created", "automaticly", "if", "you", "have", "implemented", "all", "the", "getters", "and", "setters", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth2.py#L119-L185
[ "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", ".", "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'", ")" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth2Provider.authorize_handler
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'
flask_oauthlib/provider/oauth2.py
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
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
[ "Authorization", "handler", "decorator", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth2.py#L400-L477
[ "def", "authorize_handler", "(", "self", ",", "f", ")", ":", "@", "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" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth2Provider.confirm_authorization_request
When consumer confirm the authorization.
flask_oauthlib/provider/oauth2.py
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)} ))
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)} ))
[ "When", "consumer", "confirm", "the", "authorization", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth2.py#L479-L515
[ "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", ")", ")", "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", ")", "}", ")", ")" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth2Provider.verify_request
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')
flask_oauthlib/provider/oauth2.py
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 )
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 )
[ "Verify", "current", "request", "get", "the", "oauth", "data", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth2.py#L517-L532
[ "def", "verify_request", "(", "self", ",", "scopes", ")", ":", "uri", ",", "http_method", ",", "body", ",", "headers", "=", "extract_params", "(", ")", "return", "self", ".", "server", ".", "verify_request", "(", "uri", ",", "http_method", ",", "body", ",", "headers", ",", "scopes", ")" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth2Provider.token_handler
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
flask_oauthlib/provider/oauth2.py
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
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", "handler", "decorator", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth2.py#L534-L558
[ "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_method", ",", "body", ",", "headers", ",", "credentials", ")", "return", "create_response", "(", "*", "ret", ")", "return", "decorated" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth2Provider.revoke_handler
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
flask_oauthlib/provider/oauth2.py
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
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
[ "Access", "/", "refresh", "token", "revoke", "decorator", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth2.py#L560-L590
[ "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", "=", "server", ".", "create_revocation_response", "(", "uri", ",", "headers", "=", "headers", ",", "body", "=", "body", ",", "http_method", "=", "http_method", ")", "return", "create_response", "(", "*", "ret", ")", "return", "decorated" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth2Provider.require_oauth
Protect resource with specified scopes.
flask_oauthlib/provider/oauth2.py
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
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
[ "Protect", "resource", "with", "specified", "scopes", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth2.py#L592-L615
[ "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", ")", "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" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth2RequestValidator._get_client_creds_from_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
flask_oauthlib/provider/oauth2.py
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
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
[ "Return", "client", "credentials", "based", "on", "the", "current", "request", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth2.py#L636-L661
[ "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 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" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth2RequestValidator.client_authentication_required
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
flask_oauthlib/provider/oauth2.py
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
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
[ "Determine", "if", "client", "authentication", "is", "required", "for", "current", "request", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth2.py#L663-L691
[ "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'", ",", "'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" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth2RequestValidator.authenticate_client
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
flask_oauthlib/provider/oauth2.py
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
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", "itself", "in", "other", "means", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth2.py#L693-L717
[ "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", "=", "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" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth2RequestValidator.authenticate_client_id
Authenticate a non-confidential client. :param client_id: Client ID of the non-confidential client :param request: The Request object passed by oauthlib
flask_oauthlib/provider/oauth2.py
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
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
[ "Authenticate", "a", "non", "-", "confidential", "client", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth2.py#L719-L736
[ "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.'", ")", "return", "False", "# attach client on request for convenience", "request", ".", "client", "=", "client", "return", "True" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth2RequestValidator.confirm_redirect_uri
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.
flask_oauthlib/provider/oauth2.py
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
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
[ "Ensure", "client", "is", "authorized", "to", "redirect", "to", "the", "redirect_uri", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth2.py#L738-L764
[ "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", "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" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth2RequestValidator.get_original_scopes
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.
flask_oauthlib/provider/oauth2.py
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
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
[ "Get", "the", "list", "of", "scopes", "associated", "with", "the", "refresh", "token", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth2.py#L766-L775
[ "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" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth2RequestValidator.confirm_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 ``get_original_scopes`` to determine the scope of the refreshed token.
flask_oauthlib/provider/oauth2.py
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)
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)
[ "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", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth2.py#L777-L792
[ "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", "(", "scopes", ")" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth2RequestValidator.get_default_redirect_uri
Default redirect_uri for the given client.
flask_oauthlib/provider/oauth2.py
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
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", "redirect_uri", "for", "the", "given", "client", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth2.py#L794-L799
[ "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" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth2RequestValidator.get_default_scopes
Default scopes for the given client.
flask_oauthlib/provider/oauth2.py
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 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
[ "Default", "scopes", "for", "the", "given", "client", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth2.py#L801-L806
[ "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" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth2RequestValidator.invalidate_authorization_code
Invalidate an authorization code after use. We keep the temporary code in a grant, which has a `delete` function to destroy itself.
flask_oauthlib/provider/oauth2.py
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()
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()
[ "Invalidate", "an", "authorization", "code", "after", "use", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth2.py#L808-L818
[ "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", "(", ")" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth2RequestValidator.save_authorization_code
Persist the authorization code.
flask_oauthlib/provider/oauth2.py
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
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", "authorization", "code", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth2.py#L820-L829
[ "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" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth2RequestValidator.save_bearer_token
Persist the Bearer token.
flask_oauthlib/provider/oauth2.py
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 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
[ "Persist", "the", "Bearer", "token", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth2.py#L831-L835
[ "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" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth2RequestValidator.validate_bearer_token
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
flask_oauthlib/provider/oauth2.py
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
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
[ "Validate", "access", "token", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth2.py#L837-L881
[ "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", "# 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" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth2RequestValidator.validate_client_id
Ensure client_id belong to a valid and active client.
flask_oauthlib/provider/oauth2.py
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
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", "client_id", "belong", "to", "a", "valid", "and", "active", "client", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth2.py#L883-L891
[ "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", ":", "# attach client to request object", "request", ".", "client", "=", "client", "return", "True", "return", "False" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth2RequestValidator.validate_code
Ensure the grant code is valid.
flask_oauthlib/provider/oauth2.py
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
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", "grant", "code", "is", "valid", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth2.py#L893-L911
[ "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", "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" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth2RequestValidator.validate_grant_type
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`.
flask_oauthlib/provider/oauth2.py
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
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", "the", "client", "is", "authorized", "to", "use", "the", "grant", "type", "requested", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth2.py#L913-L949
[ "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'", ",", ")", "# 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" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth2RequestValidator.validate_redirect_uri
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.
flask_oauthlib/provider/oauth2.py
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
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", "client", "is", "authorized", "to", "redirect", "to", "the", "redirect_uri", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth2.py#L951-L964
[ "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" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth2RequestValidator.validate_refresh_token
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.
flask_oauthlib/provider/oauth2.py
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
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", "the", "token", "is", "valid", "and", "belongs", "to", "the", "client" ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth2.py#L966-L982
[ "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", ":", "# Make sure the request object contains user and client_id", "request", ".", "client_id", "=", "token", ".", "client_id", "request", ".", "user", "=", "token", ".", "user", "return", "True", "return", "False" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth2RequestValidator.validate_response_type
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.
flask_oauthlib/provider/oauth2.py
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
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", "client", "is", "authorized", "to", "use", "the", "response", "type", "requested", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth2.py#L984-L997
[ "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" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth2RequestValidator.validate_scopes
Ensure the client is authorized access to requested scopes.
flask_oauthlib/provider/oauth2.py
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))
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", "client", "is", "authorized", "access", "to", "requested", "scopes", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth2.py#L999-L1004
[ "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", ")", ")" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth2RequestValidator.validate_user
Ensure the username and password is valid. Attach user object on request for later using.
flask_oauthlib/provider/oauth2.py
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
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
[ "Ensure", "the", "username", "and", "password", "is", "valid", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth2.py#L1006-L1022
[ "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", "(", "'Password credential authorization is disabled.'", ")", "return", "False" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth2RequestValidator.revoke_token
Revoke an access or refresh token.
flask_oauthlib/provider/oauth2.py
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
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
[ "Revoke", "an", "access", "or", "refresh", "token", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/provider/oauth2.py#L1024-L1043
[ "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", "tok", ".", "delete", "(", ")", "return", "True", "msg", "=", "'Invalid token supplied.'", "log", ".", "debug", "(", "msg", ")", "request", ".", "error_message", "=", "msg", "return", "False" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
json_to_dict
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.
example/qq.py
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
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
[ "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", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/example/qq.py#L28-L42
[ "def", "json_to_dict", "(", "x", ")", ":", "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" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
update_qq_api_request_data
Update some required parameters for OAuth2.0 API calls
example/qq.py
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 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
[ "Update", "some", "required", "parameters", "for", "OAuth2", ".", "0", "API", "calls" ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/example/qq.py#L45-L53
[ "def", "update_qq_api_request_data", "(", "data", "=", "{", "}", ")", ":", "defaults", "=", "{", "'openid'", ":", "session", ".", "get", "(", "'qq_openid'", ")", ",", "'access_token'", ":", "session", ".", "get", "(", "'qq_token'", ")", "[", "0", "]", ",", "'oauth_consumer_key'", ":", "QQ_APP_ID", ",", "}", "defaults", ".", "update", "(", "data", ")", "return", "defaults" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
convert_keys_to_string
Recursively converts dictionary keys to strings.
example/qq.py
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 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())
[ "Recursively", "converts", "dictionary", "keys", "to", "strings", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/example/qq.py#L107-L111
[ "def", "convert_keys_to_string", "(", "dictionary", ")", ":", "if", "not", "isinstance", "(", "dictionary", ",", "dict", ")", ":", "return", "dictionary", "return", "dict", "(", "(", "str", "(", "k", ")", ",", "convert_keys_to_string", "(", "v", ")", ")", "for", "k", ",", "v", "in", "dictionary", ".", "items", "(", ")", ")" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
change_weibo_header
Since weibo is a rubbish server, it does not follow the standard, we need to change the authorization header for it.
flask_oauthlib/contrib/apps.py
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
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
[ "Since", "weibo", "is", "a", "rubbish", "server", "it", "does", "not", "follow", "the", "standard", "we", "need", "to", "change", "the", "authorization", "header", "for", "it", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/contrib/apps.py#L191-L198
[ "def", "change_weibo_header", "(", "uri", ",", "headers", ",", "body", ")", ":", "auth", "=", "headers", ".", "get", "(", "'Authorization'", ")", "if", "auth", ":", "auth", "=", "auth", ".", "replace", "(", "'Bearer'", ",", "'OAuth2'", ")", "headers", "[", "'Authorization'", "]", "=", "auth", "return", "uri", ",", "headers", ",", "body" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
RemoteAppFactory.register_to
Creates a remote app and registers it.
flask_oauthlib/contrib/apps.py
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 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", "and", "registers", "it", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/contrib/apps.py#L57-L61
[ "def", "register_to", "(", "self", ",", "oauth", ",", "name", "=", "None", ",", "*", "*", "kwargs", ")", ":", "kwargs", "=", "self", ".", "_process_kwargs", "(", "name", "=", "(", "name", "or", "self", ".", "default_name", ")", ",", "*", "*", "kwargs", ")", "return", "oauth", ".", "remote_app", "(", "*", "*", "kwargs", ")" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
RemoteAppFactory.create
Creates a remote app only.
flask_oauthlib/contrib/apps.py
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 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)
[ "Creates", "a", "remote", "app", "only", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/contrib/apps.py#L63-L67
[ "def", "create", "(", "self", ",", "oauth", ",", "*", "*", "kwargs", ")", ":", "kwargs", "=", "self", ".", "_process_kwargs", "(", "name", "=", "self", ".", "default_name", ",", "register", "=", "False", ",", "*", "*", "kwargs", ")", "return", "oauth", ".", "remote_app", "(", "*", "*", "kwargs", ")" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
_get_uri_from_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
flask_oauthlib/utils.py
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
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
[ "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" ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/utils.py#L8-L17
[ "def", "_get_uri_from_request", "(", "request", ")", ":", "uri", "=", "request", ".", "base_url", "if", "request", ".", "query_string", ":", "uri", "+=", "'?'", "+", "request", ".", "query_string", ".", "decode", "(", "'utf-8'", ")", "return", "uri" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
extract_params
Extract request params.
flask_oauthlib/utils.py
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
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
[ "Extract", "request", "params", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/utils.py#L20-L37
[ "def", "extract_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" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
to_bytes
Make sure text is bytes type.
flask_oauthlib/utils.py
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 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
[ "Make", "sure", "text", "is", "bytes", "type", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/utils.py#L40-L46
[ "def", "to_bytes", "(", "text", ",", "encoding", "=", "'utf-8'", ")", ":", "if", "not", "text", ":", "return", "text", "if", "not", "isinstance", "(", "text", ",", "bytes_type", ")", ":", "text", "=", "text", ".", "encode", "(", "encoding", ")", "return", "text" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
decode_base64
Decode base64 string.
flask_oauthlib/utils.py
def decode_base64(text, encoding='utf-8'): """Decode base64 string.""" text = to_bytes(text, encoding) return to_unicode(base64.b64decode(text), encoding)
def decode_base64(text, encoding='utf-8'): """Decode base64 string.""" text = to_bytes(text, encoding) return to_unicode(base64.b64decode(text), encoding)
[ "Decode", "base64", "string", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/utils.py#L49-L52
[ "def", "decode_base64", "(", "text", ",", "encoding", "=", "'utf-8'", ")", ":", "text", "=", "to_bytes", "(", "text", ",", "encoding", ")", "return", "to_unicode", "(", "base64", ".", "b64decode", "(", "text", ")", ",", "encoding", ")" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
create_response
Create response class for Flask.
flask_oauthlib/utils.py
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 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
[ "Create", "response", "class", "for", "Flask", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/utils.py#L55-L62
[ "def", "create_response", "(", "headers", ",", "body", ",", "status", ")", ":", "response", "=", "Response", "(", "body", "or", "''", ")", "for", "k", ",", "v", "in", "headers", ".", "items", "(", ")", ":", "response", ".", "headers", "[", "str", "(", "k", ")", "]", "=", "v", "response", ".", "status_code", "=", "status", "return", "response" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
Cache._simple
Returns a :class:`SimpleCache` instance .. warning:: This cache system might not be thread safe. Use with caution.
flask_oauthlib/contrib/cache.py
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 _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", ":", "SimpleCache", "instance" ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/contrib/cache.py#L50-L58
[ "def", "_simple", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "update", "(", "dict", "(", "threshold", "=", "self", ".", "_config", "(", "'threshold'", ",", "500", ")", ")", ")", "return", "SimpleCache", "(", "*", "*", "kwargs", ")" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
Cache._memcache
Returns a :class:`MemcachedCache` instance
flask_oauthlib/contrib/cache.py
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 _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", ":", "MemcachedCache", "instance" ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/contrib/cache.py#L60-L66
[ "def", "_memcache", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "update", "(", "dict", "(", "servers", "=", "self", ".", "_config", "(", "'MEMCACHED_SERVERS'", ",", "None", ")", ",", "key_prefix", "=", "self", ".", "_config", "(", "'key_prefix'", ",", "None", ")", ",", ")", ")", "return", "MemcachedCache", "(", "*", "*", "kwargs", ")" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
Cache._redis
Returns a :class:`RedisCache` instance
flask_oauthlib/contrib/cache.py
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)
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", ":", "RedisCache", "instance" ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/contrib/cache.py#L68-L77
[ "def", "_redis", "(", "self", ",", "*", "*", "kwargs", ")", ":", "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", ")" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
Cache._filesystem
Returns a :class:`FileSystemCache` instance
flask_oauthlib/contrib/cache.py
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 _filesystem(self, **kwargs): """Returns a :class:`FileSystemCache` instance""" kwargs.update(dict( threshold=self._config('threshold', 500), )) return FileSystemCache(self._config('dir', None), **kwargs)
[ "Returns", "a", ":", "class", ":", "FileSystemCache", "instance" ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/contrib/cache.py#L79-L84
[ "def", "_filesystem", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "update", "(", "dict", "(", "threshold", "=", "self", ".", "_config", "(", "'threshold'", ",", "500", ")", ",", ")", ")", "return", "FileSystemCache", "(", "self", ".", "_config", "(", "'dir'", ",", "None", ")", ",", "*", "*", "kwargs", ")" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
get_cached_clients
Gets the cached clients dictionary in current context.
flask_oauthlib/contrib/client/__init__.py
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 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
[ "Gets", "the", "cached", "clients", "dictionary", "in", "current", "context", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/contrib/client/__init__.py#L96-L101
[ "def", "get_cached_clients", "(", ")", ":", "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" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth.add_remote_app
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.
flask_oauthlib/contrib/client/__init__.py
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
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
[ "Adds", "remote", "application", "and", "applies", "custom", "attributes", "on", "it", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/contrib/client/__init__.py#L34-L55
[ "def", "add_remote_app", "(", "self", ",", "remote_app", ",", "name", "=", "None", ",", "*", "*", "kwargs", ")", ":", "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" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
OAuth.remote_app
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.
flask_oauthlib/contrib/client/__init__.py
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)
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)
[ "Creates", "and", "adds", "new", "remote", "application", "." ]
lepture/flask-oauthlib
python
https://github.com/lepture/flask-oauthlib/blob/9e6f152a5bb360e7496210da21561c3e6d41b0e1/flask_oauthlib/contrib/client/__init__.py#L57-L75
[ "def", "remote_app", "(", "self", ",", "name", ",", "version", "=", "None", ",", "*", "*", "kwargs", ")", ":", "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", ")" ]
9e6f152a5bb360e7496210da21561c3e6d41b0e1
test
Checker_X509_get_pubkey.check_exception
Call the method repeatedly such that it will raise an exception.
leakcheck/crypto.py
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_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", "raise", "an", "exception", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/leakcheck/crypto.py#L24-L33
[ "def", "check_exception", "(", "self", ")", ":", "for", "i", "in", "xrange", "(", "self", ".", "iterations", ")", ":", "cert", "=", "X509", "(", ")", "try", ":", "cert", ".", "get_pubkey", "(", ")", "except", "Error", ":", "pass" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
Checker_X509_get_pubkey.check_success
Call the method repeatedly such that it will return a PKey object.
leakcheck/crypto.py
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()
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", "method", "repeatedly", "such", "that", "it", "will", "return", "a", "PKey", "object", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/leakcheck/crypto.py#L36-L48
[ "def", "check_success", "(", "self", ")", ":", "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", "(", ")" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
Checker_load_privatekey.check_load_privatekey_callback
Call the function with an encrypted PEM and a passphrase callback.
leakcheck/crypto.py
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(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", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/leakcheck/crypto.py#L70-L76
[ "def", "check_load_privatekey_callback", "(", "self", ")", ":", "for", "i", "in", "xrange", "(", "self", ".", "iterations", "*", "10", ")", ":", "load_privatekey", "(", "FILETYPE_PEM", ",", "self", ".", "ENCRYPTED_PEM", ",", "lambda", "*", "args", ":", "\"hello, secret\"", ")" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
Checker_load_privatekey.check_load_privatekey_callback_incorrect
Call the function with an encrypted PEM and a passphrase callback which returns the wrong passphrase.
leakcheck/crypto.py
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
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", "the", "wrong", "passphrase", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/leakcheck/crypto.py#L79-L90
[ "def", "check_load_privatekey_callback_incorrect", "(", "self", ")", ":", "for", "i", "in", "xrange", "(", "self", ".", "iterations", "*", "10", ")", ":", "try", ":", "load_privatekey", "(", "FILETYPE_PEM", ",", "self", ".", "ENCRYPTED_PEM", ",", "lambda", "*", "args", ":", "\"hello, public\"", ")", "except", "Error", ":", "pass" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
Checker_load_privatekey.check_load_privatekey_callback_wrong_type
Call the function with an encrypted PEM and a passphrase callback which returns a non-string.
leakcheck/crypto.py
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
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
[ "Call", "the", "function", "with", "an", "encrypted", "PEM", "and", "a", "passphrase", "callback", "which", "returns", "a", "non", "-", "string", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/leakcheck/crypto.py#L93-L104
[ "def", "check_load_privatekey_callback_wrong_type", "(", "self", ")", ":", "for", "i", "in", "xrange", "(", "self", ".", "iterations", "*", "10", ")", ":", "try", ":", "load_privatekey", "(", "FILETYPE_PEM", ",", "self", ".", "ENCRYPTED_PEM", ",", "lambda", "*", "args", ":", "{", "}", ")", "except", "ValueError", ":", "pass" ]
1fbe064c50fd030948141d7d630673761525b0d0
test
Checker_CRL.check_get_revoked
Create a CRL object with 100 Revoked objects, then call the get_revoked method repeatedly.
leakcheck/crypto.py
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_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()
[ "Create", "a", "CRL", "object", "with", "100", "Revoked", "objects", "then", "call", "the", "get_revoked", "method", "repeatedly", "." ]
pyca/pyopenssl
python
https://github.com/pyca/pyopenssl/blob/1fbe064c50fd030948141d7d630673761525b0d0/leakcheck/crypto.py#L120-L129
[ "def", "check_get_revoked", "(", "self", ")", ":", "crl", "=", "CRL", "(", ")", "for", "i", "in", "xrange", "(", "100", ")", ":", "crl", ".", "add_revoked", "(", "Revoked", "(", ")", ")", "for", "i", "in", "xrange", "(", "self", ".", "iterations", ")", ":", "crl", ".", "get_revoked", "(", ")" ]
1fbe064c50fd030948141d7d630673761525b0d0