"""Helper for DynamoDB requests.""" import boto3 from boto3.dynamodb.conditions import Attr, Key from ddtrace import tracer from users import config @tracer.wrap(name='dynamodb_get_social_auth_item') def get_social_auth_item(participant_id, identity_id, platform, dynamodb=None): """Query social auth db for participant's social auth info. Query social auth table in dynamodb to get the participant and related info. This helps us determine whether the user with id `identity_id` is the one who linked the participant with id `participant_id`. Args: participant_id (str): The id of the participant to query identity_id (str): The id of the user trying to unlink the participant's social account platform (str): The platform of the participant to query Returns: The participant record or None if not found """ if not participant_id: return None if not identity_id: return None if not platform: return None if not dynamodb: dynamodb = boto3.resource('dynamodb', region_name=config.AWS_REGION) table = dynamodb.Table(config.DYNAMODB_SOCIAL_AUTH_TABLE) response = table.query( KeyConditionExpression=Key('PK').eq(participant_id) & Key('SK').eq('{}#{}'.format(identity_id, platform.upper())), FilterExpression=Attr('linked').eq(True), Limit=1, ) items = response.get('Items', []) if not items: return None return items[0] @tracer.wrap(name='dynamodb_update_social_auth_item_linked_status') def update_social_auth_item_linked_status( participant_id, identity_id, platform, link_status, dynamodb=None ): """Update social auth item's link status. Update the social auth item in the table to set the link status to `link_status`. Args: participant_id (str): The id of the participant to query identity_id (str): The id of the user trying to unlink the participant's social account platform (str): The platform of the participant to query link_status (bool): The link status to set for the item Returns: The participant record or None if not found """ if not participant_id: return None if not identity_id: return None if not platform: return None if not dynamodb: dynamodb = boto3.resource('dynamodb', region_name=config.AWS_REGION) table = dynamodb.Table(config.DYNAMODB_SOCIAL_AUTH_TABLE) response = table.update_item( Key={'PK': participant_id, 'SK': '{}#{}'.format(identity_id, platform.upper())}, UpdateExpression='SET linked = :val', ExpressionAttributeValues={':val': link_status}, ReturnValues='ALL_NEW', ) attributes = response.get('Attributes', {}) if not attributes: return None return attributes