Skip to content

Commit

Permalink
feat: Added management command to update UIDs
Browse files Browse the repository at this point in the history
  • Loading branch information
zamanafzal committed Dec 9, 2024
1 parent 7ca0731 commit 163e776
Show file tree
Hide file tree
Showing 3 changed files with 163 additions and 1 deletion.
4 changes: 4 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ Unreleased
----------
* nothing unreleased

[5.4.1]
--------
* feat: Added a management command to update the Social Auth UID's for an enterprise.

[5.4.0]
--------
* chore: Update python requirements.
Expand Down
2 changes: 1 addition & 1 deletion enterprise/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
Your project description goes here.
"""

__version__ = "5.4.0"
__version__ = "5.4.1"
158 changes: 158 additions & 0 deletions enterprise/management/commands/update_ccb_enterprise_uids.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
import logging
import csv
from django.db import transaction
from django.core.management.base import BaseCommand
from django.core.exceptions import ValidationError

Check warning on line 5 in enterprise/management/commands/update_ccb_enterprise_uids.py

View check run for this annotation

Codecov / codecov/patch

enterprise/management/commands/update_ccb_enterprise_uids.py#L1-L5

Added lines #L1 - L5 were not covered by tests

try:
from social_django.models import UserSocialAuth
except ImportError:
UserSocialAuth = None

Check warning on line 10 in enterprise/management/commands/update_ccb_enterprise_uids.py

View check run for this annotation

Codecov / codecov/patch

enterprise/management/commands/update_ccb_enterprise_uids.py#L7-L10

Added lines #L7 - L10 were not covered by tests

logger = logging.getLogger(__name__)

Check warning on line 12 in enterprise/management/commands/update_ccb_enterprise_uids.py

View check run for this annotation

Codecov / codecov/patch

enterprise/management/commands/update_ccb_enterprise_uids.py#L12

Added line #L12 was not covered by tests


class CSVUpdateError(Exception):

Check warning on line 15 in enterprise/management/commands/update_ccb_enterprise_uids.py

View check run for this annotation

Codecov / codecov/patch

enterprise/management/commands/update_ccb_enterprise_uids.py#L15

Added line #L15 was not covered by tests
"""Custom exception for CSV update process."""
pass

Check warning on line 17 in enterprise/management/commands/update_ccb_enterprise_uids.py

View check run for this annotation

Codecov / codecov/patch

enterprise/management/commands/update_ccb_enterprise_uids.py#L17

Added line #L17 was not covered by tests


class Command(BaseCommand):

Check warning on line 20 in enterprise/management/commands/update_ccb_enterprise_uids.py

View check run for this annotation

Codecov / codecov/patch

enterprise/management/commands/update_ccb_enterprise_uids.py#L20

Added line #L20 was not covered by tests
"""
Update the enterprise related social auth records UID to the new one.
Example usage:
./manage.py lms update_ccb_enterprise_uids csv_file_path
./manage.py lms update_ccb_enterprise_uids csv_file_path --old-prefix="sf-ccb:" --new-prefix="ccb:samlp|{}@ccb.org.co"
./manage.py lms update_ccb_enterprise_uids csv_file_path --no-dry-run
"""

help = 'Records update from CSV with console logging'

Check warning on line 31 in enterprise/management/commands/update_ccb_enterprise_uids.py

View check run for this annotation

Codecov / codecov/patch

enterprise/management/commands/update_ccb_enterprise_uids.py#L31

Added line #L31 was not covered by tests

def add_arguments(self, parser):
parser.add_argument('csv_file', type=str, help='Path to the CSV file')
parser.add_argument(

Check warning on line 35 in enterprise/management/commands/update_ccb_enterprise_uids.py

View check run for this annotation

Codecov / codecov/patch

enterprise/management/commands/update_ccb_enterprise_uids.py#L33-L35

Added lines #L33 - L35 were not covered by tests
'--old-prefix',
type=str,
default=None,
help='Optional old prefix for old UID. If not provided, uses CSV value.'
)
parser.add_argument(

Check warning on line 41 in enterprise/management/commands/update_ccb_enterprise_uids.py

View check run for this annotation

Codecov / codecov/patch

enterprise/management/commands/update_ccb_enterprise_uids.py#L41

Added line #L41 was not covered by tests
'--new-prefix',
type=str,
default=None,
help='Optional new prefix for new UID. If not provided, uses CSV value.'
)
parser.add_argument(

Check warning on line 47 in enterprise/management/commands/update_ccb_enterprise_uids.py

View check run for this annotation

Codecov / codecov/patch

enterprise/management/commands/update_ccb_enterprise_uids.py#L47

Added line #L47 was not covered by tests
'--no-dry-run',
action='store_false',
dest='dry_run',
default=True,
help='Actually save changes instead of simulating'
)

def handle(self, *args, **options):
logger.info("Command has started...")
csv_path = options['csv_file']
dry_run = options['dry_run']

Check warning on line 58 in enterprise/management/commands/update_ccb_enterprise_uids.py

View check run for this annotation

Codecov / codecov/patch

enterprise/management/commands/update_ccb_enterprise_uids.py#L55-L58

Added lines #L55 - L58 were not covered by tests

total_processed = 0
total_updated = 0
total_errors = 0

Check warning on line 62 in enterprise/management/commands/update_ccb_enterprise_uids.py

View check run for this annotation

Codecov / codecov/patch

enterprise/management/commands/update_ccb_enterprise_uids.py#L60-L62

Added lines #L60 - L62 were not covered by tests

try:
with open(csv_path, 'r') as csvfile:
reader = csv.DictReader(csvfile)

Check warning on line 66 in enterprise/management/commands/update_ccb_enterprise_uids.py

View check run for this annotation

Codecov / codecov/patch

enterprise/management/commands/update_ccb_enterprise_uids.py#L64-L66

Added lines #L64 - L66 were not covered by tests

for row_num, row in enumerate(reader, start=1):
total_processed += 1

Check warning on line 69 in enterprise/management/commands/update_ccb_enterprise_uids.py

View check run for this annotation

Codecov / codecov/patch

enterprise/management/commands/update_ccb_enterprise_uids.py#L69

Added line #L69 was not covered by tests

try:
with transaction.atomic():

Check warning on line 72 in enterprise/management/commands/update_ccb_enterprise_uids.py

View check run for this annotation

Codecov / codecov/patch

enterprise/management/commands/update_ccb_enterprise_uids.py#L71-L72

Added lines #L71 - L72 were not covered by tests
if self.update_record(row, dry_run):
total_updated += 1

Check warning on line 74 in enterprise/management/commands/update_ccb_enterprise_uids.py

View check run for this annotation

Codecov / codecov/patch

enterprise/management/commands/update_ccb_enterprise_uids.py#L74

Added line #L74 was not covered by tests

except Exception as row_error:
total_errors += 1
error_msg = f"Row {row_num} update failed: {row} - Error: {str(row_error)}"
logger.error(error_msg, exc_info=True)

Check warning on line 79 in enterprise/management/commands/update_ccb_enterprise_uids.py

View check run for this annotation

Codecov / codecov/patch

enterprise/management/commands/update_ccb_enterprise_uids.py#L76-L79

Added lines #L76 - L79 were not covered by tests

summary_msg = (

Check warning on line 81 in enterprise/management/commands/update_ccb_enterprise_uids.py

View check run for this annotation

Codecov / codecov/patch

enterprise/management/commands/update_ccb_enterprise_uids.py#L81

Added line #L81 was not covered by tests
f"CSV Update Summary:\n"
f"Total Records Processed: {total_processed}\n"
f"Records Successfully Updated: {total_updated}\n"
f"Errors Encountered: {total_errors}\n"
f"Dry Run Mode: {'Enabled' if dry_run else 'Disabled'}"
)
logger.info(summary_msg)
except IOError as io_error:
logger.critical(f"File I/O error: {str(io_error)}")

Check warning on line 90 in enterprise/management/commands/update_ccb_enterprise_uids.py

View check run for this annotation

Codecov / codecov/patch

enterprise/management/commands/update_ccb_enterprise_uids.py#L88-L90

Added lines #L88 - L90 were not covered by tests

except Exception as e:
logger.critical(f"Critical error in CSV processing: {str(e)}")

Check warning on line 93 in enterprise/management/commands/update_ccb_enterprise_uids.py

View check run for this annotation

Codecov / codecov/patch

enterprise/management/commands/update_ccb_enterprise_uids.py#L92-L93

Added lines #L92 - L93 were not covered by tests

def update_record(self, row, dry_run=True, old_prefix=None, new_prefix=None):

Check warning on line 95 in enterprise/management/commands/update_ccb_enterprise_uids.py

View check run for this annotation

Codecov / codecov/patch

enterprise/management/commands/update_ccb_enterprise_uids.py#L95

Added line #L95 was not covered by tests
"""
Update a single record, applying optional prefixes to UIDs if provided.
Args:
row (dict): CSV row data
dry_run (bool): Whether to simulate or actually save changes
old_prefix (str): Prefix to apply to the old UID
new_prefix (str): Prefix to apply to the new UID
Returns:
bool: Whether the update was successful
"""
try:
old_uid = row.get('old-uid')
new_uid = row.get('new-uid')

Check warning on line 110 in enterprise/management/commands/update_ccb_enterprise_uids.py

View check run for this annotation

Codecov / codecov/patch

enterprise/management/commands/update_ccb_enterprise_uids.py#L108-L110

Added lines #L108 - L110 were not covered by tests

# Validating that both values are present
if not old_uid or not new_uid:
raise CSVUpdateError("Missing required UID fields")

Check warning on line 114 in enterprise/management/commands/update_ccb_enterprise_uids.py

View check run for this annotation

Codecov / codecov/patch

enterprise/management/commands/update_ccb_enterprise_uids.py#L114

Added line #L114 was not covered by tests

# Construct dynamic UIDs
old_uid_with_prefix = f'{old_prefix}{old_uid}' if old_prefix else old_uid
new_uid_with_prefix = (

Check warning on line 118 in enterprise/management/commands/update_ccb_enterprise_uids.py

View check run for this annotation

Codecov / codecov/patch

enterprise/management/commands/update_ccb_enterprise_uids.py#L117-L118

Added lines #L117 - L118 were not covered by tests
new_prefix.format(new_uid) if new_prefix and '{}' in new_prefix
else f"{new_prefix}{new_uid}" if new_prefix
else new_uid
)

instance_with_old_uid = UserSocialAuth.objects.filter(uid=old_uid_with_prefix).first()

Check warning on line 124 in enterprise/management/commands/update_ccb_enterprise_uids.py

View check run for this annotation

Codecov / codecov/patch

enterprise/management/commands/update_ccb_enterprise_uids.py#L124

Added line #L124 was not covered by tests

if not instance_with_old_uid:
raise CSVUpdateError(f"No record found with old UID {old_uid_with_prefix}")

Check warning on line 127 in enterprise/management/commands/update_ccb_enterprise_uids.py

View check run for this annotation

Codecov / codecov/patch

enterprise/management/commands/update_ccb_enterprise_uids.py#L127

Added line #L127 was not covered by tests

instance_with_new_uid = UserSocialAuth.objects.filter(uid=new_uid_with_prefix).first()

Check warning on line 129 in enterprise/management/commands/update_ccb_enterprise_uids.py

View check run for this annotation

Codecov / codecov/patch

enterprise/management/commands/update_ccb_enterprise_uids.py#L129

Added line #L129 was not covered by tests
if instance_with_new_uid:
log_entry = f"Warning: Existing record with new UID {new_uid_with_prefix} is deleting."
logger.info(log_entry)

Check warning on line 132 in enterprise/management/commands/update_ccb_enterprise_uids.py

View check run for this annotation

Codecov / codecov/patch

enterprise/management/commands/update_ccb_enterprise_uids.py#L131-L132

Added lines #L131 - L132 were not covered by tests
if not dry_run:
instance_with_new_uid.delete()

Check warning on line 134 in enterprise/management/commands/update_ccb_enterprise_uids.py

View check run for this annotation

Codecov / codecov/patch

enterprise/management/commands/update_ccb_enterprise_uids.py#L134

Added line #L134 was not covered by tests

if not dry_run:
instance_with_old_uid.uid = new_uid_with_prefix
instance_with_old_uid.save()

Check warning on line 138 in enterprise/management/commands/update_ccb_enterprise_uids.py

View check run for this annotation

Codecov / codecov/patch

enterprise/management/commands/update_ccb_enterprise_uids.py#L137-L138

Added lines #L137 - L138 were not covered by tests

log_entry = f"Successfully updated record: Old UID {old_uid_with_prefix} → New UID {new_uid_with_prefix}"
logger.info(log_entry)

Check warning on line 141 in enterprise/management/commands/update_ccb_enterprise_uids.py

View check run for this annotation

Codecov / codecov/patch

enterprise/management/commands/update_ccb_enterprise_uids.py#L140-L141

Added lines #L140 - L141 were not covered by tests

return True

Check warning on line 143 in enterprise/management/commands/update_ccb_enterprise_uids.py

View check run for this annotation

Codecov / codecov/patch

enterprise/management/commands/update_ccb_enterprise_uids.py#L143

Added line #L143 was not covered by tests

except ValidationError as ve:
error_msg = f"Validation error: {ve}"
logger.error(error_msg)
raise

Check warning on line 148 in enterprise/management/commands/update_ccb_enterprise_uids.py

View check run for this annotation

Codecov / codecov/patch

enterprise/management/commands/update_ccb_enterprise_uids.py#L145-L148

Added lines #L145 - L148 were not covered by tests

except CSVUpdateError as update_error:
error_msg = f"Update processing error: {update_error}"
logger.error(error_msg)
raise

Check warning on line 153 in enterprise/management/commands/update_ccb_enterprise_uids.py

View check run for this annotation

Codecov / codecov/patch

enterprise/management/commands/update_ccb_enterprise_uids.py#L150-L153

Added lines #L150 - L153 were not covered by tests

except Exception as e:
error_msg = f"Unexpected error during record update: {e}"
logger.error(error_msg, exc_info=True)
raise

Check warning on line 158 in enterprise/management/commands/update_ccb_enterprise_uids.py

View check run for this annotation

Codecov / codecov/patch

enterprise/management/commands/update_ccb_enterprise_uids.py#L155-L158

Added lines #L155 - L158 were not covered by tests

0 comments on commit 163e776

Please sign in to comment.