Python Classes¶
-
class
apicrud.
AccessControl
(policy_file=None, model=None)¶ Role-based access control
- Parameters
policy_file (str) – name of the yaml definitions file
model (obj) – a model to be validated for permissions
-
load_rbac
(filename)¶ Read RBAC default policies from rbac.yaml, process any string substitutions, and convert * for re.match()
- Parameters
filename (str) – filename containing RBAC definitions
-
rbac_permissions
(query=None, owner_uid=None, membership=None, id=None, privacy=None)¶ Evaluate an access request for self.auth roles of self.uid in self.resource against defined policies
- Parameters
query (obj) – an existing record (takes precedence over owner_uid)
owner_uid (str) – owner-uid of a record
membership (str) – resource type which defines membership privacy
id (str) – the resource ID if membership is set
- Returns
actions available to principal
- Return type
set
-
with_filter
(query, access='r')¶ Apply RBAC and privacy to a query
- Parameters
query (obj) – a resource query in SQLalchemy
access (str) – one of lrwcd (list, read, write, create, delete)
- Returns
updated SQLalchemy query with filter applied
- Return type
obj
TODO restrictions on contact-read by list-id
-
with_permission
(access, query=None, new_uid=None, membership=None, id=None)¶ Evaluate permission to access an object identified by an open query or new uid. Pass in at least one of the query/uid/eid params
- Parameters
access (str) – one of lrwcd (list, read, write, create, delete)
query (obj) – a resource query by id in SQLalchemy
new_uid (str) – user id of a new record
membership (str) – resource type which defines membership privacy
id (str) – resource ID
- Returns
True if access allowed
- Return type
bool
-
class
apicrud.
AccountSettings
(account_id, db_session=None, uid=None)¶ Account Settings - converts db record to object attributes.
- Parameters
account_id (str) – ID in database of a user’s account
db_session (obj) – a session connected to datbase
uid (str) – User ID
-
property
locale
¶ Returns the language for the uid if specified in the user’s profile
-
class
apicrud.
BasicCRUD
(resource=None, model=None)¶ Controller base class
-
resource
¶ a resource name (endpoint prefix)
- Type
str
-
model
¶ the model corresponding to the resource
- Type
obj
-
static
create
(body, id_prefix='x-')¶ Controller for POST endpoints. This method assigns a new object ID, sets the _created_ timestamp, evaluates user’s permissions, adds a default category_id if the model has this attribute, and inserts a row to the back-end database.
- Parameters
body (dict) – resource fields as defined by openapi.yaml schema
id_prefix (str) – generated objects will be assigned a random 10- to 16-character ID; you can set a unique prefix if desired
- Returns
first element is a dict with the id, second element is response code (201 on success)
- Return type
tuple
-
db_get
(id)¶ Activate a SQLalchemy query object for the specified ID in the current model
- Parameters
id (str) – object ID
- Returns
query object
- Return type
obj
-
static
delete
(ids, force=False)¶ Controller for DELETE endpoints. This method looks for existing records, evaluates user’s permissions, and updates or removes rows in the back-end database.
- Parameters
ids (list of str) – record IDs to be flagged for removal
force (bool) – flag for removal if false; remove data if true
- Returns
first element is a dict with the id, second element is response code (200 on success)
- Return type
tuple
-
static
find
(**kwargs)¶ Find records which match query parameters passed from connexion by name, in a dictionary that also includes user and token info
- Parameters
cursor_next (str) – pagination token to fetch subsequent records
filter (dict) – field/value pairs to query (simple queries only, with string or list matching; or * for any)
limit (int) – max records to fetch
offset (int) – old-style pagination starting offset
sort (str) – <field>[:{asc|desc}]
status (str) – value is added to filter
- Returns
items (list), count(int), cursor_next (str)
- Return type
dict
-
static
get
(id)¶ Controller for GET endpoints. This method evaluates privacy settings against the user’s permissions, looks up category, owner and geocode values, and fetches the object from back-end database.
- Parameters
id (str) – ID of the desired resource
- Returns
first element is a dict with the object or error message, second element is response code (200 on success)
- Return type
tuple
-
static
update
(id, body, access='u')¶ Controller for PUT endpoints. This method looks for an existing record, evaluates user’s permissions, and updates the row in the back-end database.
- Parameters
body (dict) – fields to be updated
access (str) – access-level required for RBAC evaluation
- Returns
first element is a dict with the id, second element is response code (200 on success)
- Return type
dict
-
static
update_contact
(id, body)¶ This is a special-case function for the contact-update resource
validate sms carrier
keep person identity in sync with primary contact
- Parameters
id (str) – resource ID
body (dict) – as defined in openapi.yaml
-
-
class
apicrud.
Grants
(db_session=None, ttl=None)¶ Account usage limits
-
db_session
¶ existing db session
- Type
obj
-
ttl
¶ how long to cache a grant in memory
- Type
int
-
crud_get
(crud_results, id)¶ Process results from BasicCRUD.get() for grants endpoint. If the id is found in database, perform the standard CRUD get(). Otherwise, look for a hybrid id in form uid:grant and return the cached Grant value.
- Parameters
crud_results (tuple) – preliminary response
name (str) – name filter, if specified
-
find
(crud_results, **kwargs)¶ Process results from BasicCRUD.find() for grants endpoint
- Parameters
crud_results (tuple) – preliminary response
name (str) – name filter, if specified
-
get
(name, uid=None)¶ Get the cached value of a named grant, if it hasn’t expired Note that if any grant assigned to a uid expires before others, the earliest expiration applies to all the uid’s grants
- Parameters
name (str) – name of a grant, as defined in service config
uid (str) – user ID
- Returns
granted limit
- Return type
str
-
load_defaults
(defaults)¶ Load default values from a dict of keyword: value pairs
- Parameters
defaults (dict) – new defaults
-
uncache
(uid)¶ Remove grants from cache, any time a user’s status changes
- Parameters
uid (str) – user ID
-
-
class
apicrud.
ServiceConfig
(file=None, models=None, reset=False, **kwargs)¶ Service config for flask application
- Parameters
file (str) – path of a YAML file defining override values
models (obj) – sqlalchemy db models
reset (boolean) – reset cached values (for unit tests)
**kwargs – key=value pair arguments to override values
- Raises
AttributeError if invalid specification –
-
set
(key, value)¶ Set a single value
- Parameters
key (str) –
- new value (value) –
-
class
apicrud.
ServiceRegistry
(ttl=None, redis_conn=None)¶ Service registry
-
db_session
¶ existing db session
- Type
obj
-
ttl
¶ how long to cache instance’s registration
- Type
int
-
redis_conn
¶ connection to redis
- Type
obj
-
find
(service_name=None)¶ Finds one or all services
- Parameters
service_name (str) – a service, or None for all
- Returns
- dict - instances (list of registered services)
url_map (public url for each top-level resource)
-
register
(resource_endpoints, service_name=None, instance_id='build-11819309-project-613164-apicrud', tcp_port=None)¶ register an instance serving a list of endpoints
- Parameters
resource_endpoints (list of str) – controller endpoints served
service_name (str) – microservice name
instance_id (str) – unique ID of instance
tcp_port (int) – port number of service
-
static
update
()¶ background function to update registration at the defined interval from local memory cache, until the instance terminates.
-
-
class
apicrud.
SessionAuth
(func_send=None)¶ Session Authorization
- Parameters
func_send (function) – name of function for sending message
-
account_login
(username, password, roles_from=None)¶ Log in with username or email
- Parameters
username (str) – account name or email
password (str) – credential
identity_from (obj) – model from which to find contact info
roles_from (obj) – model for which to look up authorizations
- Returns
Fields include jwt_token (contains uid / account ID), ID of entry in settings database, and a sub-dictionary with mapping of endpoints registered to microservices
- Return type
dict
-
change_password
(uid, new_password, reset_token, old_password=None, verify_password=None)¶ Update a user’s password, applying complexity rules; must specify either the old password or a reset token
- Parameters
uid (str) – User ID
new_password (str) – the new passphrase
reset_token (str) – a token retrieved from Confirmation.request
old_password (str) – the old passphrase
- Returns
dict with account_id/uid/username, http response
- Return type
tuple
-
forgot_password
(identity, username, template='password_reset')¶ Trigger Confirmation.request; specify either the username or email address
- Parameters
identity (str) – account’s primary identity, usually an email
username (str) – account’s username
template (str) – template for message (confirming new user)
- Returns
the Confirmation.request dict and http response
- Return type
tuple
-
get_roles
(uid, member_model, resource=None, id=None)¶ Get roles that match uid / id for a resource Each is in the form <resource>-<id>-<privacy level>
- Parameters
uid (str) – User ID
member_model (obj) – the DB model that defines membership in resource
resource (str) – the resource that defines privacy (e.g. list)
id (str) – ID of the resource (omit if all are desired)
- Returns
authorized roles
- Return type
list of str
-
register
(identity, username, name, template='confirm_new')¶ Register a new account: create related records in database and send confirmation token to new user
TODO caller still has to invoke account-create function to generate record in accounts table
- Parameters
identity (str) – account’s primary identity, usually an email
username (str) – account’s username
name (str) – name
template (str) – template for message (confirming new user)
- Returns
the Confirmation.request dict and http response
- Return type
tuple
-
update_auth
(member_model, id, resource=None, force=False)¶ Check current access, update if recently changed
- Parameters
member_model (obj) – model (e.g. Guest) which defines membership in resource
id (str) – resource id of parent resource
resource (str) – parent resource for which membership should be checked
force (bool) – perform update regardless of logged-in permissions
-
class
apicrud.
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
access.py |
|
account_settings.py |
|
aes_encrypt.py |
|
basic_crud.py |
|
const.py |
|
database.py |
|
geocode.py |
|
grants.py |
|
health.py |
|
service_config.py |
|
service_registry.py |
|
session_auth |
|
session_manager.py |
|
utilities.py |