models.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. import ldapdb.models
  4. import unicodedata
  5. import datetime
  6. from django.db import models
  7. from django.db.models import Q, Max
  8. from django.db.models.signals import pre_save
  9. from django.dispatch import receiver
  10. from django.contrib.auth.models import AbstractUser, Permission, UserManager
  11. from django.contrib.contenttypes.models import ContentType
  12. from django.conf import settings
  13. from django.core.validators import RegexValidator
  14. from django.core.exceptions import ValidationError
  15. from django.utils import timezone
  16. from django.utils.text import slugify
  17. from ldapdb.models.fields import CharField, IntegerField, ListField
  18. from coin.offers.models import Offer, OfferSubscription
  19. from coin.mixins import CoinLdapSyncMixin
  20. from coin import utils
  21. class MemberManager(UserManager):
  22. def manageable_by(self, user):
  23. """" Renvoie la liste des members que l'utilisateur est autorisé à voir
  24. dans l'interface d'administration.
  25. """
  26. if user.is_superuser:
  27. return super(MemberManager, self).all()
  28. else:
  29. offers = Offer.objects.manageable_by(user)
  30. return super(MemberManager, self).filter(offersubscription__offer__in=offers).distinct()
  31. class Member(CoinLdapSyncMixin, AbstractUser):
  32. # USERNAME_FIELD = 'login'
  33. REQUIRED_FIELDS = ['first_name', 'last_name', 'email', ]
  34. MEMBER_TYPE_CHOICES = (
  35. ('natural_person', 'Personne physique'),
  36. ('legal_entity', 'Personne morale'),
  37. )
  38. MEMBER_STATUS_MEMBER = 'member'
  39. MEMBER_STATUS_NOT_MEMBER = 'not_member'
  40. MEMBER_STATUS_PENDING = 'pending'
  41. MEMBER_STATUS_CHOICES = (
  42. (MEMBER_STATUS_MEMBER, 'Adhérent'),
  43. (MEMBER_STATUS_NOT_MEMBER, 'Non adhérent'),
  44. (MEMBER_STATUS_PENDING, "Demande d'adhésion"),
  45. )
  46. status = models.CharField(max_length=50, choices=MEMBER_STATUS_CHOICES,
  47. default='member', verbose_name='statut')
  48. type = models.CharField(max_length=20, choices=MEMBER_TYPE_CHOICES,
  49. default='natural_person', verbose_name='type')
  50. nickname = models.CharField(max_length=64, blank=True,
  51. verbose_name="nom d'usage",
  52. help_text='Pseudonyme, …')
  53. organization_name = models.CharField(max_length=200, blank=True,
  54. verbose_name="nom de l'organisme",
  55. help_text='Pour une personne morale')
  56. home_phone_number = models.CharField(max_length=25, blank=True,
  57. verbose_name='téléphone fixe')
  58. mobile_phone_number = models.CharField(max_length=25, blank=True,
  59. verbose_name='téléphone mobile')
  60. # TODO: use a django module that provides an address model? (would
  61. # support more countries and address types)
  62. address = models.TextField(
  63. verbose_name='adresse postale', blank=True, null=True)
  64. postal_code = models.CharField(max_length=5, blank=True, null=True,
  65. validators=[RegexValidator(regex=r'^\d{5}$',
  66. message='Code postal non valide.')],
  67. verbose_name='code postal')
  68. city = models.CharField(max_length=200, blank=True, null=True,
  69. verbose_name='commune')
  70. country = models.CharField(max_length=200, blank=True, null=True,
  71. default='France',
  72. verbose_name='pays')
  73. resign_date = models.DateField(null=True, blank=True,
  74. verbose_name="date de départ de "
  75. "l'association",
  76. help_text="En cas de départ prématuré")
  77. comments = models.TextField(blank=True, verbose_name='commentaires',
  78. help_text="Commentaires libres (informations"
  79. " spécifiques concernant l'adhésion,"
  80. " raison du départ, etc)")
  81. date_last_call_for_membership_fees_email = models.DateTimeField(null=True,
  82. blank=True,
  83. verbose_name="Date du dernier email de relance de cotisation envoyé")
  84. send_membership_fees_email = models.BooleanField(
  85. default=True, verbose_name='relance de cotisation',
  86. help_text='Précise si l\'utilisateur doit recevoir des mails de relance pour la cotisation. Certains membres n\'ont pas à recevoir de relance (prélèvement automatique, membres d\'honneurs, etc.)')
  87. balance = models.DecimalField(max_digits=5, decimal_places=2, default=0,
  88. verbose_name='solde')
  89. objects = MemberManager()
  90. # Following fields are managed by the parent class AbstractUser :
  91. # username, first_name, last_name, email
  92. # However we hack the model to force theses fields to be required. (see
  93. # below)
  94. # This property is used to change password in LDAP. Used in sync_to_ldap.
  95. # Should not be defined manually. Prefer use set_password method that hash
  96. # passwords for both ldap and local db
  97. _password_ldap = None
  98. def clean(self):
  99. if self.type == 'legal_entity':
  100. if not self.organization_name:
  101. raise ValidationError("Le nom de l'organisme est obligatoire "
  102. "pour une personne morale")
  103. elif self.type == 'natural_person':
  104. if not (self.first_name and self.last_name):
  105. raise ValidationError("Le nom et prénom sont obligatoires "
  106. "pour une personne physique")
  107. def __unicode__(self):
  108. if self.type == 'legal_entity':
  109. return self.organization_name
  110. elif self.nickname:
  111. return self.nickname
  112. else:
  113. return self.first_name + ' ' + self.last_name
  114. def get_full_name(self):
  115. return str(self)
  116. def get_short_name(self):
  117. return self.username
  118. # Renvoie la date de fin de la dernière cotisation du membre
  119. def end_date_of_membership(self):
  120. aggregate = self.membership_fees.aggregate(end=Max('end_date'))
  121. return aggregate['end']
  122. end_date_of_membership.short_description = "Date de fin d'adhésion"
  123. def is_paid_up(self, date=None):
  124. """
  125. Teste si le membre est à jour de cotisation à la date donnée.
  126. """
  127. if date is None:
  128. date = datetime.date.today()
  129. end_date = self.end_date_of_membership()
  130. if end_date is None:
  131. return False
  132. return (end_date >= date)
  133. def set_password(self, new_password, *args, **kwargs):
  134. """
  135. Définit le mot de passe a sauvegarder en base et dans le LDAP
  136. """
  137. super(Member, self).set_password(new_password, *args, **kwargs)
  138. self._password_ldap = utils.ldap_hash(new_password)
  139. def get_active_subscriptions(self, date=None):
  140. """
  141. Return list of OfferSubscription which are active today
  142. """
  143. if date is None:
  144. date = datetime.date.today()
  145. return OfferSubscription.objects.filter(
  146. Q(member__exact=self.pk),
  147. Q(subscription_date__lte=date),
  148. Q(resign_date__isnull=True) | Q(resign_date__gte=date))
  149. def get_inactive_subscriptions(self, date=None):
  150. """
  151. Return list of OfferSubscription which are not active today
  152. """
  153. if date is None:
  154. date = datetime.date.today()
  155. return OfferSubscription.objects.filter(
  156. Q(member__exact=self.pk),
  157. Q(subscription_date__gt=date) |
  158. Q(resign_date__lt=date))
  159. def get_ssh_keys(self):
  160. # Quick & dirty, ensure that keys are unique (otherwise, LDAP complains)
  161. return list({k.key for k in self.cryptokey_set.filter(type='RSA')})
  162. def sync_ssh_keys(self):
  163. """
  164. Called whenever a SSH key is saved
  165. """
  166. ldap_user = LdapUser.objects.get(pk=self.username)
  167. ldap_user.sshPublicKey = self.get_ssh_keys()
  168. ldap_user.save()
  169. def sync_to_ldap(self, creation, update_fields, *args, **kwargs):
  170. """
  171. Update LDAP data when a member is saved
  172. """
  173. # Do not perform LDAP query if no usefull fields to update are specified
  174. # in update_fields
  175. # Ex : at login, last_login field is updated by django auth module.
  176. relevant_fields = {'username', 'last_name', 'first_name',
  177. 'organization_name', 'email'}
  178. if update_fields and relevant_fields.isdisjoint(set(update_fields)):
  179. return
  180. # Fail if no username specified
  181. assert self.username, ('Can\'t sync with LDAP because missing username '
  182. 'value for the Member : %s' % self)
  183. # If try to sync a superuser in creation mode
  184. # Try to retrieve the user in ldap. If exists, switch to update mode
  185. # This allow to create a superuser without having to delete corresponding
  186. # username in LDAP
  187. if self.is_superuser and creation:
  188. try:
  189. ldap_user = LdapUser.objects.get(pk=self.username)
  190. creation = False
  191. except LdapUser.DoesNotExist:
  192. pass
  193. if not creation:
  194. ldap_user = LdapUser.objects.get(pk=self.username)
  195. if creation:
  196. users = LdapUser.objects
  197. if users.exists():
  198. uid_number = users.order_by('-uidNumber')[0].uidNumber + 1
  199. else:
  200. uid_number = settings.LDAP_USER_FIRST_UID
  201. ldap_user = LdapUser()
  202. ldap_user.pk = self.username
  203. ldap_user.uid = self.username
  204. ldap_user.nick_name = self.username
  205. ldap_user.uidNumber = uid_number
  206. ldap_user.homeDirectory = '/home/' + self.username
  207. if self.type == 'natural_person':
  208. ldap_user.last_name = self.last_name
  209. ldap_user.first_name = self.first_name
  210. elif self.type == 'legal_entity':
  211. ldap_user.last_name = self.organization_name
  212. ldap_user.first_name = ""
  213. # If a password is definied in _password_ldap, change it in LDAP
  214. if self._password_ldap:
  215. # Make sure password is hashed
  216. ldap_user.password = utils.ldap_hash(self._password_ldap)
  217. ldap_user.mail = self.email
  218. # Store SSH keys
  219. ldap_user.sshPublicKey = self.get_ssh_keys()
  220. ldap_user.save()
  221. # if creation:
  222. # ldap_group = LdapGroup.objects.get(pk='coin')
  223. # ldap_group.members.append(ldap_user.pk)
  224. # ldap_group.save()
  225. def delete_from_ldap(self):
  226. """
  227. Delete member from the LDAP
  228. """
  229. assert self.username, ('Can\'t delete from LDAP because missing '
  230. 'username value for the Member : %s' % self)
  231. # Delete user from LDAP
  232. ldap_user = LdapUser.objects.get(pk=self.username)
  233. ldap_user.delete()
  234. # Lorsqu'un membre est supprimé du SI, son utilisateur LDAP
  235. # correspondant est sorti du groupe "coin" afin qu'il n'ait plus
  236. # accès au SI
  237. # ldap_group = LdapGroup.objects.get(pk='coin')
  238. # if self.username in ldap_group.members:
  239. # ldap_group.members.remove(self.username)
  240. # ldap_group.save()
  241. def send_welcome_email(self):
  242. """ Envoie le courriel de bienvenue à ce membre """
  243. from coin.isp_database.models import ISPInfo
  244. isp_info = ISPInfo.objects.first()
  245. kwargs = {}
  246. if isp_info.administrative_email:
  247. kwargs['from_email'] = isp_info.administrative_email
  248. utils.send_templated_email(
  249. to=self.email,
  250. subject_template='members/emails/welcome_email_subject.txt',
  251. body_template='members/emails/welcome_email.html',
  252. context={'member': self, 'branding': isp_info},
  253. **kwargs)
  254. def send_call_for_membership_fees_email(self, auto=False):
  255. """ Envoie le courriel d'appel à cotisation du membre
  256. :param auto: is it an auto email? (changes slightly template content)
  257. """
  258. if auto and not self.send_membership_fees_email:
  259. return False
  260. from dateutil.relativedelta import relativedelta
  261. from coin.isp_database.models import ISPInfo
  262. isp_info = ISPInfo.objects.first()
  263. kwargs = {}
  264. # Il peut ne pas y avir d'ISPInfo, ou bien pas d'administrative_email
  265. if isp_info and isp_info.administrative_email:
  266. kwargs['from_email'] = isp_info.administrative_email
  267. # Si le dernier courriel de relance a été envoyé il y a moins de trois
  268. # semaines, n'envoi pas un nouveau courriel
  269. if (not self.date_last_call_for_membership_fees_email
  270. or (self.date_last_call_for_membership_fees_email
  271. <= timezone.now() + relativedelta(weeks=-3))):
  272. utils.send_templated_email(
  273. to=self.email,
  274. subject_template='members/emails/call_for_membership_fees_subject.txt',
  275. body_template='members/emails/call_for_membership_fees.html',
  276. context={'member': self, 'branding': isp_info,
  277. 'membership_info_url': settings.MEMBER_MEMBERSHIP_INFO_URL,
  278. 'today': datetime.date.today,
  279. 'auto_sent': auto},
  280. **kwargs)
  281. # Sauvegarde en base la date du dernier envoi de mail de relance
  282. self.date_last_call_for_membership_fees_email = timezone.now()
  283. self.save()
  284. return True
  285. return False
  286. class Meta:
  287. verbose_name = 'membre'
  288. # Hack to force email to be required by Member model
  289. Member._meta.get_field('email')._unique = True
  290. Member._meta.get_field('email').blank = False
  291. Member._meta.get_field('email').null = False
  292. def count_active_members():
  293. return Member.objects.filter(status='member').count()
  294. def get_automatic_username(member):
  295. """
  296. Calcul le username automatiquement en fonction
  297. du nom et du prénom
  298. """
  299. # S'il s'agit d'une entreprise, utilise son nom:
  300. if member.type == 'legal_entity' and member.organization_name:
  301. username = member.organization_name
  302. # Sinon, si un pseudo est définit, l'utilise
  303. elif member.nickname:
  304. username = member.nickname
  305. # Sinon, utilise nom et prenom
  306. elif member.first_name and member.last_name:
  307. # Première lettre de chaque partie du prénom
  308. first_name_letters = ''.join(
  309. [c[0] for c in member.first_name.split('-')]
  310. )
  311. # Concaténer avec nom de famille
  312. username = ('%s%s' % (first_name_letters, member.last_name))
  313. else:
  314. raise Exception('Il n\'y a pas sufissement d\'informations pour déterminer un login automatiquement')
  315. # Remplacer ou enlever les caractères non ascii
  316. username = unicodedata.normalize('NFD', username)\
  317. .encode('ascii', 'ignore')
  318. # Enlever ponctuation (sauf _-.) et espace
  319. punctuation = ('!"#$%&\'()*+,/:;<=>?@[\\]^`{|}~ ').encode('ascii')
  320. username = username.translate(None, punctuation)
  321. # En minuscule
  322. username = username.lower()
  323. # Maximum de 30 char
  324. username = username[:30]
  325. # Recherche dans les membres existants un username identique
  326. member = Member.objects.filter(username=username)
  327. base_username = username
  328. incr = 2
  329. # Tant qu'un membre est trouvé, incrémente un entier à la fin
  330. while member:
  331. if len(base_username) >= 30:
  332. username = base_username[30 - len(str(incr)):]
  333. else:
  334. username = base_username
  335. username = username + str(incr)
  336. member = Member.objects.filter(username=username)
  337. incr += 1
  338. return username
  339. class CryptoKey(CoinLdapSyncMixin, models.Model):
  340. KEY_TYPE_CHOICES = (('RSA', 'RSA'), ('GPG', 'GPG'))
  341. type = models.CharField(max_length=3, choices=KEY_TYPE_CHOICES,
  342. verbose_name='type')
  343. key = models.TextField(verbose_name='clé')
  344. member = models.ForeignKey('Member', verbose_name='membre')
  345. def sync_to_ldap(self, creation, *args, **kwargs):
  346. """Simply tell the member object to resync all its SSH keys to LDAP"""
  347. self.member.sync_ssh_keys()
  348. def delete_from_ldap(self, *args, **kwargs):
  349. self.member.sync_ssh_keys()
  350. def __unicode__(self):
  351. return 'Clé %s de %s' % (self.type, self.member)
  352. class Meta:
  353. verbose_name = 'clé'
  354. class MembershipFee(models.Model):
  355. PAYMENT_METHOD_CHOICES = (
  356. ('cash', 'Espèces'),
  357. ('check', 'Chèque'),
  358. ('transfer', 'Virement'),
  359. ('other', 'Autre')
  360. )
  361. member = models.ForeignKey('Member', related_name='membership_fees',
  362. verbose_name='membre')
  363. amount = models.DecimalField(null=False, max_digits=5, decimal_places=2,
  364. default=settings.DEFAULT_MEMBERSHIP_FEE,
  365. verbose_name='montant', help_text='en €')
  366. start_date = models.DateField(
  367. null=False,
  368. blank=False,
  369. verbose_name='date de début de cotisation')
  370. end_date = models.DateField(
  371. null=False,
  372. blank=True,
  373. verbose_name='date de fin de cotisation',
  374. help_text='par défaut, la cotisation dure un an')
  375. payment_method = models.CharField(max_length=100, null=True, blank=True,
  376. choices=PAYMENT_METHOD_CHOICES,
  377. verbose_name='moyen de paiement')
  378. reference = models.CharField(max_length=125, null=True, blank=True,
  379. verbose_name='référence du paiement',
  380. help_text='numéro de chèque, '
  381. 'référence de virement, commentaire...')
  382. payment_date = models.DateField(null=True, blank=True,
  383. verbose_name='date du paiement')
  384. def clean(self):
  385. if self.start_date is not None and self.end_date is None:
  386. self.end_date = self.start_date + datetime.timedelta(364)
  387. def __unicode__(self):
  388. return '%s - %s - %i€' % (self.member, self.start_date, self.amount)
  389. class Meta:
  390. verbose_name = 'cotisation'
  391. class LdapUser(ldapdb.models.Model):
  392. # "ou=users,ou=unix,o=ILLYSE,l=Villeurbanne,st=RHA,c=FR"
  393. base_dn = settings.LDAP_USER_BASE_DN
  394. object_classes = [b'inetOrgPerson', b'organizationalPerson', b'person',
  395. b'top', b'posixAccount', b'ldapPublicKey']
  396. uid = CharField(db_column=b'uid', unique=True, max_length=255)
  397. nick_name = CharField(db_column=b'cn', unique=True, primary_key=True,
  398. max_length=255)
  399. first_name = CharField(db_column=b'givenName', max_length=255)
  400. last_name = CharField(db_column=b'sn', max_length=255)
  401. display_name = CharField(db_column=b'displayName', max_length=255,
  402. blank=True)
  403. password = CharField(db_column=b'userPassword', max_length=255)
  404. uidNumber = IntegerField(db_column=b'uidNumber', unique=True)
  405. gidNumber = IntegerField(db_column=b'gidNumber', default=2000)
  406. # Used by Sympa for logging in.
  407. mail = CharField(db_column=b'mail', max_length=255, blank=True,
  408. unique=True)
  409. homeDirectory = CharField(db_column=b'homeDirectory', max_length=255,
  410. default='/tmp')
  411. loginShell = CharField(db_column=b'loginShell', max_length=255,
  412. default='/bin/bash')
  413. sshPublicKey = ListField(db_column=b'sshPublicKey', default=[])
  414. def __unicode__(self):
  415. return self.display_name
  416. class Meta:
  417. managed = False # Indique à Django de ne pas intégrer ce model en base
  418. # class LdapGroup(ldapdb.models.Model):
  419. # "ou=groups,ou=unix,o=ILLYSE,l=Villeurbanne,st=RHA,c=FR"
  420. # base_dn = settings.LDAP_GROUP_BASE_DN
  421. # object_classes = [b'posixGroup']
  422. # gid = IntegerField(db_column=b'gidNumber', unique=True)
  423. # name = CharField(db_column=b'cn', max_length=200, primary_key=True)
  424. # members = ListField(db_column=b'memberUid')
  425. # def __unicode__(self):
  426. # return self.name
  427. # class Meta:
  428. # managed = False # Indique à Django de ne pas intégrer ce model en base
  429. @receiver(pre_save, sender=Member)
  430. def define_username(sender, instance, **kwargs):
  431. """
  432. Lors de la sauvegarde d'un membre. Si le champ username n'est pas définit,
  433. le calcul automatiquement en fonction du nom et du prénom
  434. """
  435. if not instance.username and not instance.pk:
  436. instance.username = get_automatic_username(instance)
  437. @receiver(pre_save, sender=LdapUser)
  438. def define_display_name(sender, instance, **kwargs):
  439. """
  440. Lors de la sauvegarde d'un utilisateur Ldap, le champ display_name est la
  441. concaténation de first_name et last_name
  442. """
  443. if not instance.display_name:
  444. instance.display_name = '%s %s' % (instance.first_name,
  445. instance.last_name)
  446. class RowLevelPermission(Permission):
  447. offer = models.ForeignKey(
  448. 'offers.Offer', null=True, verbose_name="Offre",
  449. help_text="Offre dont l'utilisateur est autorisé à voir et modifier les membres et les abonnements.")
  450. description = models.TextField(blank=True)
  451. def save(self, *args, **kwargs):
  452. """
  453. Lors de la sauvegarde d'une RowLevelPermission. Si le champ codename n'est pas définit,
  454. le calcul automatiquement.
  455. """
  456. if not self.codename:
  457. self.codename = self.generate_codename()
  458. return super(RowLevelPermission, self).save(*args, **kwargs)
  459. def generate_codename(self):
  460. """
  461. Calcule le codename automatiquement en fonction du name.
  462. """
  463. # Convertit en ASCII. Convertit les espaces en tirets. Enlève les caractères qui ne sont ni alphanumériques, ni soulignements, ni tirets. Convertit en minuscules. Les espaces en début et fin de chaîne sont aussi enlevés
  464. codename = slugify(self.name)
  465. # Maximum de 30 char
  466. codename = codename[:30]
  467. # Recherche dans les membres existants un codename identique
  468. perm = Permission.objects.filter(codename=codename)
  469. base_codename = codename
  470. incr = 2
  471. # Tant qu'une permission est trouvée, incrémente un entier à la fin
  472. while perm:
  473. codename = base_codename + str(incr)
  474. perm = Permission.objects.filter(codename=codename)
  475. incr += 1
  476. return codename
  477. class Meta:
  478. verbose_name = 'permission fine'
  479. verbose_name_plural = 'permissions fines'
  480. RowLevelPermission._meta.get_field('codename').blank = True
  481. RowLevelPermission._meta.get_field('codename').help_text = 'Laisser vide pour le générer automatiquement'
  482. RowLevelPermission._meta.get_field('content_type').help_text = "Garder 'abonnement' pour une utilisation normale"