|
| 1 | +import logging |
| 2 | + |
| 3 | +from django.core.exceptions import ValidationError |
| 4 | +from django.db import IntegrityError |
| 5 | + |
| 6 | +from django_setup_configuration.configuration import BaseConfigurationStep |
| 7 | +from django_setup_configuration.exceptions import ConfigurationRunFailed |
| 8 | + |
| 9 | +from objects.setup_configuration.models.token_auth import ( |
| 10 | + TokenAuthGroupConfigurationModel, |
| 11 | +) |
| 12 | +from objects.token.models import TokenAuth |
| 13 | + |
| 14 | +logger = logging.getLogger(__name__) |
| 15 | + |
| 16 | + |
| 17 | +class TokenAuthConfigurationStep( |
| 18 | + BaseConfigurationStep[TokenAuthGroupConfigurationModel] |
| 19 | +): |
| 20 | + """ |
| 21 | + Configure tokens for other applications to access Objects API |
| 22 | + """ |
| 23 | + |
| 24 | + namespace = "tokenauth" |
| 25 | + enable_setting = "tokenauth_config_enable" |
| 26 | + |
| 27 | + verbose_name = "Configuration to set up authentication tokens for objects" |
| 28 | + config_model = TokenAuthGroupConfigurationModel |
| 29 | + |
| 30 | + def execute(self, model: TokenAuthGroupConfigurationModel) -> None: |
| 31 | + if len(model.items) == 0: |
| 32 | + logger.warning("No tokens provided for configuration") |
| 33 | + |
| 34 | + for item in model.items: |
| 35 | + logger.info(f"Configuring {item.identifier}") |
| 36 | + |
| 37 | + model_kwargs = { |
| 38 | + "identifier": item.identifier, |
| 39 | + "token": item.token, |
| 40 | + "contact_person": item.contact_person, |
| 41 | + "email": item.email, |
| 42 | + "organization": item.organization, |
| 43 | + "application": item.application, |
| 44 | + "administration": item.administration, |
| 45 | + "is_superuser": item.is_superuser, |
| 46 | + } |
| 47 | + |
| 48 | + token_instance = TokenAuth(**model_kwargs) |
| 49 | + |
| 50 | + try: |
| 51 | + token_instance.full_clean(exclude=("id",), validate_unique=False) |
| 52 | + except ValidationError as exception: |
| 53 | + exception_message = ( |
| 54 | + f"Validation error(s) occured for {item.identifier}." |
| 55 | + ) |
| 56 | + raise ConfigurationRunFailed(exception_message) from exception |
| 57 | + |
| 58 | + logger.debug(f"No validation errors found for {item.identifier}") |
| 59 | + |
| 60 | + try: |
| 61 | + logger.debug(f"Saving {item.identifier}") |
| 62 | + |
| 63 | + TokenAuth.objects.update_or_create( |
| 64 | + identifier=item.identifier, |
| 65 | + defaults={ |
| 66 | + key: value |
| 67 | + for key, value in model_kwargs.items() |
| 68 | + if key != "identifier" |
| 69 | + }, |
| 70 | + ) |
| 71 | + except IntegrityError as exception: |
| 72 | + exception_message = f"Failed configuring token {item.identifier}." |
| 73 | + raise ConfigurationRunFailed(exception_message) from exception |
| 74 | + |
| 75 | + logger.info(f"Configured {item.identifier}") |
0 commit comments