iam_python_sdk package¶
Submodules¶
iam_python_sdk.async_client module¶
IAM Python SDK async client module.
-
class
iam_python_sdk.async_client.
AsyncClient
(config: iam_python_sdk.config.Config, rolePermissionCache: iam_python_sdk.cache.Cache, clientInfoCache: iam_python_sdk.cache.Cache, httpClient: iam_python_sdk.async_client.HttpClient) → None[source]¶ Bases:
object
Async Client class.
-
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
-
-
class
iam_python_sdk.async_client.
HttpClient
[source]¶ Bases:
object
HttpClient class to do http request.
iam_python_sdk.bloom module¶
Bloom filter module.
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
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.
-
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
-
iam_python_sdk.config module¶
Config module.
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'¶
-
Bases:
iam_python_sdk.errors.Error
-
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.fastapi module¶
FastAPI module.
-
class
iam_python_sdk.fastapi.
IAM
(app: typing.Union[fastapi.applications.FastAPI, NoneType] = None, config: iam_python_sdk.fastapi.Settings = Settings(iam_base_url='', iam_client_id='', iam_client_secret='', iam_token_locations=['headers', 'cookies'], iam_token_header_name='Authorization', iam_token_header_type='Bearer', iam_token_cookie_name='access_token', iam_token_cookie_path='/', iam_csrf_protection=True, iam_strict_referer=True, iam_cors_enable=False, iam_cors_origin='*', iam_cors_headers='*', iam_cors_methods='*', iam_cors_credentials=True)) → None[source]¶ Bases:
object
IAM FastAPI extensions class.
-
init_app
(app: fastapi.applications.FastAPI, config: iam_python_sdk.fastapi.Settings = Settings(iam_base_url='', iam_client_id='', iam_client_secret='', iam_token_locations=['headers', 'cookies'], iam_token_header_name='Authorization', iam_token_header_type='Bearer', iam_token_cookie_name='access_token', iam_token_cookie_path='/', iam_csrf_protection=True, iam_strict_referer=True, iam_cors_enable=False, iam_cors_origin='*', iam_cors_headers='*', iam_cors_methods='*', iam_cors_credentials=True)) → None[source]¶ Init IAM FastAPI extensions with FastAPI 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 config (Settings): Configuration object
- Raises:
- ValueError: Error if the requirement configs are not set
-
-
class
iam_python_sdk.fastapi.
Settings
[source]¶ Bases:
pydantic.env_settings.BaseSettings
IAM settings class.
-
iam_python_sdk.fastapi.
permission_required
(required_permission: typing.Union[dict, iam_python_sdk.models.Permission], permission_resource: dict = {}, csrf_protect: typing.Union[bool, NoneType] = None) → typing.Callable[source]¶ Validate permission in the token if it has required permission
- Args:
- required_permission (Union[dict, Permission]): The required permission permission_resource (dict, optional): The placeholder replacement if any. Defaults to {}. csrf_protect (Union[bool, None], optional): CSRF protect options. Defaults to None.
- Returns:
- Callable: _description_
-
iam_python_sdk.fastapi.
token_required
(csrf_protect: typing.Union[bool, NoneType] = None) → typing.Callable[source]¶ Validate token in the FastAPI request. This method support headers and cookies with based token.
- Args:
- csrf_protect (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.fastapi.
validate_referer_header
(request: starlette.requests.Request, jwt_claims: iam_python_sdk.models.JWTClaims) → bool[source]¶ Validate referer header for CSRF protection
- Args:
- request (Request): FastAPI request object jwt_claims (JWTClaims): JWT Claim data from token
- Returns:
- bool: Is referrer header valid
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.
BloomFilterJSON
[source]¶ Bases:
iam_python_sdk.models.Model
-
Bits
= [0]¶
-
K
= 0¶
-
M
= 0¶
-
-
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.
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
= ['']¶
-
-
class
iam_python_sdk.models.
RevocationList
[source]¶ Bases:
iam_python_sdk.models.Model
Contains revoked user and token.
-
RevokedTokens
= <iam_python_sdk.models.BloomFilterJSON 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.
AsyncTask
(interval: typing.Union[int, float], function: typing.Callable[..., typing.Any], repeat: bool = True, *args, **kwargs) → None[source]¶ Bases:
object
AsyncTask module for background task.
-
status
¶
-
-
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.
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.