Mojo.Auth

The Mojo.Auth modules are designed to make authentication easier in Tornado by providing a model framework, password management, encryption and validation tools.

To accompany the authentication tools, there is also a session management system that makes maintaining persistent sessions easy across requests.

This module also provides a set of Mixins that integrate the authentication and session management functionality and integrate with either the synchronous or asynchronous mongo drivers, see the mixins section to see how this is accomplished.

AuthManager

Mojo.Auth.AuthManager.add_to_group(userObj, groupObj)

Will add a group object to the groups list in the User object. returns a Mojo.Auth.models.User object.

Mojo.Auth.AuthManager.authenticate(userObj, password)

Will check if a user password matches the input to authenticate the user, this will not log them in:

from Mojo.Auth.AuthManager import authenticate

thisUser = Users.find_one({'_id':ObjectId('504e0439a9ee2f04a0835a92'})
authenticated = authenticate(thisUser, password)
if authenticated:
    #Process the login
    ...
else:
    ...

Will return True if passwords matches and False if password doesn’t match.

Authentication in Mojo uses the bcrypt library for encrypting passwords and is a requirement for using the Auth module.

Mojo.Auth.AuthManager.is_member_of(userObj, groupObj)

Will determine is a user is a member of a group. Returns Tru or False

Mojo.Auth.AuthManager.login(userObj)

If you are using the Auth module and want to track login times as part of the userObj, use this to set the appropriate state of the user objects last_login field, can be used in conjunction with Mojo.Auth.Helpers.login_assistant() to round-off the login process:

from Mojo.Auth.AuthManager import login
from Mojo.Auth.Helpers import login_assitant

thisUser = Users.find_one({'_id':ObjectId('504e0439a9ee2f04a0835a92'})

if thisUser:
    is_authenticated = login_assistant(thisUser, password, self) #self in this case is a RequestHandler
    if is_authenticated:
        login(thisUser)             #set the last_login
        thisUser.save()             #save the user
    else:
        ...
Mojo.Auth.AuthManager.make_random_password()

Generates a random string consisting of 8 characters chosen from the uppercase ascii alphabet and digits.

Returns string.

Mojo.Auth.AuthManager.remove_from_group(userObj, groupObj)

Removes a user from the group, returns True if successful, False if the user is not a member of the group

Mojo.Auth.AuthManager.set_password(userObj, new_password)

Sets the user password and returns the user object, the object is not saved to the database. Usage requires bcrypt to be installed alongside Mojo:

from Mojo.Auth.AuthManager import set_password

thisUser = Users.find_one({'_id':ObjectId('504e0439a9ee2f04a0835a92'})
thisUser = set_password(thisUser, 'new-password=string')
thisUser.save() #save the user object to the database.

Helpers

Mojo.Auth.Helpers.login_assistant(thisUser, password, request)

Shortcut function that will perform three things at once:

  1. Checks if the user exists
  2. Authenticates the user against a password using Auth.AuthManager.authenticate()
  3. If authenticated, sets the appropriate session cookie (that is checked by get_current_user() and returns True

Parameters

  • thisUser - Mojo.Auth.models.User object
  • password - string password representation
  • request - RequestHandler object, does not require the Session Mixin to be used.

Usage:

from Mojo.Auth.Helpers import login_assitant

thisUser = Users.find_one({'_id':ObjectId('504e0439a9ee2f04a0835a92'})

if thisUser:
    is_authenticated = login_assistant(thisUser, password, self) #self in this case is a RequestHandler
    if is_authenticated:
        ...
    else:
        ...
Mojo.Auth.Helpers.logout_assistant(request)

Shortcut function to log a user out. Uses Mojo.Auth.SessionManager to set the appropriate session cookie and returns True.

Once called, get_current_user() and curent_user will be returned as None in a RequestHandler.

Auth Models

class Mojo.Auth.models.Group(data=None)

Group definition - consists only of the name of the group, is part of a ListField in the User object

class Mojo.Auth.models.Profile(data=None)

Represents a user profile - currently cannot be extended. Is an embedded document in a User object.

class Mojo.Auth.models.Session(data=None)

The Session object is mainly used as part of the SessionManager class and the SessionMixin mix-in base class.

This should not be manipulated directly, but stores any session information in the session_data database field.

Data stored in session_data is a JSON string that is base64 encoded, user log in flags are not stored in session_data to avoid hitting the database every time current_user is queried in a request.

class Mojo.Auth.models.User(data=None)

Main User model used by the Mojo.Auth modules, consists of multiple fields:

  • username: The username of the user (required)
  • password: The bcrypt encrypted password (required)
  • email: the email address of the user (optional)
  • groups: A list field of Group objects that the user belongs to
  • active: Is the user active, and allowed in?
  • profile: An embedded field that uses the Profile model
  • is_superuser: Flag to indicate super user status (BooleanField)
  • last_login: DateTimeField with last login date/time
  • date_joined: Can be set to when the user joined (DateTimeField)

Session Manager

Mojo.Auth.SessionManager.Reset_session(sessionObj, expiry_days=30, expiry_hours=0, expiry_minutes=0)

Resets an exisitng session - for example, if a user has logged in again, the expiry date needs to be extended to another 30 days. Takes the same parameters as Setup_session():

Paramaters:

  • sessionObj - The session_model to be initialised
  • expiry_days - How long the session shoul last (optional, default is 30 days)
  • expiry_hours - How long the session should last i hours (optional)
  • expiry_minutes - How long the session should last in minutes (optional)
class Mojo.Auth.SessionManager.SessionManager(request_handler)

SessionManager is meant to make it easier to manage sesison cookies and persistent session data by providing a series of methods that can be used to log a user in, log a user out, get all cookie data.

The SessionManager also manages the encoding, decoding, getting and setting of persistent session data and session valididty, it can be used on it’s own or through the SessionMixin base class.

For example, the Mojo.Auth.Helpers.login_assitant function will use a SessionManager class to get and set the cookies that log a uder in and out, while the SessionMixin class will also get and set persistent session data and save it to the database automatically, making sesison manageent easier and more secure.

SessionManager objects take a RequestHandler as an init parameter in order to function:

if thisUser is not None:
    if is_authenticated:
        SessionManager(request)._login(thisUser) #Will make the relevant changes to the cookies.
        return True
    else:
        return False
else:
    return False
_create_new_session(callback=None)

Creates and sets up a new session_model ready for the request.

_decode_session(session_data)

Internal helper function that decodes the session_data attribute of the session_model.

_encode_session(session_data)

Internal helper function that encodes the session_data attribute of the session_model.

_get_session_key(key)

Gets a session value stored in the session model by it’s key. Session data is stored as a base64-encoded JSON string, and so the function will go through a check -> decode -> set -> encode -> return process and get the key value of the session_data of the session_model attribute.

_is_logged_in()

Checks if a user is logged in, will get the session cookies and check the logged_in value to see if it is None returns True or False depending on the outcome.

_is_session_valid()

This queries the session model in the database to check if the session has expired or not - this is not the same as the cookie expiry. Returns True or False

_login(userObj)

Set the secure cookie to log a user in, the valud of logged_in is set to the _id of the User object.

_logout()

Set the secure cookie to log a user out - essentially setting the logged_in session cookie to blank.

_set_session_key(key, value)

Sets a session key to be stored in the session model. Session data is stored as a base64-encoded JSON string, and so the function will go through a check -> decode -> set process and set the session_model attribute of the SesionManager

get_session_cookies()

Returns Mojo-specific cookie data:

  • session_id - the ID used to lookup the session in the database
  • logged_in - the _id of the User model that is currently logged in

Cookie data is returned as a dict

Mojo.Auth.SessionManager.Setup_session(sessionObj, expiry_days=30, expiry_hours=0, expiry_minutes=0)

Helper function that will take a ‘’session_model’’ object and apply the base data to it ready for use in a ‘’RequestHandler’’ or ‘’SessionManager’‘. By default, a session will expire after 30 days.

Paramaters:

  • sessionObj - The session_model to be initialised
  • expiry_days - How long the session shoul last (optional, default is 30 days)
  • expiry_hours - How long the session should last i hours (optional)
  • expiry_minutes - How long the session should last in minutes (optional)

Usage:

from Auth.SessionManager import Setup_session
from Auth.models import Session

new_session = Setup_session(Session())

Mojo.Auth.Mixins

Mixin Modules to help with Authentication and Session management

Read the Docs v: latest
Versions
latest
Downloads
PDF
HTML
Epub
On Read the Docs
Project Home
Builds

Free document hosting provided by Read the Docs.