Skip to content

Commit

Permalink
feat: update identity methods
Browse files Browse the repository at this point in the history
  • Loading branch information
cowan-macady committed Jul 13, 2023
1 parent 44e25cb commit cb07b18
Show file tree
Hide file tree
Showing 19 changed files with 1,099 additions and 694 deletions.
1 change: 1 addition & 0 deletions .coveragerc
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ omit =
setup.py
version.py
indykite_sdk/api.py
indykite_sdk/api_helper.py
indykite_sdk/example.py
indykite_sdk/indykite/*
indykite_sdk/validate/*
Expand Down
1 change: 1 addition & 0 deletions codecov.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ ignore:
- "setup.py"
- "version.py"
- "indykite_sdk/api.py"
- "indykite_sdk/api_helper.py"
- "indykite_sdk/example.py"
- "indykite_sdk/indykite"
- "indykite_sdk/validate"
Expand Down
1,336 changes: 678 additions & 658 deletions indykite_sdk/api.py

Large diffs are not rendered by default.

112 changes: 112 additions & 0 deletions indykite_sdk/api_helper.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
import base64
import json
from datetime import datetime
from uuid import UUID
from google.protobuf.json_format import MessageToJson


def print_verify_info(digital_twin_info): # pragma: no cover
print("Digital twin info")
print("=================")
print("Tenant: " + str(UUID(bytes=digital_twin_info.digital_twin.tenant_id)))
print("Digital twin: " + str(UUID(bytes=digital_twin_info.digital_twin.id)))


def print_credential(credential): # pragma: no cover
print("Credential")
print("==========")
print("Credential id: " + str(credential.id))
print("Kid: " + str(credential.kid))
if hasattr(credential, 'agent_config'):
print("Agent config: " + str(credential.agent_config))
elif hasattr(credential, 'service_account_config'):
print("Service account config: " + str(credential.service_account_config))
print("Bookmark: " + str(credential.bookmark))
print("Create time: " + str(credential.create_time))
print("Expire time: " + str(credential.expire_time))


def print_token_info(token_info): # pragma: no cover
print("Token info")
print("==========")
print("Tenant: " + str(UUID(bytes=token_info.tenant_id)))
print("Customer: " + str(UUID(bytes=token_info.customer_id)))
print("App space: " + str(UUID(bytes=token_info.app_space_id)))
print("Application: " + str(UUID(bytes=token_info.application_id)))
print("Subject: " + str(UUID(bytes=token_info.subject_id)))
print("Expire time: " + str(datetime.fromtimestamp(token_info.expire_time.seconds)))


def print_response(resp): # pragma: no cover
def get_default(x):
if type(x) is datetime:
return str(x)
else:
return x.__dict__

if hasattr(resp, "DESCRIPTOR"):
js = MessageToJson(resp)
js_dict = json.loads(js)
prettify(js_dict)
else:
js_dict = resp
pretty_response = json.dumps(js_dict, indent=4, separators=(',', ': '), default=get_default)
print(pretty_response)


def prettify(js): # pragma: no cover
for k, v in js.items():
if isinstance(v, type(dict())):
prettify(v)
elif isinstance(v, type(list())):
for val in v:
if isinstance(val, type(str())):
val = format_convert(k, val)
pass
elif isinstance(val, type(list())) | isinstance(val, type(float())) | isinstance(val, type(
bool())) | isinstance(val, type(None)):
pass
else:
prettify(val)
else:
if isinstance(v, str):
js[k] = format_convert(k, v)


def format_convert(k, v): # pragma: no cover
try:
if "id" in k:
i = int(v)
return i
except ValueError:
pass
return str(base64_to_uuid(v))


def base64_to_uuid(b): # pragma: no cover
try:
s = b.encode('ascii')
uid = UUID(bytes=base64.b64decode(s))
except ValueError:
return b
return uid


def add_args_to_dict(all_args, action, values): # pragma: no cover
if action == "add" and values is not None:
for v in values:
all_args["add"].append(v)
elif action == "add_by_ref" and values is not None:
for v in values:
all_args["add_by_ref"].append(v)
elif action == "replace" and values is not None:
for v in values:
all_args["replace"].append(v)
elif action == "replace_by_ref" and values is not None:
for v in values:
all_args["replace_by_ref"].append(v)
elif action == "remove" and values is not None:
for v in values:
all_args["remove"].append(v)

return all_args
20 changes: 18 additions & 2 deletions indykite_sdk/identity/change_password.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,18 @@
from indykite_sdk.indykite.identity.v1beta2 import identity_management_api_pb2 as pb2
from indykite_sdk.indykite.identity.v1beta2 import model_pb2 as model
from indykite_sdk.model.change_password import ChangePassword
import sys
import indykite_sdk.utils.logger as logger


def change_password(self, token, new_password):
"""
change password from token
:param self:
:param token: user's authentication token
:param new_password: string
:return: deserialized ChangePasswordResponse
"""
sys.excepthook = logger.handle_excepthook
try:
if len(token) < 32:
Expand All @@ -26,10 +34,18 @@ def change_password(self, token, new_password):
if not response:
return None

return "The password has been changed successfully"
return ChangePassword.deserialize(response)


def change_password_of_user(self, digital_twin_id, tenant_id, new_password):
"""
change password from diigital twin
:param self:
:param digital_twin_id: string GID id
:param tenant_id: string GID id
:param new_password: string
:return:
"""
sys.excepthook = logger.handle_excepthook
try:
response = self.stub.ChangePassword(
Expand All @@ -47,4 +63,4 @@ def change_password_of_user(self, digital_twin_id, tenant_id, new_password):
if not response:
return None

return "The password has been changed successfully"
return ChangePassword.deserialize(response)
74 changes: 67 additions & 7 deletions indykite_sdk/identity/consent.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,19 @@
from indykite_sdk.indykite.identity.v1beta2 import identity_management_api_pb2 as pb2
from indykite_sdk.indykite.objects.v1beta1 import struct_pb2 as struct
from indykite_sdk.model.consent import CreateConsentResponse, CheckOAuth2ConsentChallengeResponse, CreateOAuth2ConsentVerifierResponse, ConsentRequestSessionData
import sys
import indykite_sdk.utils.logger as logger
from indykite_sdk.utils.message_to_value import arg_to_value


def create_consent(self, pii_processor_id, pii_principal_id, properties=[]):
"""
create consent
:param self:
:param pii_processor_id: string GID id of OAuth2 Application
:param pii_principal_id: string GID id of digital twin
:param properties: list of strings
:return: deserialized CreateConsentResponse
"""
sys.excepthook = logger.handle_excepthook
try:
response = self.stub.CreateConsent(
Expand All @@ -26,6 +33,12 @@ def create_consent(self, pii_processor_id, pii_principal_id, properties=[]):


def list_consents(self, pii_principal_id):
"""
lists consents
:param self:
:param pii_principal_id: string GID id of digital twin
:return: list of ConsentReceipt objects
"""
sys.excepthook = logger.handle_excepthook
try:
streams = self.stub.ListConsents(
Expand All @@ -50,6 +63,13 @@ def list_consents(self, pii_principal_id):


def revoke_consent(self, pii_principal_id, consent_ids=[]):
"""
revoke consent
:param self:
:param pii_principal_id: string GID id of digital twin
:param consent_ids: list of consents (IDs in GID format)
:return: RevokeConsentResponse
"""
sys.excepthook = logger.handle_excepthook
try:
response = self.stub.RevokeConsent(
Expand All @@ -67,6 +87,12 @@ def revoke_consent(self, pii_principal_id, consent_ids=[]):


def check_oauth2_consent_challenge(self, challenge):
"""
check OAuth2 consent challenge
:param self:
:param challenge: string
:return: deserialized CheckOAuth2ConsentChallengeResponse
"""
sys.excepthook = logger.handle_excepthook
try:
response = self.stub.CheckOAuth2ConsentChallenge(
Expand All @@ -82,9 +108,28 @@ def check_oauth2_consent_challenge(self, challenge):
return CheckOAuth2ConsentChallengeResponse.deserialize(response)


def create_oauth2_consent_verifier_approval(self, consent_challenge, grant_scopes=[], granted_audiences=[],
access_token={}, id_token={}, userinfo={}, remember=False,
def create_oauth2_consent_verifier_approval(self,
consent_challenge,
grant_scopes=[],
granted_audiences=[],
access_token={},
id_token={},
userinfo={},
remember=False,
remember_for=None):
"""
create OAuth2 consent verifier for approval
:param self:
:param consent_challenge: string
:param grant_scopes: list of strings
:param granted_audiences: list of strings
:param access_token: custom claims for jwk (map values to enrich access token)
:param id_token: (map values to enrich id token)
:param userinfo: (map values to enrich userinfo)
:param remember: boolean
:param remember_for: int
:return: CreateOAuth2ConsentVerifierResponse
"""
sys.excepthook = logger.handle_excepthook
try:
response = self.stub.CreateOAuth2ConsentVerifier(
Expand All @@ -108,12 +153,27 @@ def create_oauth2_consent_verifier_approval(self, consent_challenge, grant_scope
if not response:
return None

return response
return CreateOAuth2ConsentVerifierResponse.deserialize(response)


def create_oauth2_consent_verifier_denial(self, consent_challenge, error=None,
def create_oauth2_consent_verifier_denial(self,
consent_challenge,
error=None,
error_description=None,
error_hint=None, status_code=None,):
error_hint=None,
status_code=None):

"""
create OAuth2 consent verifier for denial
:param self:
:param consent_challenge: code challenge string
:param error: invalid_request, unauthorized_client, access_denied, unsupported_response_type, invalid_scope,
server_error, temporarily_unavailable
:param error_description: human-readable format str
:param error_hint: string
:param status_code: int
:return: CreateOAuth2ConsentVerifierResponse
"""
sys.excepthook = logger.handle_excepthook
try:
response = self.stub.CreateOAuth2ConsentVerifier(
Expand All @@ -132,4 +192,4 @@ def create_oauth2_consent_verifier_denial(self, consent_challenge, error=None,
if not response:
return None

return response
return CreateOAuth2ConsentVerifierResponse.deserialize(response)
6 changes: 4 additions & 2 deletions indykite_sdk/identity/delete.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,13 @@
import indykite_sdk.utils.logger as logger


def del_digital_twin(self, digital_twin_id, tenant_id):
def del_digital_twin(self, digital_twin_id, tenant_id, admin_token=""):
"""
delete DT by id
:param self:
:param digital_twin_id: DT gid id string
:param tenant_id: tenant gid id string
:param admin_token: token as string
:return: DigitalTwin object
"""
sys.excepthook = logger.handle_excepthook
Expand All @@ -22,7 +23,8 @@ def del_digital_twin(self, digital_twin_id, tenant_id):
id=str(digital_twin_id),
tenant_id=str(tenant_id)
)
)
),
admin_token=admin_token
)
)
except Exception as exception:
Expand Down
8 changes: 8 additions & 0 deletions indykite_sdk/identity/enrich_token.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,14 @@


def enrich_token(self, user_token: str, token_claims: dict, session_claims: dict):
"""
enrich token
:param self:
:param user_token: dict
:param token_claims: dict
:param session_claims: dict
:return: EnrichTokenResponse
"""
sys.excepthook = logger.handle_excepthook
try:
token_struct = struct_pb2.Struct()
Expand Down
7 changes: 7 additions & 0 deletions indykite_sdk/identity/forgotten_password.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,13 @@


def start_forgotten_password_flow(self, digital_twin_id, tenant_id):
"""
start forgotten password flow by sending message with link
:param self:
:param digital_twin_id: string GID id
:param tenant_id: string GID id
:return: True
"""
sys.excepthook = handle_excepthook
try:
response = self.stub.StartForgottenPasswordFlow(
Expand Down
14 changes: 7 additions & 7 deletions indykite_sdk/identity/get_digital_twin.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ def get_digital_twin(self, digital_twin_id, tenant_id, fields):
:param digital_twin_id: string gid id
:param tenant_id: string gid id
:param fields: [] of PropertyMask
:return:
:return: deserialized GetDigitalTwinResponse
"""
sys.excepthook = logger.handle_excepthook
try:
Expand All @@ -41,9 +41,9 @@ def get_digital_twin_by_token(self, token, fields):
"""
get a digital twin with its token
:param self:
:param token:
:param fields:
:return: [] of PropertyMask
:param token: string
:param fields: [] of PropertyMask
:return: deserialized GetDigitalTwinResponse
"""
sys.excepthook = logger.handle_excepthook
try:
Expand All @@ -68,9 +68,9 @@ def get_digital_twin_by_property(self, property_filter, fields):
"""
get a digital twin with a filter on its properties
:param self:
:param property_filter:
:param fields: []
:return: [] of PropertyMask
:param property_filter: PropertyFilter object
:param fields: [] of PropertyMask
:return: deserialized GetDigitalTwinResponse
"""
sys.excepthook = logger.handle_excepthook
try:
Expand Down

0 comments on commit cb07b18

Please sign in to comment.