apicrud.session_manager

session_manager.py

Session Manager

Each login session is stored as an encrypted JSON dict in redis, indexed by sub:token

created 8-may-2019 by richb@instantlinux.net

Classes

Mutex(lockname[, redis_host, maxwait, ttl, …])

Simple mutex implementation for non-clustered Redis

SessionManager([ttl, redis_conn])

Session Manager - for active user sessions

class apicrud.session_manager.Mutex(lockname, redis_host=None, maxwait=20, ttl=0, redis_conn=None)

Simple mutex implementation for non-clustered Redis

Tried to implement this as inner class to DRY out the init, but … no joy.

Parameters
  • lockname (str) – a unique name for the lock

  • redis_host (str) – IP or DNS name of redis service

  • maxwait (int) – seconds to wait for a lock

  • ttl (int) – seconds to hold lock

  • redis_conn (obj) – existing redis connection

acquire()

Acquire a mutex lock

Raises

TimeoutError – if the resource is unavailable

release()

Release a lock

class apicrud.session_manager.SessionManager(ttl=None, redis_conn=None)

Session Manager - for active user sessions

Parameters
  • ttl (int) – seconds until a session expires

  • redis_conn (obj) – connection to redis service

create(uid, roles, **kwargs)

Create a session, which is an encrypted JSON object with the values defined in https://tools.ietf.org/html/rfc7519 for JWT claim names:

  • exp - expiration time, as integer Unix epoch time

  • iss - a constant JWT_ISSUER

  • jti - JWT ID, the randomly-generated token

  • sub - the uid of a user

We add these:

  • auth - authorized roles

  • any other key=value pairs the caller passes as kwargs

The session automatically expires based on object’s ttl. Part of the jti token is used in redis key, to allow a user to log into multiple sessions. The rest of the token is encrypted, to secure it from replay attack in the event redis traffic is compromised.

Parameters
  • uid – User ID

  • roles – Authorized roles

  • nonce – a unique identifier for the token (random if not specified)

  • ttl – duration of session (defaulted from class init)

Returns

Keys include auth (authorized roles), exp / iss / jti / sub (as above), along with parameters passed into this function

Return type

dict

delete(uid, token)

Cancel a session

Parameters
  • uid – User ID

  • token (str) – The token value passed from create as ‘jti’

get(uid, token, arg=None)

Get one or all key-value pairs stored by session create

Parameters
  • uid (str) – User ID

  • token (str) – The token value passed from create as ‘jti’

  • arg (str) – key of desired value (None to fetch all)

Returns

single value or dictionary of all session keys

Return type

dict or str

update(uid, token, arg, value)

Update a specified session key

Parameters
  • uid – User ID

  • token (str) – The token value passed from create as ‘jti’

  • arg (str) – key to update

  • value (str) – new value for key