PageRenderTime 66ms CodeModel.GetById 33ms RepoModel.GetById 1ms app.codeStats 0ms

/satchmo/apps/payment/models.py

https://github.com/goodguy/satchmo
Python | 127 lines | 107 code | 7 blank | 13 comment | 3 complexity | e41037ccbf3f6c533de0b920cd932ab4 MD5 | raw file
  1. """
  2. Stores details about the available payment options.
  3. Also stores credit card info in an encrypted format.
  4. """
  5. from Crypto.Cipher import Blowfish
  6. from datetime import datetime
  7. from decimal import Decimal
  8. from django.conf import settings
  9. from django.db import models
  10. from django.utils.translation import ugettext_lazy as _
  11. from livesettings import config_value, config_choice_values, SettingNotSet
  12. from satchmo_utils.iterchoices import iterchoices_db
  13. import payment.config
  14. from satchmo_store.contact.models import Contact
  15. import base64
  16. import config
  17. import keyedcache
  18. import logging
  19. import satchmo_utils.sslurllib
  20. log = logging.getLogger('payment.models')
  21. class PaymentOption(models.Model):
  22. """
  23. If there are multiple options - CC, Cash, COD, etc this class allows
  24. configuration.
  25. """
  26. description = models.CharField(_("Description"), max_length=20)
  27. active = models.BooleanField(_("Active"),
  28. help_text=_("Should this be displayed as an option for the user?"))
  29. optionName = models.CharField(_("Option Name"), max_length=20, choices=iterchoices_db(payment.config.labelled_gateway_choices),
  30. unique=True,
  31. help_text=_("The class name as defined in payment.py"))
  32. sortOrder = models.IntegerField(_("Sort Order"))
  33. class Meta:
  34. verbose_name = _("Payment Option")
  35. verbose_name_plural = _("Payment Options")
  36. class CreditCardDetail(models.Model):
  37. """
  38. Stores an encrypted CC number, its information, and its
  39. displayable number.
  40. """
  41. orderpayment = models.ForeignKey('shop.OrderPayment', unique=True,
  42. related_name="creditcards")
  43. credit_type = models.CharField(_("Credit Card Type"), max_length=16, choices=iterchoices_db(payment.config.credit_choices))
  44. display_cc = models.CharField(_("CC Number (Last 4 digits)"),
  45. max_length=4, )
  46. encrypted_cc = models.CharField(_("Encrypted Credit Card"),
  47. max_length=40, blank=True, null=True, editable=False)
  48. expire_month = models.IntegerField(_("Expiration Month"))
  49. expire_year = models.IntegerField(_("Expiration Year"))
  50. card_holder = models.CharField(_("card_holder Name"), max_length=60, blank=True)
  51. start_month = models.IntegerField(_("Start Month"), blank=True, null=True)
  52. start_year = models.IntegerField(_("Start Year"), blank=True, null=True)
  53. issue_num = models.CharField(blank=True, null=True, max_length=2)
  54. def storeCC(self, ccnum):
  55. """Take as input a valid cc, encrypt it and store the last 4 digits in a visible form"""
  56. self.display_cc = ccnum[-4:]
  57. encrypted_cc = _encrypt_code(ccnum)
  58. if config_value('PAYMENT', 'STORE_CREDIT_NUMBERS'):
  59. self.encrypted_cc = encrypted_cc
  60. else:
  61. standin = "%s%i%i%i" % (self.display_cc, self.expire_month, self.expire_year, self.orderpayment.id)
  62. self.encrypted_cc = _encrypt_code(standin)
  63. key = _encrypt_code(standin + '-card')
  64. keyedcache.cache_set(key, skiplog=True, length=60*60, value=encrypted_cc)
  65. def setCCV(self, ccv):
  66. """Put the CCV in the cache, don't save it for security/legal reasons."""
  67. if not self.encrypted_cc:
  68. raise ValueError('CreditCardDetail expecting a credit card number to be stored before storing CCV')
  69. keyedcache.cache_set(self.encrypted_cc, skiplog=True, length=60*60, value=ccv)
  70. def getCCV(self):
  71. try:
  72. ccv = keyedcache.cache_get(self.encrypted_cc)
  73. except keyedcache.NotCachedError:
  74. ccv = ""
  75. return ccv
  76. ccv = property(fget=getCCV, fset=setCCV)
  77. def _decryptCC(self):
  78. ccnum = _decrypt_code(self.encrypted_cc)
  79. if not config_value('PAYMENT', 'STORE_CREDIT_NUMBERS'):
  80. try:
  81. key = _encrypt_code(ccnum + '-card')
  82. encrypted_ccnum = keyedcache.cache_get(key)
  83. ccnum = _decrypt_code(encrypted_ccnum)
  84. except keyedcache.NotCachedError:
  85. ccnum = ""
  86. return ccnum
  87. decryptedCC = property(_decryptCC)
  88. def _expireDate(self):
  89. return(str(self.expire_month) + "/" + str(self.expire_year))
  90. expirationDate = property(_expireDate)
  91. class Meta:
  92. verbose_name = _("Credit Card")
  93. verbose_name_plural = _("Credit Cards")
  94. def _decrypt_code(code):
  95. """Decrypt code encrypted by _encrypt_code"""
  96. # In some blowfish implementations, > 56 char keys can cause problems
  97. secret_key = settings.SECRET_KEY[:56]
  98. encryption_object = Blowfish.new(secret_key)
  99. # strip padding from decrypted credit card number
  100. return encryption_object.decrypt(base64.b64decode(code)).rstrip('X')
  101. def _encrypt_code(code):
  102. """Quick encrypter for CC codes or code fragments"""
  103. # In some blowfish implementations, > 56 char keys can cause problems
  104. secret_key = settings.SECRET_KEY[:56]
  105. encryption_object = Blowfish.new(secret_key)
  106. # block cipher length must be a multiple of 8
  107. padding = ''
  108. if (len(code) % 8) <> 0:
  109. padding = 'X' * (8 - (len(code) % 8))
  110. return base64.b64encode(encryption_object.encrypt(code + padding))