diff --git a/apps/sushi/migrations/0028_sushifetchattempt_credentials_version_hash.py b/apps/sushi/migrations/0028_sushifetchattempt_credentials_version_hash.py index 6b4621db..17631146 100644 --- a/apps/sushi/migrations/0028_sushifetchattempt_credentials_version_hash.py +++ b/apps/sushi/migrations/0028_sushifetchattempt_credentials_version_hash.py @@ -1,6 +1,40 @@ # Generated by Django 2.2.12 on 2020-05-22 13:38 +import json +from hashlib import blake2b -from django.db import migrations, models +from django.db import migrations +from django.db import models +from django.db.models import F + + +def get_hash(credentials): + keys = { + 'url', + 'counter_version', + 'requestor_id', + 'customer_id', + 'http_username', + 'http_password', + 'api_key', + 'extra_params', + } + data = {key: getattr(credentials, key) for key in keys} + dump = json.dumps(data, ensure_ascii=False, sort_keys=True) + return blake2b(dump.encode('utf-8'), digest_size=16).hexdigest() + + +def fill_credentials_version_hash(apps, schema_editor): + SushiFetchAttempt = apps.get_model('sushi', 'SushiFetchAttempt') + for fa in SushiFetchAttempt.objects.filter( + timestamp__gte=F('credentials__last_updated') + ).select_related('credentials'): + fa.credentials_version_hash = get_hash(fa.credentials) + fa.save() + + +def reverse(apps, schema_editor): + SushiFetchAttempt = apps.get_model('sushi', 'SushiFetchAttempt') + SushiFetchAttempt.objects.all().update(credentials_version_hash='') class Migration(migrations.Migration): @@ -20,4 +54,8 @@ class Migration(migrations.Migration): ), preserve_default=False, ), + # we are adding the hash of the credentials to attempts based on the last_updated + # date of the credentials. Therefore we need to add it before the credentials + # is modified by adding its hash + migrations.RunPython(fill_credentials_version_hash, reverse), ]