Advertisement
Guest User

Untitled

a guest
Oct 17th, 2019
218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.14 KB | None | 0 0
  1. # ###### IBAN Field
  2. # Write a Django custom Field model to store IBANs. The Field must meet the following requirements:
  3. # 1. The stored value should never be fully visible - given an IBAN like "GR96 0810 0010 0000 0123 4567 890",
  4. # the value should be displayed as "---7890" everywhere
  5. # 2. Superusers should be able to see the full value when needed
  6.  
  7. """
  8. Approach:
  9. Create a custom field for IBAN to handle data display. Field iban must be private to prevent direct access.
  10. And must only be accessible using via a method.
  11.  
  12. Implement a method to mask iban number when required. Mask method must take user details into account and hide iban number
  13. for all the users except super-user.
  14.  
  15. A template tag is required to access iban from django template. Template tag utlilizes mask method with logged user info.
  16. And display the iban number.
  17.  
  18. USE:
  19. // load template tag
  20. {% load mask_utils %}
  21.  
  22. // display
  23. {% mask row.iban user %}
  24. // user is instance of current logged in user
  25.  
  26. Below is the implementation:
  27. """
  28.  
  29. # mask_utils.py
  30. # start
  31. from django import template
  32. register = template.Library()
  33.  
  34. @register.simple_tag(name='mask')
  35. def mask(iban, user):
  36. return iban(user)
  37.  
  38. # end
  39.  
  40. # models.py
  41. # start
  42. class IBANField(models.TextField):
  43.  
  44. MASK_CHAR = '-'
  45. MASK_CHAR_LENGTH = 8
  46. DISPLAY_NUMBER_LENGTH = 4
  47.  
  48. def __init__(self, *args, **kwargs):
  49. super().__init__(*args, **kwargs)
  50.  
  51. def from_db_value(self, value, expression, connection, context):
  52. if value is None:
  53. return value
  54. return self.display(value)
  55.  
  56. @staticmethod
  57. def _clean(value):
  58. return value.replace(' ', '')
  59.  
  60. def _mask(self, value):
  61. value = value[-self.DISPLAY_NUMBER_LENGTH:]
  62. return value.rjust(self.MASK_CHAR_LENGTH, self.MASK_CHAR)
  63.  
  64. def display(self, value):
  65. def mask_wrapper(user):
  66. if user.is_superuser:
  67. return value
  68. return self._mask(self._clean(value))
  69. return mask_wrapper
  70.  
  71.  
  72. class SomeModel(models.Model):
  73.  
  74. # using underscore to keep it private and accessible only via method for lazy evaluation
  75. _iban = IBANField()
  76.  
  77. def iban(self):
  78. return self._iban
  79.  
  80.  
  81. # end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement