models.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. # -*- coding: utf-8 -*-
  2. import ldapdb.models
  3. import unicodedata
  4. import string
  5. import datetime
  6. from django.db import models
  7. from django.db.models import Q
  8. from django.db.models.signals import pre_save
  9. from django.dispatch import receiver
  10. from ldapdb.models.fields import CharField, IntegerField, ListField
  11. from south.modelsinspector import add_ignored_fields
  12. from coin.offers.models import OfferSubscription
  13. from coin.models import CoinLdapSyncModel
  14. from coin import utils
  15. from django.contrib.auth.signals import user_logged_in
  16. from django.conf import settings
  17. class Member(CoinLdapSyncModel):
  18. MEMBER_TYPE_CHOICES = (
  19. ('personne_physique', 'Personne physique'),
  20. ('personne_morale', 'Personne morale'),
  21. )
  22. MEMBER_STATUS_CHOICES = (
  23. ('adherent', 'Adhérent'),
  24. ('non_adherent', 'Non adhérent'),
  25. ('demande_adhesion', "Demande d'adhésion"),
  26. )
  27. user = models.OneToOneField(settings.AUTH_USER_MODEL,
  28. null=True,
  29. default=None,
  30. verbose_name='Utilisateur Django',
  31. on_delete=models.SET_NULL)
  32. status = models.CharField(max_length=50, choices=MEMBER_STATUS_CHOICES,
  33. default='non_adherent')
  34. type = models.CharField(max_length=20, choices=MEMBER_TYPE_CHOICES,
  35. default='personne_physique')
  36. first_name = models.CharField(max_length=200, verbose_name=u'Prénom')
  37. last_name = models.CharField(max_length=200, verbose_name=u'Nom')
  38. ldap_cn = models.CharField(max_length=200, blank=True,
  39. help_text='Clé avec le LDAP. Laisser vide pour '
  40. 'la générer automatiquement')
  41. organization_name = models.CharField(max_length=200, blank=True,
  42. verbose_name='Nom de l\'organisme',
  43. help_text='Pour une personne morale')
  44. email = models.EmailField(max_length=254, verbose_name=u'Courriel')
  45. home_phone_number = models.CharField(max_length=25, blank=True,
  46. verbose_name=u'Téléphone fixe')
  47. mobile_phone_number = models.CharField(max_length=25, blank=True,
  48. verbose_name=u'Téléphone mobile')
  49. # TODO: use a django module that provides an address model? (would
  50. # support more countries and address types)
  51. address = models.TextField(verbose_name=u'Adresse')
  52. postal_code = models.CharField(max_length=15,
  53. verbose_name=u'Code postal')
  54. city = models.CharField(max_length=200,
  55. verbose_name=u'Commune')
  56. country = models.CharField(max_length=200,
  57. default='France',
  58. verbose_name=u'Pays')
  59. entry_date = models.DateField(null=False,
  60. blank=False,
  61. default=datetime.date.today,
  62. verbose_name='Date de première adhésion')
  63. # TODO: for data retention, prevent deletion of a user object while
  64. # the resign date is recent enough (e.g. one year in France).
  65. resign_date = models.DateField(null=True, blank=True,
  66. verbose_name='Date de départ de '
  67. 'l\'association')
  68. def __unicode__(self):
  69. name = self.first_name + ' ' + self.last_name
  70. if self.organization_name:
  71. name += ' (%s)' % self.organization_name
  72. return name
  73. # Renvoie la date de fin de la dernière cotisation du membre
  74. def end_date_of_membership(self):
  75. try:
  76. return self.membership_fees.order_by('-end_date')[0].end_date
  77. #TODO: bad practice de tout matcher comme ca
  78. except:
  79. return None
  80. def is_paid_up(self):
  81. """
  82. True si le membre est à jour de cotisation. False sinon
  83. """
  84. if self.end_date_of_membership() and self.end_date_of_membership() >= datetime.date.today():
  85. return True
  86. else:
  87. return False
  88. def change_password(self, new_password):
  89. ldap_user = LdapUser.objects.get(pk=self.ldap_cn)
  90. ldap_user.password = new_password
  91. ldap_user.save()
  92. def get_active_subscriptions(self, date=datetime.date.today()):
  93. return OfferSubscription.objects.filter(
  94. Q(member__exact=self.pk),
  95. Q(subscription_date__lte=date),
  96. Q(resign_date__isnull=True) | Q(resign_date__gte=date))
  97. def get_automatic_ldap_cn(self):
  98. """
  99. Calcul le login / ldap_cn automatiquement en fonction
  100. du nom et du prénom
  101. """
  102. # Première lettre de chaque partie du prénom
  103. first_name_letters = ''.join(
  104. [c[0] for c in self.first_name.split('-')]
  105. )
  106. # Concaténer avec nom de famille
  107. ldap_cn = ('%s%s' % (first_name_letters, self.last_name))
  108. # Remplacer ou enlever les caractères non ascii
  109. ldap_cn = unicodedata.normalize('NFD', ldap_cn)\
  110. .encode('ascii', 'ignore')
  111. # Enlever ponctuation et espace
  112. ldap_cn = ldap_cn.translate(None, string.punctuation + ' ')
  113. # En minuscule
  114. ldap_cn = ldap_cn.lower()
  115. return ldap_cn
  116. def sync_to_ldap(self, creation):
  117. """
  118. Update LDAP data when a member is saved
  119. """
  120. assert self.ldap_cn, ('Can\'t sync with LDAP because missing ldap_cn '
  121. 'value for the Member : %s' % self)
  122. if not creation:
  123. ldap_user = LdapUser.objects.get(pk=self.ldap_cn)
  124. if creation:
  125. max_uid_number = LdapUser.objects.order_by('-uidNumber')[0].uidNumber
  126. ldap_user = LdapUser()
  127. ldap_user.pk = self.ldap_cn
  128. ldap_user.uid = self.ldap_cn
  129. ldap_user.nick_name = self.ldap_cn
  130. ldap_user.uidNumber = max_uid_number + 1
  131. ldap_user.last_name = self.last_name
  132. ldap_user.first_name = self.first_name
  133. ldap_user.save()
  134. if creation:
  135. ldap_group = LdapGroup.objects.get(pk='coin')
  136. ldap_group.members.append(ldap_user.pk)
  137. ldap_group.save()
  138. def delete_from_ldap(self):
  139. """
  140. Delete member from the LDAP
  141. """
  142. assert self.ldap_cn, ('Can\'t delete from LDAP because missing '
  143. 'ldap_cn value for the Member : %s' % self)
  144. # Lorsqu'un membre est supprimé du SI, son utilisateur LDAP
  145. # correspondant est sorti du groupe "coin" afin qu'il n'ait plus
  146. # accès au SI
  147. ldap_group = LdapGroup.objects.get(pk='coin')
  148. if self.ldap_cn in ldap_group.members:
  149. ldap_group.members.remove(self.ldap_cn)
  150. ldap_group.save()
  151. class Meta:
  152. verbose_name = 'membre'
  153. class CryptoKey(models.Model):
  154. KEY_TYPE_CHOICES = (('RSA', 'RSA'), ('GPG', 'GPG'))
  155. type = models.CharField(max_length=3, choices=KEY_TYPE_CHOICES)
  156. key = models.TextField(verbose_name=u'Clé')
  157. member = models.ForeignKey('Member', verbose_name=u'Membre')
  158. def __unicode__(self):
  159. return u'Clé %s de %s' % (self.type, self.member)
  160. class Meta:
  161. verbose_name = 'clé'
  162. class MembershipFee(models.Model):
  163. member = models.ForeignKey('Member', related_name='membership_fees',
  164. verbose_name=u'Membre')
  165. amount = models.IntegerField(null=False, default='20', help_text='en €',
  166. verbose_name=u'Montant')
  167. start_date = models.DateField(
  168. null=False,
  169. blank=False,
  170. default=datetime.date.today,
  171. verbose_name='Date de début de cotisation')
  172. end_date = models.DateField(
  173. null=False,
  174. blank=False,
  175. default=datetime.date.today() + datetime.timedelta(365),
  176. verbose_name='Date de fin de cotisation')
  177. def __unicode__(self):
  178. return u'%s - %s - %i€' % (self.member, self.start_date, self.amount)
  179. class Meta:
  180. verbose_name = 'cotisation'
  181. class LdapUser(ldapdb.models.Model):
  182. # TODO: déplacer ligne suivante dans settings.py
  183. base_dn = "ou=users,ou=unix,o=ILLYSE,l=Villeurbanne,st=RHA,c=FR"
  184. object_classes = ['inetOrgPerson', 'organizationalPerson', 'person',
  185. 'top', 'posixAccount']
  186. uid = CharField(db_column='uid', unique=True, max_length=255)
  187. nick_name = CharField(db_column='cn', unique=True, primary_key=True,
  188. max_length=255)
  189. first_name = CharField(db_column='givenName', max_length=255)
  190. last_name = CharField(db_column='sn', max_length=255)
  191. display_name = CharField(db_column='displayName', max_length=255,
  192. blank=True)
  193. password = CharField(db_column='userPassword', max_length=255)
  194. uidNumber = IntegerField(db_column='uidNumber', unique=True)
  195. gidNumber = IntegerField(db_column='gidNumber', default=2000)
  196. homeDirectory = CharField(db_column='homeDirectory', max_length=255,
  197. default='/tmp')
  198. def __unicode__(self):
  199. return self.display_name
  200. class Meta:
  201. managed = False # Indique à South de ne pas gérer le model LdapUser
  202. class LdapGroup(ldapdb.models.Model):
  203. """
  204. Class for representing an LDAP group entry.
  205. """
  206. #TODO: config à externaliser
  207. # LDAP meta-data
  208. base_dn = "ou=groups,ou=unix,o=ILLYSE,l=Villeurbanne,st=RHA,c=FR"
  209. object_classes = ['posixGroup']
  210. # posixGroup attributes
  211. gid = IntegerField(db_column='gidNumber', unique=True)
  212. name = CharField(db_column='cn', max_length=200, primary_key=True)
  213. members = ListField(db_column='memberUid')
  214. def __unicode__(self):
  215. return self.name
  216. class Meta:
  217. managed = False # Indique à South de ne pas gérer le model LdapGroup
  218. # Indique à South de ne pas gérer les models LdapUser et LdapGroup
  219. add_ignored_fields(["^ldapdb\.models\.fields"])
  220. @receiver(pre_save, sender=Member)
  221. def define_ldap_cn(sender, instance, **kwargs):
  222. """
  223. Lors de la sauvegarde d'un membre. Si le champ ldap_cn n'est pas définit,
  224. le calcul automatiquement en fonction du nom et du prénom
  225. """
  226. if not instance.ldap_cn and not instance.pk:
  227. instance.ldap_cn = instance.get_automatic_ldap_cn()
  228. @receiver(pre_save, sender=LdapUser)
  229. def change_password(sender, instance, **kwargs):
  230. """
  231. Lors de la sauvegarde d'un utilisateur Ldap, cette fonction est exécutée
  232. avant la sauvegarde pour chiffrer le mot de passe s'il est définit
  233. et s'il n'est pas déjà chiffré
  234. """
  235. instance.password = utils.ldap_hash(instance.password)
  236. @receiver(pre_save, sender=LdapUser)
  237. def define_display_name(sender, instance, **kwargs):
  238. """
  239. Lors de la sauvegarde d'un utilisateur Ldap, le champ display_name est la
  240. concaténation de first_name et last_name
  241. """
  242. if not instance.display_name:
  243. instance.display_name = '%s %s' % (instance.first_name,
  244. instance.last_name)
  245. @receiver(user_logged_in)
  246. def define_member_user(sender, request, user, **kwargs):
  247. """
  248. Lorsqu'un utilisateur se connect avec succes, fait le lien entre le membre
  249. et l'utilisateur en définissant le champ user du model membre ayant le
  250. ldap_cn utilisé pour la connexion
  251. """
  252. try:
  253. member = Member.objects.get(ldap_cn=user.username)
  254. if not member.user:
  255. member.user = user
  256. member.save()
  257. elif member.user.username != user.username:
  258. raise Exception('Un membre avec cet ldap_cn existe en base de '
  259. 'donnée mais l\'utilisateur auquel il est rattaché '
  260. 'ne correspond pas.')
  261. except Member.DoesNotExist:
  262. if not user.is_superuser:
  263. raise
  264. #==============================================================================
  265. # @receiver(pre_save, sender = LdapUser)
  266. # def ssha_password(sender, **kwargs):
  267. # if not kwargs['instance'].password.startswith('{SSHA}'):
  268. # salt = os.urandom(8).encode('hex')
  269. # kwargs['instance'].password = '{SSHA}' + base64.b64encode(
  270. # hashlib.sha1(obj.password + salt).digest() + salt)
  271. #==============================================================================