Classes¶
authomatic.Authomatic |
Encapsulates all the functionality of this package. |
authomatic.core.User |
Provides unified interface to selected user info returned by different providers. |
authomatic.core.Credentials |
Contains all necessary information to fetch user’s protected resources. |
authomatic.core.LoginResult |
Result of the authomatic.login() function. |
authomatic.core.Response |
Wraps httplib.HTTPResponse and adds. |
authomatic.core.UserInfoResponse |
Inherits from Response, adds user attribute. |
authomatic.core.Future |
Represents an activity run in a separate thread. |
-
class
authomatic.Authomatic(config, secret, session_max_age=600, secure_cookie=False, session=None, session_save_method=None, report_errors=True, debug=False, logging_level=20, prefix='authomatic', logger=None)[source]¶ Encapsulates all the functionality of this package.
Parameters: - config (dict) – Config
- secret (str) – A secret string that will be used as the key for signing
Sessioncookie and as a salt by CSRF token generation. - session_max_age – Maximum allowed age of
Sessioncookie nonce in seconds. - secure_cookie (bool) – If
TruetheSessioncookie will be saved witSecureattribute. - session – Custom dictionary-like session implementation.
- session_save_method (callable) – A method of the supplied session or any mechanism that saves the session data and cookie.
- report_errors (bool) – If
Trueexceptions encountered during the login procedure will be caught and reported in theLoginResult.errorattribute. Default isTrue. - debug (bool) – If
Truetraceback of exceptions will be written to response. Default isFalse. - logging_level (int) – The logging level threshold for the default logger as specified in
the standard Python
logging library.
This setting is ignored when
loggeris set. Default islogging.INFO. - prefix (str) – Prefix used as the
Sessioncookie name. - logger – A
logging.loggerinstance.
-
login(adapter, provider_name, callback=None, session=None, session_saver=None, **kwargs)[source]¶ If
provider_namespecified, launches the login procedure for corresponding provider and returnsLoginResult.If
provider_nameis empty, acts likeAuthomatic.backend().Warning
The method redirects the user to the provider which in turn redirects him/her back to the request handler where it has been called.
Parameters: - provider_name (str) – Name of the provider as specified in the keys of the Config.
- callback (callable) – If specified the method will call the callback with
LoginResultpassed as argument and will return nothing. - report_errors (bool) –
Note
Accepts additional keyword arguments that will be passed to provider constructor.
Returns: LoginResult
-
credentials(credentials)[source]¶ Deserializes credentials.
Parameters: credentials – Credentials serialized with Credentials.serialize()orCredentialsinstance.Returns: Credentials
-
access(credentials, url, params=None, method='GET', headers=None, body='', max_redirects=5, content_parser=None)[source]¶ Accesses protected resource on behalf of the user.
Parameters: - credentials – The user’s
Credentials(serialized or normal). - url (str) – The protected resource URL.
- method (str) – HTTP method of the request.
- headers (dict) – HTTP headers of the request.
- body (str) – Body of
POST,PUTandPATCHrequests. - max_redirects (int) – Maximum number of HTTP redirects to follow.
- content_parser (function) – A function to be used to parse the
Response.datafromResponse.content.
Returns: - credentials – The user’s
-
async_access(*args, **kwargs)[source]¶ Same as
Authomatic.access()but runs asynchronously in a separate thread.Warning
The internal implementation of the future pattern is quite naive. Use with caution!
Returns: Futureinstance representing the separate thread.
-
request_elements(credentials=None, url=None, method='GET', params=None, headers=None, body='', json_input=None, return_json=False)[source]¶ Creates request elements for accessing protected resource of a user. Required arguments are
credentialsandurl. You can passcredentials,url,method, andparamsas a JSON object.Parameters: - credentials – The user’s credentials (can be serialized).
- url (str) – The url of the protected resource.
- method (str) – The HTTP method of the request.
- params (dict) – Dictionary of request parameters.
- headers (dict) – Dictionary of request headers.
- body (str) – Body of
POST,PUTandPATCHrequests. - json_input (str) –
you can pass
credentials,url,method,paramsandheadersin a JSON object. Values from arguments will be used for missing properties.{ "credentials": "###", "url": "https://example.com/api", "method": "POST", "params": { "foo": "bar" }, "headers": { "baz": "bing", "Authorization": "Bearer ###" }, "body": "Foo bar baz bing." }
- return_json (bool) –
if
Truethe function returns a json object.{ "url": "https://example.com/api", "method": "POST", "params": { "access_token": "###", "foo": "bar" }, "headers": { "baz": "bing", "Authorization": "Bearer ###" }, "body": "Foo bar baz bing." }
Returns: RequestElementsor JSON string.
-
backend(adapter)[source]¶ Converts a request handler to a JSON backend which you can use with authomatic.js.
Just call it inside a request handler like this:
class JSONHandler(webapp2.RequestHandler): def get(self): authomatic.backend(Webapp2Adapter(self))
Parameters: adapter – The only argument is an adapter. The request handler will now accept these request parameters:
Parameters: - type (str) – Type of the request. Either
auto,fetchorelements. Default isauto. - credentials (str) – Serialized
Credentials. - url (str) – URL of the protected resource request.
- method (str) – HTTP method of the protected resource request.
- body (str) – HTTP body of the protected resource request.
- params (JSON) – HTTP params of the protected resource request as a JSON object.
- headers (JSON) – HTTP headers of the protected resource request as a JSON object.
- json (JSON) –
You can pass all of the aforementioned params except
typein a JSON object.{ "credentials": "######", "url": "https://example.com", "method": "POST", "params": {"foo": "bar"}, "headers": {"baz": "bing"}, "body": "the body of the request" }
Depending on the
typeparam, the handler will either write a JSON object with request elements to the response, and add anAuthomatic-Response-To: elementsresponse header, …{ "url": "https://example.com/api", "method": "POST", "params": { "access_token": "###", "foo": "bar" }, "headers": { "baz": "bing", "Authorization": "Bearer ###" } }
… or make a fetch to the protected resource and forward it’s response content, status and headers with an additional
Authomatic-Response-To: fetchheader to the response.Warning
The backend will not work if you write anything to the response in the handler!
- type (str) – Type of the request. Either
-
class
authomatic.core.Future(func, *args, **kwargs)[source]¶ Represents an activity run in a separate thread. Subclasses the standard library
threading.Threadand addsget_resultmethod.Warning
The internal implementation of the future pattern is quite naive. Use with caution!
Parameters: func (callable) – The function to be run in separate thread. Calls
funcin separate thread and returns immediately. Accepts arbitrary positional and keyword arguments which will be passed tofunc.-
run()[source]¶ Method representing the thread’s activity.
You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.
-
-
class
authomatic.core.User(provider, **kwargs)[source]¶ Provides unified interface to selected user info returned by different providers.
Note
The value format may vary across providers.
-
credentials= None¶ An
Credentialsinstance.
-
data= None¶ A
dictcontaining all the user information returned by the provider. The structure differs across providers.
-
content= None¶ The
Response.contentof the request made to update the user.
-
gae_user= None¶ Instance of the Google App Engine Users API User class. Only present when using the
authomatic.providers.gaeopenid.GAEOpenIDprovider.
-
update()[source]¶ Updates the user info by fetching the provider’s user info URL.
Returns: Updated instance of this class.
-
-
class
authomatic.core.Credentials(config, **kwargs)[source]¶ Contains all necessary information to fetch user’s protected resources.
-
provider_class= None¶ classProvider class.
-
expire_in¶
-
expiration_date¶ Expiration date as
datetime.datetimeorNoneif credentials never expire.
-
valid¶ Trueif credentials are valid,Falseif expired.
-
expire_soon(seconds)[source]¶ Returns
Trueif credentials expire sooner than specified.Parameters: seconds (int) – Number of seconds. Returns: Trueif credentials expire sooner than specified, elseFalse.
-
refresh(force=False, soon=86400)[source]¶ Refreshes the credentials only if the provider supports it and if it will expire in less than one day. It does nothing in other cases.
Note
The credentials will be refreshed only if it gives sense i.e. only OAuth 2.0 has the notion of credentials refreshment/extension. And there are also differences across providers e.g. Google supports refreshment only if there is a
refresh_tokenin the credentials and that in turn is present only if theaccess_typeparameter was set toofflinein the user authorization request.Parameters:
-
async_refresh(*args, **kwargs)[source]¶ Same as
refresh()but runs asynchronously in a separate thread.Warning
The internal implementation of the future pattern is quite naive. Use with caution!
Returns: Futureinstance representing the separate thread.
-
provider_type_class()[source]¶ Returns the provider class specified in the Config.
Returns: authomatic.providers.BaseProvidersubclass.
-
serialize()[source]¶ Converts the credentials to a percent encoded string to be stored for later use.
Returns: string
-
classmethod
deserialize(config, credentials)[source]¶ A class method which reconstructs credentials created by
serialize(). You can also pass it aCredentialsinstance.Parameters: - config (dict) – The same Config used in the
login()to get the credentials. - credentials (str) –
stringThe serialized credentials orCredentialsinstance.
Returns: - config (dict) – The same Config used in the
-
-
class
authomatic.core.LoginResult(provider)[source]¶ Result of the
authomatic.login()function.-
error= None¶ An instance of the
authomatic.exceptions.BaseErrorsubclass.
-
popup_js(callback_name=None, indent=None, custom=None, stay_open=False)[source]¶ Returns JavaScript that:
- Triggers the
options.onLoginComplete(result, closer)handler set with the authomatic.setup() function of javascript.js. - Calls the JavasScript callback specified by
callback_nameon the opener of the login handler popup and passes it the login result JSON object as first argument and the closer function which you should call in your callback to close the popup.
Parameters: - callback_name (str) – The name of the javascript callback e.g
foo.bar.loginCallbackwill result inwindow.opener.foo.bar.loginCallback(result);in the HTML. - indent (int) – The number of spaces to indent the JSON result object.
If
0or negative, only newlines are added. IfNone, no newlines are added. - custom – Any JSON serializable object that will be passed to the
result.customattribute. - stay_open (str) – If
True, the popup will stay open.
Returns: strwith JavaScript.- Triggers the
-
popup_html(callback_name=None, indent=None, title='Login | {0}', custom=None, stay_open=False)[source]¶ Returns a HTML with JavaScript that:
- Triggers the
options.onLoginComplete(result, closer)handler set with the authomatic.setup() function of javascript.js. - Calls the JavasScript callback specified by
callback_nameon the opener of the login handler popup and passes it the login result JSON object as first argument and the closer function which you should call in your callback to close the popup.
Parameters: - callback_name (str) – The name of the javascript callback e.g
foo.bar.loginCallbackwill result inwindow.opener.foo.bar.loginCallback(result);in the HTML. - indent (int) – The number of spaces to indent the JSON result object.
If
0or negative, only newlines are added. IfNone, no newlines are added. - title (str) – The text of the HTML title. You can use
{0}tag inside, which will be replaced by the provider name. - custom – Any JSON serializable object that will be passed to the
result.customattribute. - stay_open (str) – If
True, the popup will stay open.
Returns: strwith HTML.- Triggers the
-
-
class
authomatic.core.Response(httplib_response, content_parser=None)[source]¶ Wraps
httplib.HTTPResponseand adds.Parameters: - httplib_response – The wrapped
httplib.HTTPResponseinstance. - content_parser (function) – Callable which accepts
contentas argument, parses it and returns the parsed data asdict.
-
msg= None¶ Same as
httplib.HTTPResponse.msg.
-
version= None¶ Same as
httplib.HTTPResponse.version.
-
status= None¶ Same as
httplib.HTTPResponse.status.
-
reason= None¶ Same as
httplib.HTTPResponse.reason.
-
read(amt=None)[source]¶ Same as
httplib.HTTPResponse.read().Parameters: amt –
-
getheader(name, default=None)[source]¶ Same as
httplib.HTTPResponse.getheader().Parameters: - name –
- default –
-
fileno()[source]¶ Same as
httplib.HTTPResponse.fileno().
-
getheaders()[source]¶ Same as
httplib.HTTPResponse.getheaders().
-
content¶ The whole response content.
- httplib_response – The wrapped