Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # ###### IBAN Field
- # Write a Django custom Field model to store IBANs. The Field must meet the following requirements:
- # 1. The stored value should never be fully visible - given an IBAN like "GR96 0810 0010 0000 0123 4567 890",
- # the value should be displayed as "---7890" everywhere
- # 2. Superusers should be able to see the full value when needed
- """
- Approach:
- Create a custom field for IBAN to handle data display. Field iban must be private to prevent direct access.
- And must only be accessible using via a method.
- Implement a method to mask iban number when required. Mask method must take user details into account and hide iban number
- for all the users except super-user.
- A template tag is required to access iban from django template. Template tag utlilizes mask method with logged user info.
- And display the iban number.
- USE:
- // load template tag
- {% load mask_utils %}
- // display
- {% mask row.iban user %}
- // user is instance of current logged in user
- Below is the implementation:
- """
- # mask_utils.py
- # start
- from django import template
- register = template.Library()
- @register.simple_tag(name='mask')
- def mask(iban, user):
- return iban(user)
- # end
- # models.py
- # start
- class IBANField(models.TextField):
- MASK_CHAR = '-'
- MASK_CHAR_LENGTH = 8
- DISPLAY_NUMBER_LENGTH = 4
- def __init__(self, *args, **kwargs):
- super().__init__(*args, **kwargs)
- def from_db_value(self, value, expression, connection, context):
- if value is None:
- return value
- return self.display(value)
- @staticmethod
- def _clean(value):
- return value.replace(' ', '')
- def _mask(self, value):
- value = value[-self.DISPLAY_NUMBER_LENGTH:]
- return value.rjust(self.MASK_CHAR_LENGTH, self.MASK_CHAR)
- def display(self, value):
- def mask_wrapper(user):
- if user.is_superuser:
- return value
- return self._mask(self._clean(value))
- return mask_wrapper
- class SomeModel(models.Model):
- # using underscore to keep it private and accessible only via method for lazy evaluation
- _iban = IBANField()
- def iban(self):
- return self._iban
- # end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement