API Reference#

Config Submodule#

This SubModule holds different Config Classes needed for the package.

The Following Config Classes are provided:

  • LDAPConfig - for configuring the LDAP Connection.

  • DBConfig - for configuring the DB Connection.

  • AppConfig - for general Settings regarding this Package.

class py_auth_micro.Config.LDAPConfig(address='ldap://127.0.0.1:389', base_dn='ou=User,dc=ad,dc=local', group='allowed_to_login', groups_prefix='API_PERM', domain='ad.local', ca_file=None)#

a Configuration class storing our AD Related config

Variables:
  • address (str) – Server Address.

  • base_dn (str) – Base DN for Users.

  • group (str, optional) – Group that allows the Login itself. Defaults to "allowed_to_login".

  • groups_prefix (str, optional) – Prefix of groups that should be added to the User. Defaults to "API_PERM".

  • domain (str, optional) – The Domain the user should log into. Defaults to 3306.

  • ca_file (str, optional) – Path to the CA File used for ldaps. Defaults to None.

class py_auth_micro.Config.DBConfig(database, user, password, host='127.0.0.1', port=3306, ca_file=None)#

A Class holding our Database configuration

This Class holds our Database Configuration and has a function to get a TortoiseORM compliant connection String or a dictionary

Variables:
  • database (str) – Name of the Database which should be used.

  • user (str) – Username for the Database connection.

  • host (str, optional) – IP or DNS Hostname of the Database Server. Defaults to “127.0.0.1”.

  • port (int, optional) – Port of the Database Server. Defaults to 3306.

  • ca_file (str, optional) – Path to an ca file. If specified it will create an ssl context. Defaults to None.

property sslcontext#

if a ca_file is specified this is an SSLContext else it is None

property connection_string#

Connectionstring for tortoise ORM using the specified Values

Type:

str

to_dict(connection_name='default')#

This Function generates a TortoiseORM compliant Database Connection dict

Pass the Result of this Function into the connections Part of you Tortoise ORM config dict.

Parameters:

connection_name (str, optional) – Name of this Database Connection. Defaults to “default”.

Return type:

dict

Returns:

dict – Tortoise ORM Compliant dictionary Config (at least for the connections section)

class py_auth_micro.Config.AppConfig(id_token_valid_time=1440, access_token_valid_time=5, allow_registration=False, auto_activate_accounts=True, admin_group='admin', default_vhost='prod', group_regex='[a-zA-Z0-9_-]{1,50}', username_regex='[a-zA-Z-_0-9]{4,30}', password_regex='.{4,}', email_regex="[a-zA-Z0-9.!#$%&'*+\\\\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)")#

A class holding information about the general configuration State.

Variables:
  • id_token_valid_time (int) – How long ID Tokens stay valid (in minutes). Defaults to 1440 (24 hours).

  • access_token_valid_time (int) – How long Access Tokens stay valid (in minutes). Defaults to 5 .

  • allow_registration (bool) – Can users register themselfs?. Defaults to False .

  • auto_activate_accounts (bool) – Automatically activate Accounts on creation. Defaults to True .

  • admin_group (str) – Name of the administrator Group. Defaults to admin .

  • default_vhost (str) – Name of the Default VHOST if no VHOST ist given on Login. Defaults to prod .

  • username_regex (str) – Regex to check Usernames with. Defaults to r"[a-zA-Z-_0-9]{4,30}" .

  • password_regex (str) – Regex to check Passwords with. Defaults to r".{4,}" .

  • email_regex (str) – Regex to check Emails with. Defaults to a kinda long regex doing basic checks for emails.

Core Submodule#

Some Core Modules used by other packages from this library.

Provides the Following classes:

  • AuthSource - an enum specifying the Authentification source which should be used for a User.

  • LDAPHelper - a class to simplify the interactions with an LDAP Server

class py_auth_micro.Core.AuthSource(value)#

Describes the Possible Authentification Sources Supported by this Library.

LOCAL = 'LOCAL'#

Is used for authenticating users from the app database

LDAP = 'LDAP'#

Is used for authenticating users from an LDAP as Identity Provider.

KERBEROS = 'KERBEROS'#

Is used for authenticating users via Kerberos.

class py_auth_micro.Core.LDAPHelper(ldap_cfg, username, password)#

A class which helps interacting with an LDAP Server

Warning

While instantiating this class it will bind against the LDAP!

Variables:
  • config (LDAPConfig) – The Configuration to connect to the LDAP.

  • username (str) – Name of the User we want to log in with.

  • password (str) – Password of the user.

property email#

Extracts the Users email after he sucessfully logged in (if he needs to be created in the Database)

get_groups()#

This function will return a list of all relevant Groups.

Return type:

list

Returns:

list – List of Usergroups

login()#

This Function checks if the User has the correct Usergroup to sign in.

Return type:

bool

Returns:

bool – True if the user is allowed to.

Exceptions Submodule#

This submodule Contains Custom Exceptions for the py_auth_micro framework

exception py_auth_micro.Exceptions.AlreadyExists#

An Exception to indicate a given Object already exists and can’t be created again

LoginHandler Submodule#

The LoginHandler Package contains classes for different identity Sources.

Currently there are Classes to work with the following identity Sources:

  • LoginLocal - for a Local Database

  • LoginLDAP - for LDAP

These are choosen automatically by the auth_type field connected to every Users DB Entry. The auth_type is an AuthSource.

async py_auth_micro.LoginHandler.login(username, password, ldap_config=None)#

Function which logs a user in with specified Credentials.

Parameters:
  • username (str) – Username of the User

  • password (str) – Password of the User

  • ldap_config (LDAPConfig, optional) – Configuration for LDAPAuth. Defaults to None.

Raises:

ValueError – If the Credentials are wrong

Return type:

User

Returns:

User – the User mathcing the credentials

class py_auth_micro.LoginHandler.LoginBaseClass(**kwargs)#

Abstract Baseclass for Authenticating Users

This is an abstract baseclass describing all functions needed to be implemented by a generic LoginHandler.

class py_auth_micro.LoginHandler.LoginLDAP(**kwargs)#

Login Provider for LDAP/AD Users

Keyword Arguments:
  • ldap_config (LDAPConfig) – configuration which are important for interacting with the LDAP.

  • username (str) – Username we want to authenticate.

  • password (str) – password for that specified user.

  • user (User) – Database instance of that user.

async login()#

Checks User Credentials against the LDAP/AD.

Note

calls self._sync_groups to sync the LDAP/AD Group memberships of the User with the Database.

Return type:

bool

Returns:

bool – Successfull Login

class py_auth_micro.LoginHandler.LoginLocal(**kwargs)#

Login Handler for Local Users

Variables:
  • username (str) – Username we want to authenticate.

  • password (str) – password for that specified user.

  • user (User) – Database instance of that user.

Returns:

_type_ – _description_

async login()#

Hashes the users password and compares it against the Database.

Note

Uses the bcrypt Module

Return type:

bool

Returns:

bool – Successfull Login

Models Submodule#

This SubModule contains the Database Model Definitions.

Since this package uses Tortoise ORM they are needed!

class py_auth_micro.Models.Token(**kwargs)#

Databse Entity Holding Information around issued Identity Tokens

This Entity holds Information about issued Tokens. The Token ID is supplied in the JWT Header. A User can only have one valid Identity Token Per Time. A Token is bound to a vhost for the Message Broker. The Vhost is not specified in the Identity Token and only gets supplied in the Access Token.

Variables:
  • user (User) – Relation to the User Object.

  • token_id (int) – A Unique ID for our issued Identity Tokens. (kid claim)

  • ip (str) – Ip which is valid for the Token. (Used for verification)

  • valid_until (datetime.datetime) – We store the validity of the Token in the Database as well so we can check the Tokens “exp” claim and in out Database to make sure it did not get forged (Trust me Bro!).

  • last_use (datetime.datetime) – Timestamp of the last Access-Token generation.

  • sign_method (SignMethod) – Method used to sign the ID-Token. (should be checked against the supported Mehtods of the JWTValidator)

  • vhost (str) – Identifies the VHOST of the RabbitMQ Server. For example prod for the Production VHOST and test for the Test VHOST.

async get_id_jwt(jwt_encoder, app_cfg)#

This Function will create a new ID-JWT

Parameters:
  • jwt_encoder (JWTEncoder) – JWTEncoder which should be used to create the Token.

  • app_cfg (AppConfig) – Some misc. Config (important for the Validity duration of the Token)

Return type:

str

Returns:

str – The ID-JWT

async static verify_id_jwt(jwt_validator, id_jwt, ip=None)#

Checks an ID-JWT

Looks up the kid Claim from the Token Header and will validate the Token against the Token described in the Database.

Parameters:
  • jwt_validator (JWTValidator) – JWT-Validator holding Information about our trusted Issuers (should contain ourself)

  • id_jwt (str) – The JWT to verify

  • ip (Optional[str], optional) – IP-Address of the Requesting Party. Defaults to None. (is not checked against if its None)

Raises:

ValueError – Token is not valid or does not Match data in DB.

Returns:

Token – the matched Database Token instance.

async create_access_jwt(jwt_encoder, app_cfg)#

Creates an Access JWT

It’s expected that you verify the ID JWT beforehand with Token.verify_token()

Parameters:

jwt_encoder (JWTEncoder – JWT Encoder to use for creating the token

Return type:

str

Returns:

str – a JWT Token

class py_auth_micro.Models.User(**kwargs)#

Model Representing a User

Variables:
  • username (str) – Name of the User.

  • password_hash (str, optional) – Passwordhash for local Users

  • auth_type (AuthSource) – How to authenticate the User.

  • email (str) – Email address of the User.

  • activated (bool) – User verified his email Address.

async create_id_token(jwt_encoder, app_config, vhost='/', ip='*')#

Creates a Token instance.

Parameters:
  • jwt_encoder (JWTEncoder) – JWTEncoder instance which specifies the SigingMethod.

  • app_config (AppConfig) – AppConfig specifying the Lifetime of the Token.

  • vhost (str, optional) – For which VHost the Token is valid for. Defaults to “/”.

  • ip (str, optional) – IP which the Token is bound to. Defaults to *.

Return type:

Token

Returns:

Token – _description_

async revoke_id_token()#

Revokes the ID-Token by deleting the Database Entity Representing it.

Return type:

bool

Returns:

bool – The Token got revoked.

class py_auth_micro.Models.Group(**kwargs)#

Database Model Representing a Group.

Groups are used for Permission.

Variables:
  • name (str) – Name of the Usergroup

  • users (list[User]) – List of Users in this group

WorkFlows Submodule#

This Package specifies classes which implement the most common workflows.

following workflows are implemented:

  • SessionWorkflow
    • Sign In

    • Sign Out

    • Token Request

  • UserWorkFlow
    • Registration

    • User creation (by Administrators)

    • User deletion

  • GroupWorkfFlow
    • Group creation (by Administrators)

    • Group deletion (by Administrators)

    • Adding User to a Group (by Administrators)

    • Removing User from a Group (by Administrators)

All Function should return Dictionaries which can be easily parsed to JSON

class py_auth_micro.WorkFlows.UserWorkflow(jwt_validator, app_cfg)#

This Helper Class contains all interactions related to Users.

Variables:
  • jwt_validator (JWTValidator) – JWTValidator used to check Tokens with.

  • app_cfg (AppConfig) – Some miscellaneous settings regarding the Application.

async get_all(*, access_token, **kwargs)#

Returns a list of all Usernames.

Parameters:

access_token (str) – Access Token of the Requesting User

Raises:

PermissionError – If the Access Token is invalid

Return type:

dict[str, list[str]]

Returns:

dict – A list of all known Users

async register_user(*, username, password, password_confirm, email, **kwargs)#

This Function is for User Registration

Parameters:
  • username (str) – Username.

  • password (str) – Password of the User

  • password_confirm (str) – Confirmation of the Password

  • email (str) – Email Address of the User

Raises:

ValueError – some Values do not match the specified Regexes or the password confirmation does not match the Password.

Return type:

dict

Returns:

dictresp_code 200 if operation was successfull

async get_user(*, username, access_token=None, **kwargs)#

Returns a dictionary containing Userinformation.

This Function returns more Information if you are the User you are requesting. Even more Info is provided if you are an Administrator

Parameters:
  • username (str) – Username of the User we want the Data from

  • access_token (str, optional) – Access Token of the Requesting User. Defaults to None.

Return type:

dict

Returns:

dict – Dictionary containing User Information

async admin_create_user(*, username, password, email, access_token, **kwargs)#

Lets an administrator create an User

Parameters:
  • username (str) – Username of the new User.

  • password (str) – Password of the new User.

  • email (str) – Email of the new User.

  • access_token (str) – Access Token of the Administrator

Raises:

PermissionError – If the User is not an administrator this gets raised

Return type:

dict

Returns:

dict{"success":True} if operation was successfull

async delete_user(*, access_token, username, **kwargs)#

A user can delete himself or an Administrator can do so as well

Parameters:
  • access_token (str) – Token of the requesting user.

  • username (str) – username of the user to be deleted.

Raises:

PermissionError – If you are not an admin or the User itself

Return type:

dict

Returns:

dict{"success":True} if operation was successfull

async change_user(*, username, access_token, password=None, email=None, activated=None, **kwargs)#

Used to change a User

For Ldap authenticated Users you ca only change the Activation state. The activation State can only be changed by an Administrator.

Important

Changing the users password will invalidate that Users ID-Token!

Parameters:
  • username (str) – username of the User we want to change Information for

  • access_token (str) – Token of the Requesting User.

  • password (str, optional) – New Password. Defaults to None.

  • email (str, optional) – new Email of the User. Defaults to None.

  • activated (bool, optional) – Activation State for the User. Defaults to None.

Raises:
  • PermissionError – Not Authorized to change Userinformation

  • ValueError – Changed Value is invalid

Return type:

dict

Returns:

dict{"success":True} if operation was successfull

class py_auth_micro.WorkFlows.SessionWorkflow(ldap_cfg, jwt_encoder, jwt_validator, app_cfg)#

This Helper Class contains all interactions related to Sessions.

Variables:
  • ldap_cfg (LDAPConfig) – Configuration regarding the LDAP connection.

  • jwt_encoder (JWTEncoder) – JWTEncoder used to create Tokens.

  • jwt_validator (JWTValidator) – JWTValidator used to check Tokens with.

  • app_cfg (AppConfig) – Some miscellaneous settings regarding the Application.

async login(*, username, password, vhost=None, ip='*', **kwargs)#

This Function checks the User Credentials and returns an ID-Token on success.

Parameters:
  • username (str) – Username of the User.

  • password (str) – Password of the User.

  • vhost (str, optional) – VHost for which the ID-Token is valid. Defaults to “test”.

  • ip (str, optional) – IP of the Host making the Request. The ID-Token gets bound to that Request-IP. Defaults to “*”.

Return type:

dict

Returns:

dictresp_data contains the id_token

async logout(*, id_token, ip='*', **kwargs)#

Invalidates the ID-Token given and thereby logs the User out

Parameters:
  • id_token (str) – The ID-Token as JWT

  • ip (str, optional) – IP Address making the Request. Used for validating the ID-Token. Defaults to “*”.

Return type:

dict

Returns:

dictresp_code = 200 if logout was successfull, resp_code = 500 if it was not

async get_access_token(*, id_token, ip='*', **kwargs)#

Verifies an ID-Token and returns an Access-Token

Parameters:
  • id_token (str) – The ID-Token of the Requesting User

  • ip (str, optional) – IP-Address of the requesting User. Defaults to “*”.

Return type:

str

Returns:

dictresp_data contains access_token

class py_auth_micro.WorkFlows.GroupWorkflow(jwt_validator, app_cfg)#

This Helper Class contains all interactions related to Groups and Group Memberships.

Variables:
  • jwt_validator (JWTValidator) – JWTValidator used to check Tokens with.

  • app_cfg (AppConfig) – Some miscellaneous settings regarding the Application.

async get_groups(*, access_token, **kwargs)#

This Function returns a list of all Groups

Parameters:

access_token (str) – Access-Token of the Requesting User.

Return type:

dict

Returns:

dictresp_data contains the key groups which is a list of all groups.

async group_members(*, access_token, groupname, **kwargs)#

This Function returns all Users in a group

Parameters:
  • access_token (str) – Access-Token of the Requesting User.

  • groupname (str) – Name of the Group of which we want the Users.

Raises:
  • ValueError – if Group does not exist.

  • PermissionError – if User is not an admin.

Return type:

list

Returns:

list – List of all usernames in this group.

async create_group(*, access_token, groupname, **kwargs)#

Creates a Group with the specified Name

Parameters:
  • access_token (str) – Access-Token of the Requesting User.

  • groupname (str) – Name of the Group to create.

Raises:

ValueError – Group already exists.

Return type:

dict

Returns:

dictresp_code = 200 action was successfull, resp_code = 500 if it was not

async delete_group(*, access_token, groupname, **kwargs)#

Deletes the specified Group.

Parameters:
  • access_token (str) – Access-Token of the Requesting User.

  • groupname (str) – Name of the Group to delete.

Raises:

ValueError – Group does not exist

Return type:

dict

Returns:

dictresp_code = 200 action was successfull, resp_code = 500 if it was not

async add_user_to_group(*, access_token, groupname, username, **kwargs)#

Adds a User to a group

Parameters:
  • access_token (str) – Access Token of the Requesting User.

  • groupname (str) – Name of the Group to add the User to.

  • username (str) – Name of the User to add to the Group.

Raises:

ValueError – Group does not exist.

Return type:

dict

Returns:

dictresp_code = 200 action was successfull, resp_code = 500 if it was not

async remove_user_from_group(*, access_token, groupname, username, **kwargs)#

Removes a User from a group

Parameters:
  • access_token (str) – Access Token of the Requesting User.

  • groupname (str) – Name of the Group to remove the User from.

  • username (str) – Name of the User to remove the Group.

Raises:

ValueError – Group does not exist.

Return type:

dict

Returns:

dictresp_code = 200 action was successfull, resp_code = 500 if it was not