models.py 23 KB

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