Warning: This document is for an old version of iam-python-sdk. The latest version is 1.4.1.

iam_python_sdk package

Submodules

iam_python_sdk.bloom module

Bloom filter module.

class iam_python_sdk.bloom.BloomFilter → None[source]

Bases: object

Bloom Filer class.

contain(item: str) → bool[source]
insert(item: str) → None[source]

iam_python_sdk.cache module

Cache module.

class iam_python_sdk.cache.Cache(ttl: int = None, *args, **kwargs) → None[source]

Bases: collections.OrderedDict

Cache class that implement OrderedDict with thread safe feature.

Args:
OrderedDict ([type]): dict subclass that remembers the order entries were added.
get(key: AnyStr, default=None) → typing.Any[source]

Get cache value by key.

Args:
key (AnyStr): cache key default (Any, optional): Default value if cache key is not found. Defaults to None.
Returns:
Any: cache value
is_expired(key: AnyStr, when: int = None) → bool[source]

Check if cache key is expired.

Args:
key (AnyStr): cache key when (int, optional): added time if needed. Defaults to None.
Returns:
bool: expired status
set(key: AnyStr, value: typing.Any, ttl: int = None) → None[source]

Set cache value

Args:
key (AnyStr): cache key value (Any): cache value ttl (int, optional): time to live in seconds. Defaults to None.

iam_python_sdk.cli module

Console script for iam_python_sdk.

iam_python_sdk.client module

IAM Python SDK client module.

class iam_python_sdk.client.DefaultClient(config: iam_python_sdk.config.Config, rolePermissionCache: iam_python_sdk.cache.Cache, clientInfoCache: iam_python_sdk.cache.Cache, httpClient: iam_python_sdk.client.HttpClient) → None[source]

Bases: object

Default Client class.

ClientToken() → str[source]

Returns client access token

Returns:
str: token
ClientTokenGrant() → None[source]

Starts client token grant to get client bearer token for role caching

Raises:
ClientTokenGrantError: exception response format error ClientTokenGrantError: exceptions http request error
GetClientInformation(namespace: str, clientID: str) → typing.Union[iam_python_sdk.models.ClientInformation, NoneType][source]

Gets IAM client information, it will look into cache first, if not found then fetch it to IAM.

Args:
namespace (str): namespace clientID (str): client ID
Returns:
Union[ClientInformation, None]: client information or None
GetRolePermissions(roleID: str) → typing.List[iam_python_sdk.models.Permission][source]

Get permssions of a role

Args:
roleID (str): role id
Raises:
GetRolePermissionError: exception failed to refresh token GetRolePermissionError: exception response format error GetRolePermissionError: exceptions http request error
Returns:
Union[List[Permission], None]: list of permissions or None
HasBan(claims: typing.Union[iam_python_sdk.models.JWTClaims, NoneType], banType: str) → bool[source]

Validates if certain ban exist

Args:
claims (JWTClaims): JWT claims banType (str): ban type
Returns:
bool: ban status
HealthCheck() → bool[source]

Lets caller know the health of the IAM client

Returns:
bool: health status
StartLocalValidation() → None[source]

Starts thread to refresh JWK and revocation list periodically this enables local token validation

UserAnonymousStatus(claims: typing.Union[iam_python_sdk.models.JWTClaims, NoneType]) → bool[source]

Gets user anonymous status on access token

Args:
claims (JWTClaims): JWT claims
Returns:
bool: user anonymous status
UserEmailVerificationStatus(claims: typing.Union[iam_python_sdk.models.JWTClaims, NoneType]) → bool[source]

Gets user email verification status on access token

Args:
claims (JWTClaims): JWT claims
Returns:
bool: user email verification status
UserPhoneVerificationStatus(claims: typing.Union[iam_python_sdk.models.JWTClaims, NoneType]) → bool[source]

Gets user phone verification status on access token

Args:
claims (JWTClaims): JWT claims
Returns:
bool: user phone verification status
ValidateAccessToken(accessToken: str) → bool[source]

Validates access token by calling IAM service

Args:
accessToken (str): access token
Raises:
ValidateAccessTokenError: exception failed to refresh token ValidateAccessTokenError: exceptions http request error
Returns:
bool: access token validity status
ValidateAndParseClaims(accessToken: str) → typing.Union[iam_python_sdk.models.JWTClaims, NoneType][source]

Validates access token locally and returns the JWT claims contained in the token

Args:
accessToken (str): access token
Returns:
Union[JWTClaims, None]: JWT claims or None
ValidateAudience(claims: typing.Union[iam_python_sdk.models.JWTClaims, NoneType]) → None[source]

Validate audience of user access token

Args:
claims (JWTClaims): JWT claims
ValidatePermission(claims: typing.Union[iam_python_sdk.models.JWTClaims, NoneType], requiredPermission: iam_python_sdk.models.Permission, permissionResources: typing.Dict[str, str]) → bool[source]

Validates if an access token has right for a specific permission

Args:
claims (JWTClaims): JWT claims requiredPermission (Permission): permission to access resource, example: {Resource: “NAMESPACE:{namespace}:USER:{userId}”, Action: 2} permissionResources (Dict[str, str]): resource string to replace the {} placeholder in requiredPermission, example: p[“{namespace}”] = “accelbyte”
Returns:
bool: permission status
ValidateRole(requiredRoleID: str, claims: typing.Union[iam_python_sdk.models.JWTClaims, NoneType]) → bool[source]

Validates if an access token has a specific role

Args:
requiredRoleID (str): role ID that required claims (JWTClaims): JWT claims
Returns:
bool: role validity status
ValidateScope(claims: typing.Union[iam_python_sdk.models.JWTClaims, NoneType], reqScope: str) → None[source]

Validate scope of user access token

Args:
claims (JWTClaims): JWT claims reqScope (str): required role scope
class iam_python_sdk.client.HttpClient[source]

Bases: object

HttpClient class to do http request.

get(*args, **kwargs) → httpx.Response[source]
post(*args, **kwargs) → httpx.Response[source]
request(method: str = 'GET', *args, **kwargs) → httpx.Response[source]
class iam_python_sdk.client.NewDefaultClient(config: iam_python_sdk.config.Config) → None[source]

Bases: iam_python_sdk.client.DefaultClient

iam_python_sdk.client.backoff_giveup_handler(backoff) → None[source]

iam_python_sdk.config module

Config module.

class iam_python_sdk.config.Config(BaseURL: str = '', ClientID: str = '', ClientSecret: str = '', RolesCacheExpirationTime: int = 60, JWKSRefreshInterval: int = 60, RevocationListRefreshInterval: int = 60, Debug: bool = False) → None[source]

Bases: object

Config class.

iam_python_sdk.errors module

Error module.

exception iam_python_sdk.errors.ClientTokenGrantError(message: str = '') → None[source]

Bases: iam_python_sdk.errors.Error

exception iam_python_sdk.errors.EmptyTokenError(message: str = '') → None[source]

Bases: iam_python_sdk.errors.Error

message = 'token is empty'
exception iam_python_sdk.errors.Error(message: str = '') → None[source]

Bases: Exception

Base error class.

exception iam_python_sdk.errors.ForbiddenError(message: str = '') → None[source]

Bases: iam_python_sdk.errors.Error

message = 'access forbidden, make sure you have client creds that has sufficient permission'
exception iam_python_sdk.errors.GetClientInformationError(message: str = '') → None[source]

Bases: iam_python_sdk.errors.Error

exception iam_python_sdk.errors.GetJWKSError(message: str = '') → None[source]

Bases: iam_python_sdk.errors.Error

exception iam_python_sdk.errors.GetRevocationListError(message: str = '') → None[source]

Bases: iam_python_sdk.errors.Error

exception iam_python_sdk.errors.GetRolePermissionError(message: str = '') → None[source]

Bases: iam_python_sdk.errors.Error

exception iam_python_sdk.errors.HTTPClientError(message: str = '') → None[source]

Bases: iam_python_sdk.errors.Error

exception iam_python_sdk.errors.InvalidAudError(message: str = '') → None[source]

Bases: iam_python_sdk.errors.Error

message = "audience doesn't match the client's base uri. access denied"
exception iam_python_sdk.errors.InvalidScopeError(message: str = '') → None[source]

Bases: iam_python_sdk.errors.Error

message = 'insufficient scope'
exception iam_python_sdk.errors.InvalidTokenSignatureKeyError(message: str = '') → None[source]

Bases: iam_python_sdk.errors.Error

message = 'invalid token signature key ID'
exception iam_python_sdk.errors.NilClaimError(message: str = '') → None[source]

Bases: iam_python_sdk.errors.Error

message = 'claims is nil'
exception iam_python_sdk.errors.NoLocalValidationError(message: str = '') → None[source]

Bases: iam_python_sdk.errors.Error

message = 'local validation is not active, activate by calling StartLocalValidation()'
exception iam_python_sdk.errors.RefreshAccessTokenError(message: str = '') → None[source]

Bases: iam_python_sdk.errors.Error

exception iam_python_sdk.errors.RoleNotFoundError(message: str = '') → None[source]

Bases: iam_python_sdk.errors.Error

message = 'role not found'
exception iam_python_sdk.errors.StartLocalValidationError(message: str = '') → None[source]

Bases: iam_python_sdk.errors.Error

exception iam_python_sdk.errors.TokenRevokedError(message: str = '') → None[source]

Bases: iam_python_sdk.errors.Error

message = 'token has been revoked'
exception iam_python_sdk.errors.UnauthorizedError(message: str = '') → None[source]

Bases: iam_python_sdk.errors.Error

message = 'access unauthorized, make sure you have valid client access token using ClientTokenGrant'
exception iam_python_sdk.errors.UserRevokedError(message: str = '') → None[source]

Bases: iam_python_sdk.errors.Error

message = 'user has been revoked'
exception iam_python_sdk.errors.ValidateAccessTokenError(message: str = '') → None[source]

Bases: iam_python_sdk.errors.Error

exception iam_python_sdk.errors.ValidateAndParseClaimsError(message: str = '') → None[source]

Bases: iam_python_sdk.errors.Error

exception iam_python_sdk.errors.ValidateAudienceError(message: str = '') → None[source]

Bases: iam_python_sdk.errors.Error

exception iam_python_sdk.errors.ValidateJWTError(message: str = '') → None[source]

Bases: iam_python_sdk.errors.Error

exception iam_python_sdk.errors.ValidatePermissionError(message: str = '') → None[source]

Bases: iam_python_sdk.errors.Error

exception iam_python_sdk.errors.ValidateScopeError(message: str = '') → None[source]

Bases: iam_python_sdk.errors.Error

iam_python_sdk.flask module

Flask module.

class iam_python_sdk.flask.IAM(app: flask.app.Flask = None) → None[source]

Bases: object

IAM Flask extensions class.

init_app(app: flask.app.Flask)[source]

Init IAM flask extensions with Flask app. Client token grant and local validation will be executed once here, then the background thread will spawn to refresh token, jwks and revocation list.

Args:
app (Flask): Flask app instance
Raises:
ValueError: Error if the requirement configs are not set
validate_permission(jwt_claims: iam_python_sdk.models.JWTClaims, required_permission: typing.Union[dict, iam_python_sdk.models.Permission], permission_resource: dict) → bool[source]

Validate permission from JWT claims data.

Args:

jwt_claims (JWTClaims): JWT claims data required_permission (Union[dict, Permission]): Required permission that needed,

can be in dict or Permission format.

permission_resource (dict): Optional permission resource if needed

Raises:
UnauthorizedError: Error if JWT claims data is not sufficient to access required permission and resource
Returns:
bool: Permission status
validate_token_in_request(validate_referer: bool) → iam_python_sdk.models.JWTClaims[source]

Validate token in the Flask request. This method support headers and cookies with based token.

Args:
validate_referer (bool): Validate referer for CSRF protection
Raises:
EmptyTokenError: Error if token is not found UnauthorizedError: Error if token permission is not sufficient
Returns:
JWTClaims: JWT claims data
iam_python_sdk.flask.cors_options(headers: dict = {}, preflight_options: bool = True)[source]

Decorator for set the CORS response header. This method will override default app-wide CORS options if it has enabled.

Args:
headers (dict, optional): CORS headers key and value to be added to the response. Defaults to {}.
iam_python_sdk.flask.token_required(required_permission: dict, permission_resource: dict = {}, csrf_protect: bool = None)[source]

The decorator to protect endpoint using IAM service.

Args:

required_permission (dict): Required permission with format {“resource”: xxx, “action”: n} permission_resource (dict, optional): Optional permission resource if needed with format

{“{xxx}”: “xxx replacement”}. Defaults to {}.
csrf_protect (bool): CSRF protection (Note: CSRF protect is available only on cookie token).
Defaults to IAM_CSRF_PROTECTION config.

iam_python_sdk.log module

iam_python_sdk.models module

Model module.

class iam_python_sdk.models.ClientInformation[source]

Bases: iam_python_sdk.models.Model

Holds client information.

Baseuri = ''
Clientname = ''
Namespace = ''
Redirecturi = ''
class iam_python_sdk.models.JWTBan[source]

Bases: iam_python_sdk.models.Model

Holds information about ban record in JWT.

Ban = ''
Enddate = 0.0
class iam_python_sdk.models.JWTClaims[source]

Bases: iam_python_sdk.models.Model

Holds data stored in a JWT access token with additional Justice Flags field.

AcceptedPolicyVersion = ['']
Aud = ['']
Bans = [<iam_python_sdk.models.JWTBan object>]
ClientId = ''
Country = ''
DisplayName = ''
Exp = -1
Iat = -1
IsComply = False
Jflgs = -1
Namespace = ''
NamespaceRoles = [<iam_python_sdk.models.NamespaceRole object>]
Permissions = [<iam_python_sdk.models.Permission object>]
Roles = ['']
Scope = ''
Sub = ''
class iam_python_sdk.models.Model[source]

Bases: object

Base model class.

classmethod loads(data: typing.Any) → typing.Any[source]

Decode data to model

Args:
data (Any): data to decode
Returns:
Any: model object
class iam_python_sdk.models.NamespaceRole[source]

Bases: iam_python_sdk.models.Model

Hold info about a namespace role.

Namespace = ''
Roleid = ''
class iam_python_sdk.models.Permission[source]

Bases: iam_python_sdk.models.Model

Holds information about the actions can be performed to the resource.

Action = -1
Resource = ''
Schedaction = -1
Schedcron = ''
Schedrange = ['']
is_in_range() → bool[source]
is_recurring() → bool[source]
is_scheduled() → bool[source]
class iam_python_sdk.models.RevocationList[source]

Bases: iam_python_sdk.models.Model

Contains revoked user and token.

RevokedTokens = <iam_python_sdk.bloom.BloomFilter object>
RevokedUsers = [<iam_python_sdk.models.UserRevocationListRecord object>]
class iam_python_sdk.models.Role[source]

Bases: iam_python_sdk.models.Model

Hold info about a user role.

Permissions = [<iam_python_sdk.models.Permission object>]
Roleid = ''
Rolename = ''
class iam_python_sdk.models.TokenResponse[source]

Bases: iam_python_sdk.models.Model

Token response class on successful token request.

AcceptedPolicyVersion = ['']
AccessToken = ''
Bans = [<iam_python_sdk.models.JWTBan object>]
DisplayName = ''
ExpiresIn = -1
IsComply = ''
Jflgs = -1
Namespace = ''
NamespaceRoles = [<iam_python_sdk.models.NamespaceRole object>]
Permissions = [<iam_python_sdk.models.Permission object>]
PlatformId = ''
PlatformUserId = ''
RefreshToken = ''
Roles = ['']
TokenType = ''
UserId = ''
class iam_python_sdk.models.UserRevocationListRecord[source]

Bases: iam_python_sdk.models.Model

Used to store revoked user data.

Id = ''
RevokedAt = 0.0

iam_python_sdk.task module

Task module.

class iam_python_sdk.task.Task(interval: typing.Union[int, float], function: typing.Callable[..., typing.Any], *args, **kwargs) → None[source]

Bases: object

Task module for background task.

start(repeat: bool = False) → None[source]

Start the thread in background(daemon).

Args:
repeat (bool, optional): Status if the task is repetitive. Defaults to False.
stop() → None[source]

Stop the background task.

iam_python_sdk.utils module

Utils module.

iam_python_sdk.utils.decode_model(data: typing.Union[str, list, dict], model: object) → typing.Any[source]

Decode model data from response json.

Args:
data (Union[str, list, dict]): A list, a dict or a string of json response. model (object): Model object.
Raises:
ValueError: Data error if none or empty. ValueError: Model error if not an object. ValueError: Data error if not a list, a dict or a string json.
Returns:
object: Model instance with data.
iam_python_sdk.utils.parse_nanotimestamp(s: str) → typing.Union[int, float][source]

Parse datetime string with nanoseconds

Args:
s (str): datetime string
Returns:
datetime: datetime object

Module contents

class iam_python_sdk.NewDefaultClient(config: iam_python_sdk.config.Config) → None[source]

Bases: iam_python_sdk.client.DefaultClient

class iam_python_sdk.Config(BaseURL: str = '', ClientID: str = '', ClientSecret: str = '', RolesCacheExpirationTime: int = 60, JWKSRefreshInterval: int = 60, RevocationListRefreshInterval: int = 60, Debug: bool = False) → None[source]

Bases: object

Config class.