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
theSession
cookie will be saved witSecure
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 theLoginResult.error
attribute. Default isTrue
. - debug (bool) – If
True
traceback 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
logger
is set. Default islogging.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 returnsLoginResult
.If
provider_name
is 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
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()
orCredentials
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
andPATCH
requests. - max_redirects (int) – Maximum number of HTTP redirects to follow.
- content_parser (function) – A function to be used to parse the
Response.data
fromResponse.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: 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
andurl
. You can passcredentials
,url
,method
, andparams
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
andPATCH
requests. - json_input (str) –
you can pass
credentials
,url
,method
,params
andheaders
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
orelements
. 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
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 anAuthomatic-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!
- 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.Thread
and addsget_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 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
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.
-
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.
-
-
class
authomatic.core.
Credentials
(config, **kwargs)[source]¶ Contains all necessary information to fetch user’s protected resources.
-
provider_class
= None¶ class
Provider class.
-
expire_in
¶
-
expiration_date
¶ Expiration date as
datetime.datetime
orNone
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, 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_token
in the credentials and that in turn is present only if theaccess_type
parameter was set tooffline
in 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: 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 aCredentials
instance.Parameters: - config (dict) – The same Config used in the
login()
to get the credentials. - credentials (str) –
string
The serialized credentials orCredentials
instance.
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.BaseError
subclass.
-
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_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 inwindow.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. IfNone
, 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.- 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_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 inwindow.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. 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.custom
attribute. - stay_open (str) – If
True
, the popup will stay open.
Returns: str
with HTML.- Triggers the
-
-
class
authomatic.core.
Response
(httplib_response, content_parser=None)[source]¶ Wraps
httplib.HTTPResponse
and adds.Parameters: - httplib_response – The wrapped
httplib.HTTPResponse
instance. - content_parser (function) – Callable which accepts
content
as 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