apicrud.SessionManager

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

Session Manager - for active user sessions

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

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

  • redis_conn (obj) – connection to redis service

__init__(ttl=None, redis_conn=None)

Methods

__init__([ttl, redis_conn])

create(uid, roles[, key_id])

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

delete(uid, token[, key_id])

Cancel a session

get(uid, token[, arg, key_id])

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

update(uid, token, arg, value[, key_id])

Update a specified session key

create(uid, roles, key_id=None, **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

  • key_id – session key ID for redis (defaults to uid)

  • 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, key_id=None)

Cancel a session

Parameters
  • uid – User ID

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

  • key_id (str) – session key ID for redis

get(uid, token, arg=None, key_id=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)

  • key_id (str) – session key ID for redis (defaults to uid)

Returns

single value or dictionary of all session keys

Return type

dict or str

update(uid, token, arg, value, key_id=None)

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

  • key_id (str) – session key ID for redis (defaults to uid)

Raises

TypeError if uid/token not found in redis