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 Session cookie and as a salt by CSRF token generation.
  • session_max_age – Maximum allowed age of Session cookie nonce in seconds.
  • secure_cookie (bool) – If True the Session cookie will be saved wit Secure attribute.
  • 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 True exceptions encountered during the login procedure will be caught and reported in the LoginResult.error attribute. Default is True.
  • debug (bool) – If True traceback of exceptions will be written to response. Default is False.
  • logging_level (int) – The logging level threshold for the default logger as specified in the standard Python logging library. This setting is ignored when logger is set. Default is logging.INFO.
  • prefix (str) – Prefix used as the Session cookie name.
  • logger – A logging.logger instance.
login(adapter, provider_name, callback=None, session=None, session_saver=None, **kwargs)[source]

If provider_name specified, launches the login procedure for corresponding provider and returns LoginResult.

If provider_name is empty, acts like Authomatic.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 LoginResult passed 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() or Credentials instance.
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, PUT and PATCH requests.
  • max_redirects (int) – Maximum number of HTTP redirects to follow.
  • content_parser (function) – A function to be used to parse the Response.data from Response.content.
Returns:

Response

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:Future instance 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 credentials and url. You can pass credentials, url, method, and params as 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, PUT and PATCH requests.
  • json_input (str) –

    you can pass credentials, url, method, params and headers in 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 True the 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:

RequestElements or 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, fetch or elements. Default is auto.
  • 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 type in 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 type param, the handler will either write a JSON object with request elements to the response, and add an Authomatic-Response-To: elements response 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: fetch header to the response.

Warning

The backend will not work if you write anything to the response in the handler!

class authomatic.core.Future(func, *args, **kwargs)[source]

Represents an activity run in a separate thread. Subclasses the standard library threading.Thread and adds get_result method.

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 func in separate thread and returns immediately. Accepts arbitrary positional and keyword arguments which will be passed to func.

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.

get_result(timeout=None)[source]

Waits for the wrapped func to finish and returns its result.

Note

This will block the calling thread until the func returns.

Parameters:timeoutfloat or None A timeout for the func to return in seconds.
Returns:The result of the wrapped func.
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.

provider = None

A provider instance.

credentials = None

An Credentials instance.

data = None

A dict containing all the user information returned by the provider. The structure differs across providers.

content = None

The Response.content of the request made to update the user.

id = None

str ID assigned to the user by the provider.

username = None

str User name e.g. andrewpipkin.

name = None

str Name e.g. Andrew Pipkin.

first_name = None

str First name e.g. Andrew.

last_name = None

str Last name e.g. Pipkin.

nickname = None

str Nickname e.g. Andy.

str Link URL.

gender = None

str Gender.

timezone = None

str Timezone.

locale = None

str Locale.

email = None

str E-mail.

phone = None

str phone.

picture = None

str Picture URL.

country = None

str Country.

city = None

str City.

location = None

str Geographical location.

postal_code = None

str Postal code.

gae_user = None

Instance of the Google App Engine Users API User class. Only present when using the authomatic.providers.gaeopenid.GAEOpenID provider.

update()[source]

Updates the user info by fetching the provider’s user info URL.

Returns:Updated instance of this class.
async_update()[source]

Same as update() but runs asynchronously in a separate thread.

Warning

The internal implementation of the future pattern is quite naive. Use with caution!

Returns:Future instance representing the separate thread.
to_dict()[source]

Converts the User instance to a dict.

Returns:dict
class authomatic.core.Credentials(config, **kwargs)[source]

Contains all necessary information to fetch user’s protected resources.

config = None

dict Config.

token = None

str User access token.

token_type = None

str Access token type.

refresh_token = None

str Refresh token.

token_secret = None

str Access token secret.

provider_name = None

str Provider name specified in the Config.

provider_id = None

str Provider short name specified in the Config.

provider_class = None

class Provider class.

consumer_key = None

str Consumer key specified in the Config.

consumer_secret = None

str Consumer secret specified in the Config.

expire_in
expiration_time

int Expiration date as UNIX timestamp.

expiration_date

Expiration date as datetime.datetime or None if credentials never expire.

valid

True if credentials are valid, False if expired.

expire_soon(seconds)[source]

Returns True if credentials expire sooner than specified.

Parameters:seconds (int) – Number of seconds.
Returns:True if credentials expire sooner than specified, else False.
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_token in the credentials and that in turn is present only if the access_type parameter was set to offline in the user authorization request.

Parameters:
  • force (bool) – If True the credentials will be refreshed even if they won’t expire soon.
  • soon (int) – Number of seconds specifying what means soon.
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:Future instance representing the separate thread.
provider_type_class()[source]

Returns the provider class specified in the Config.

Returns:authomatic.providers.BaseProvider subclass.
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 a Credentials instance.

Parameters:
  • config (dict) – The same Config used in the login() to get the credentials.
  • credentials (str) – string The serialized credentials or Credentials instance.
Returns:

Credentials

class authomatic.core.LoginResult(provider)[source]

Result of the authomatic.login() function.

provider = None

A provider instance.

error = None

An instance of the authomatic.exceptions.BaseError subclass.

popup_js(callback_name=None, indent=None, custom=None, stay_open=False)[source]

Returns JavaScript that:

  1. Triggers the options.onLoginComplete(result, closer) handler set with the authomatic.setup() function of javascript.js.
  2. Calls the JavasScript callback specified by callback_name on 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.loginCallback will result in window.opener.foo.bar.loginCallback(result); in the HTML.
  • indent (int) – The number of spaces to indent the JSON result object. If 0 or negative, only newlines are added. If None, no newlines are added.
  • custom – Any JSON serializable object that will be passed to the result.custom attribute.
  • stay_open (str) – If True, the popup will stay open.
Returns:

str with JavaScript.

popup_html(callback_name=None, indent=None, title='Login | {0}', custom=None, stay_open=False)[source]

Returns a HTML with JavaScript that:

  1. Triggers the options.onLoginComplete(result, closer) handler set with the authomatic.setup() function of javascript.js.
  2. Calls the JavasScript callback specified by callback_name on 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.loginCallback will result in window.opener.foo.bar.loginCallback(result); in the HTML.
  • indent (int) – The number of spaces to indent the JSON result object. If 0 or negative, only newlines are added. If None, 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.custom attribute.
  • stay_open (str) – If True, the popup will stay open.
Returns:

str with HTML.

user

A User instance.

class authomatic.core.Response(httplib_response, content_parser=None)[source]

Wraps httplib.HTTPResponse and adds.

content and data attributes.

Parameters:
  • httplib_response – The wrapped httplib.HTTPResponse instance.
  • content_parser (function) – Callable which accepts content as argument, parses it and returns the parsed data as dict.
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().

static is_binary_string(content)[source]

Return true if string is binary data.

content

The whole response content.

data

A dict of data parsed from content.

class authomatic.core.UserInfoResponse(user, *args, **kwargs)[source]

Inherits from Response, adds user attribute.

user = None

User instance.

Fork me on GitHub