Commit b88d8168 authored by Charlie Jacomme's avatar Charlie Jacomme

[compte]Dev de la vu de création d'adh

parent 41d3cd89
......@@ -7,6 +7,8 @@ from django.core.validators import validate_email
from gestion import config
from gestion.config import factures
from gestion.chgpass import check_password
from django.forms.util import ErrorList
from lc_ldap.attributs import UniquenessError
import subprocess
import unicodedata
......@@ -49,8 +51,21 @@ class CompteForm(BaseCompteForm):
else:
return ""
class NewCompteForm(CompteForm):
mail = forms.CharField(label=u'Email', max_length=40, validators=[validate_email], required=True)
def apply(self, luser):
if 'etabetudes' in self.changed_data or 'annetudes' in self.changed_data or 'dometudes' in self.changed_data:
luser['etudes'] = [unicode(self.cleaned_data['etabetudes']), unicode(self.cleaned_data['annetudes']), unicode(self.cleaned_data['dometudes'])]
_ = self.changed_data.remove('annetudes')
_ = self.changed_data.remove('etabetudes')
_ = self.changed_data.remove('dometudes')
# On boucle sur les champs "simples"
for field in self.changed_data:
try:
luser[field] = unicode(self.cleaned_data[field])
except ValueError as e:
elist = self._errors.setdefault(field, ErrorList())
elist.append(e)
return False
return True
class MailForm(forms.Form):
mailredirect = forms.CharField(label=u'Redirection des mails', max_length=40, required=False)
......@@ -84,8 +99,8 @@ class AliasForm(forms.Form):
mailAlias = forms.EmailField(label=u'Nouvel alias Mail', max_length=40, required=False)
class BasePassForm(forms.Form):
newpasswd1 = forms.CharField(label=u'Nouveau mot de passe', max_length=255, widget=widgets.PasswordInput, required=True)
newpasswd2 = forms.CharField(label=u'Retaper le mot de passe', max_length=255, widget=widgets.PasswordInput, required=True)
newpasswd1 = forms.CharField(label=u'Nouveau mot de passe', max_length=255, widget=widgets.PasswordInput, required=False)
newpasswd2 = forms.CharField(label=u'Retaper le mot de passe', max_length=255, widget=widgets.PasswordInput, required=False)
def clean(self):
newpasswd1 = self.cleaned_data.get('newpasswd1')
newpasswd2 = self.cleaned_data.get('newpasswd2')
......@@ -98,6 +113,21 @@ class BasePassForm(forms.Form):
return self.cleaned_data
def apply(self, luser):
"""
Applique les modifications dans le user ldap
"""
if self.cleaned_data['newpasswd1']:
hashedPassword = lc_ldap.crans_utils.hash_password(self.cleaned_data['newpasswd1'].encode('utf-8'))
try:
luser['userPassword'] = [hashedPassword.decode('ascii')]
return True
except EnvironmentError as e:
errors = self._errors.setdefault("newpasswd2", ErrorList())
errors.append(e)
return False
class PassForm(BasePassForm):
passwdexists = forms.CharField(label=u'Ancien mot de passe', max_length=255, widget=widgets.PasswordInput, required=True)
......@@ -116,24 +146,60 @@ class AdhesionForm(forms.Form):
mode = forms.ChoiceField(label=u'Mode de réglement', choices=tuple([("", "<choisis un mode de réglement>")] + factures.VENTE.items()), required=True)
class ComptecransForm(forms.Form):
login = forms.CharField(label=u'Login Crans', required=True)
def __init__(self, ldap_user, ldap_conn, ptype, *args, **kwargs):
login = forms.CharField(label=u'Login Crans', required=False)
def __init__(self, ldap_user=None, ldap_conn=None, ptype=None, *args, **kwargs):
super(ComptecransForm, self).__init__(*args, **kwargs)
nom = unicode(unicodedata.normalize('NFKD', unicode(ldap_user['nom'][0])).encode('ascii', 'ignore')).lower().replace(' ', '-')
if ptype != 'club':
prenom = unicode(unicodedata.normalize('NFKD', unicode(ldap_user['prenom'][0])).encode('ascii', 'ignore')).lower().replace(' ', '-')
login_crans = nom
baselogin = nom
for rang,let in enumerate(prenom):
if ldap_conn.search(u'uid=%s' % login_crans) == []:
break
else:
login_crans = prenom[:rang] + baselogin
else:
login_crans = u'club-' + nom
self.fields['login'].initial = login_crans
class DemenagementForm(forms.Form):
if ldap_user and ldap_conn and ptype:
nom = unicode(unicodedata.normalize('NFKD', unicode(ldap_user['nom'][0])).encode('ascii', 'ignore')).lower().replace(' ', '-')
if ptype != 'club':
prenom = unicode(unicodedata.normalize('NFKD', unicode(ldap_user['prenom'][0])).encode('ascii', 'ignore')).lower().replace(' ', '-')
login_crans = nom
baselogin = nom
for rang,let in enumerate(prenom):
if ldap_conn.search(u'uid=%s' % login_crans) == []:
break
else:
login_crans = prenom[:rang] + baselogin
else:
login_crans = u'club-' + nom
self.fields['login'].initial = login_crans
def apply(self, luser):
if self.cleaned_data['login']:
try:
luser.compte(login=unicode(self.cleaned_data['login']))
return True
except ValueError as e:
# Le message d'une ValueError est directement dans e
elist = self._errors.setdefault('login', ErrorList())
elist.append(e)
return False
return True
class EmenagementForm(forms.Form):
chbre = forms.CharField(label=u'Chambre de l\'adhérent', max_length=255, required=True)
def apply(self, luser, confirm, conn):
chbre = self.cleaned_data['chbre']
try:
luser['chbre'] = chbre
luser['postalAddress'] = []
return True
except ValueError as e:
self._errors.setdefault('chbre', ErrorList()).append(e )
return False
except UniquenessError:
# La chambre est occupée
if not confirm:
# on demande confirmation
self._errors.setdefault('chbre', ErrorList()).append("Cette chambre est déjà occupée, corrigez la saisie ou revalidez pour confirmer.")
return 'confirm'
else:
squatteur = conn.search(u'chbre=%s' % chbre, mode='w')[0]
squatteur['chbre'] = '????'
squatteur.save()
luser['chbre'] = chbre
return True
class DemenagementForm(EmenagementForm):
postalAddress = forms.CharField(label=u'Adresse :', max_length=255, required=False)
postalAddress2 = forms.CharField(label=u'Adresse :', max_length=255, required=False)
postalAddress3 = forms.CharField(label=u'Code Postal :', max_length=255, required=False)
......@@ -145,3 +211,18 @@ class DemenagementForm(forms.Form):
if "chbre" in datas and len(datas)>1 :
print self.cleaned_data
raise forms.ValidationError("Impossible d'avoir une chambre et une adresse extérieur")
def apply(self, luser, confirm, conn):
chbre = self.cleaned_data['chbre']
if chbre:
return super(DemenagementForm, self).apply(luser,confirm, conn)
else:
luser['chbre'] = 'EXT'
luser['postalAddress'] = [self.cleaned_data['postalAddress'], self.cleaned_data['postalAddress2'], self.cleaned_data['postalAddress3'], self.cleaned_data['postalAddress4']]
if self.cleaned_data['del_machines']:
for m in luser.machines():
m.delete(login = request.user.username)
return True
class NewCompteForm(CompteForm):
mail = forms.CharField(label=u'Email', max_length=40, validators=[validate_email], required=False)
......@@ -3,61 +3,89 @@
{% block h1 %} Création d'un adhérent{% endblock %}
{% block content %}
<form class="form-full-width" method="post">{% csrf_token %}
<form class="form1-full-width" method="post" {% if confirm %} action="{% url 'compte:create' confirm %}" {% endif %}>{% csrf_token %}
<div class="error-container">
{{ form.non_field_errors }}
{{ form1.non_field_errors }}
</div>
<h2>Informations personnelles</h2>
<div class="row">
<div class="four columns{% if form.nom.errors %} error{% endif %}">
{{ form.nom.label_tag}}
{{ form.nom }}
{{ form.nom.errors }}
<div class="four columns{% if form1.nom.errors %} error{% endif %}">
{{ form1.nom.label_tag}}
{{ form1.nom }}
{{ form1.nom.errors }}
</div>
<div class="four columns{% if form.prenom.errors %} error{% endif %}">
{{ form.prenom.label_tag}}
{{ form.prenom }}
{{ form.prenom.errors }}
<div class="four columns{% if form1.prenom.errors %} error{% endif %}">
{{ form1.prenom.label_tag}}
{{ form1.prenom }}
{{ form1.prenom.errors }}
</div>
<div class="four columns{% if form.tel.errors %} error{% endif %}">
{{ form.tel.label_tag}}
{{ form.tel }}
{{ form.tel.errors }}
<div class="four columns{% if form1.tel.errors %} error{% endif %}">
{{ form1.tel.label_tag}}
{{ form1.tel }}
{{ form1.tel.errors }}
</div>
</div>
<div class="row">
<div class="four columns{% if form.etabetudes.errors %} error{% endif %}">
{{ form.etabetudes.label_tag}}
{{ form.etabetudes }}
{{ form.etabetudes.errors }}
<div class="four columns{% if form1.etabetudes.errors %} error{% endif %}">
{{ form1.etabetudes.label_tag}}
{{ form1.etabetudes }}
{{ form1.etabetudes.errors }}
</div>
<div class="four columns{% if form.annetudes.errors %} error{% endif %}">
{{ form.annetudes.label_tag}}
{{ form.annetudes }}
{{ form.annetudes.errors }}
<div class="four columns{% if form1.annetudes.errors %} error{% endif %}">
{{ form1.annetudes.label_tag}}
{{ form1.annetudes }}
{{ form1.annetudes.errors }}
</div>
<div class="four columns{% if form.dometudes.errors %} error{% endif %}">
{{ form.dometudes.label_tag}}
{{ form.dometudes }}
{{ form.dometudes.errors }}
<div class="four columns{% if form1.dometudes.errors %} error{% endif %}">
{{ form1.dometudes.label_tag}}
{{ form1.dometudes }}
{{ form1.dometudes.errors }}
</div>
</div>
<div class="row">
<div class="four columns{% if form.mail.errors %} error{% endif %}">
{{ form.mail.label_tag}}
{{ form.mail }}
{{ form.mail.errors }}
<div class="error-container">
{{ form2.non_field_errors }}
</div>
<h2>Chambre de l'adhérent</h2>
<div class="row">
<div class="six columns{% if form2.chbre.errors %} error{% endif %}">
{{ form2.chbre.label_tag}}
{{ form2.chbre }}
{{ form2.chbre.errors }}
</div>
</div>
{% if form3 %}
<div class="error-container">
{{ form3.non_field_errors }}
</div>
<h2>Compte crans ou mail extérieur</h2>
<div class="row">
<div class="six columns{% if form3.login.errors %} error{% endif %}">
{{ form3.login.label_tag}}
{{ form3.login }}
{{ form3.login.errors }}
</div>
<div class="four columns{% if form1.mail.errors %} error{% endif %}">
{{ form1.mail.label_tag}}
{{ form1.mail }}
{{ form1.mail.errors }}
</div>
</div>
{% else %}
<input type="hidden" value=1 name="step2" />
{% endif %}
<footer>
<div class="row">
<div class="six columns">
<input class="button-add" type="submit" value="Enregistrer les changements">
<input class="button-add" type="submit" value="Valider">
</div>
</div>
</footer>
</form>
{% endblock %}
1
......@@ -10,7 +10,7 @@
<h2>Déménagement à l'intérieur du campus</h2>
<div class="row">
<div class="six columns{% if form.mode.errors %} error{% endif %}">
<div class="six columns{% if form.chbre.errors %} error{% endif %}">
{{ form.chbre.label_tag}}
{{ form.chbre }}
{{ form.chbre.errors }}
......@@ -24,33 +24,33 @@
{% if ptype != "club" %}
<h2>Déménagement à l'extérieur</h2>
<div class="row">
<div class="six columns{% if form.articles.errors %} error{% endif %}">
<div class="six columns{% if form.del_machines.errors %} error{% endif %}">
{{ form.del_machines.label_tag}}
{{ form.del_machines }}
{{ form.del_machines.errors }}
</div>
</div>
<div class="row">
<div class="twelve columns{% if form.mode.errors %} error{% endif %}">
<div class="twelve columns{% if form.postalAddress.errors %} error{% endif %}">
{{ form.postalAddress.label_tag}}
{{ form.postalAddress }}
{{ form.postalAddress.errors }}
</div>
</div>
<div class="row">
<div class="twelve columns{% if form.mode.errors %} error{% endif %}">
<div class="twelve columns{% if form.postalAddress2.errors %} error{% endif %}">
{{ form.postalAddress2.label_tag}}
{{ form.postalAddress2 }}
{{ form.postalAddress2.errors }}
</div>
</div>
<div class="row">
<div class="six columns{% if form.mode.errors %} error{% endif %}">
<div class="six columns{% if form.postalAddress3.errors %} error{% endif %}">
{{ form.postalAddress3.label_tag}}
{{ form.postalAddress3 }}
{{ form.postalAddress3.errors }}
</div>
<div class="six columns{% if form.mode.errors %} error{% endif %}">
<div class="six columns{% if form.postalAddress4.errors %} error{% endif %}">
{{ form.postalAddress4.label_tag}}
{{ form.postalAddress4 }}
{{ form.postalAddress4.errors }}
......
......@@ -36,4 +36,5 @@ views.delete_alias, name='delete_alias'),
url('^delete/(?P<ptype>club)/(?P<uid>[0-9]+)/$', views.delete, name='delete'),
url('^delete/(?P<ptype>adh)/(?P<uid>[0-9]+)/$', views.delete, name='delete'),
url('^create/$', views.create, name='create'),
url('^create/(?P<confirm>confirm)/$$', views.create, name='create'),
)
......@@ -23,12 +23,11 @@ import datetime
from passlib.apps import ldap_context
import lc_ldap.crans_utils
from lc_ldap.attributs import UniquenessError
from intranet import settings
from gestion.config import factures, cotisation
from forms import BaseCompteForm, CompteForm, BasePassForm, PassForm, MailForm, AliasForm, SoldeForm, VenteForm, AdhesionForm, ComptecransForm, DemenagementForm, NewCompteForm
from forms import BaseCompteForm, CompteForm, BasePassForm, PassForm, MailForm, AliasForm, SoldeForm, VenteForm, AdhesionForm, ComptecransForm, DemenagementForm, NewCompteForm, EmenagementForm
from django.forms.util import ErrorList
def is_cableur(user):
......@@ -188,36 +187,11 @@ class CompteView(CableurOrSelfMixin, View):
form = CompteForm(luser, request.POST)
if form.is_valid():
luser = conn_pool.get_conn(request.user).search(u'aid=%s' % aid, mode="w")[0]
# Certains champs n'ont pas les même type entre ldap et django, il faut
# les modifier à part.
# Les trois champs concernant les études côté django sont rassemblés
# dans une liste côté ldap.
if 'etabetudes' in form.changed_data:
luser['etudes'][0] = unicode(form.cleaned_data['etabetudes'])
_ = form.changed_data.remove('etabetudes')
if 'annetudes' in form.changed_data:
luser['etudes'][1] = unicode(form.cleaned_data['annetudes'])
_ = form.changed_data.remove('annetudes')
if 'dometudes' in form.changed_data:
luser['etudes'][2] = unicode(form.cleaned_data['dometudes'])
_ = form.changed_data.remove('dometudes')
# On boucle sur les champs "simples"
for field in form.changed_data:
try:
luser[field] = form.cleaned_data[field]
except ValueError as e:
elist = form._errors.setdefault(field, ErrorList())
elist.append(e)
# Il faut créer l'historique avant de sauvegarder.
luser.history_gen()
luser.save()
messages.success(request, u"""Les modifications ont été prises en compte""")
if form.apply(luser):
# Il faut créer l'historique avant de sauvegarder.
luser.history_gen()
luser.save()
messages.success(request, u"""Les modifications ont été prises en compte""")
context = {
'form': form,
......@@ -272,17 +246,11 @@ class ChgPassView(CableurOrSelfMixin, RedirectHomeMixin, View):
if form.is_valid():
# Soit on est en train de cabler soit l'ancien mot de passe est bon
if cablage or ldap_context.verify(unicode(form.cleaned_data['passwdexists']), unicode(luser['userPassword'][0])):
hashedPassword = lc_ldap.crans_utils.hash_password(form.cleaned_data['newpasswd1'].encode('utf-8'))
try:
luser['userPassword'] = [hashedPassword.decode('ascii')]
if form.apply(luser):
luser.history_gen()
luser.save()
messages.success(request, u"""Le mot de passe a bien été changé""")
return redirect(next)
except EnvironmentError as e:
errors = form._errors.setdefault("newpasswd2", ErrorList())
errors.append(e)
else:
errors = form._errors.setdefault("passwdexists", ErrorList())
errors.append(u"Ancien mot de passe erroné.")
......@@ -594,17 +562,11 @@ class ComptecransView(CableurMixin, View):
form = ComptecransForm(luser, conn_pool.get_conn(request.user), ptype, request.POST)
if form.is_valid():
with luser as user:
try:
user.compte(login=unicode(form.cleaned_data['login']))
user.history_gen()
user.save()
messages.success(request, u"""Compte Crans crée, choisir un mot de passe""")
return redirect(reverse('compte:chgpass', args=(ptype,uid)))
except ValueError as e:
# Le message d'une ValueError est directement dans e
elist = form._errors.setdefault('login', ErrorList())
elist.append(e)
if form.apply(luser): #Si on arrive à appliquer les modifs à l'objet
luser.history_gen()
luser.save()
messages.success(request, u"""Compte Crans crée, choisir un mot de passe""")
return redirect(reverse('compte:chgpass', args=(ptype,uid)))
return render(request, self.template_name, {'form': form, 'ptype': ptype, 'ide': uid})
comptecrans = ComptecransView.as_view()
......@@ -626,42 +588,14 @@ class DemenagementView(CableurMixin, RedirectHomeMixin, View):
luser = conn_pool.get_conn(request.user).search(u'aid=%s' % uid, mode='w')[0]
form = DemenagementForm(request.POST)
if form.is_valid():
chbre = form.cleaned_data['chbre']
if chbre:
try:
luser['chbre'] = chbre
luser['postalAddress'] = []
luser.save()
messages.success(request, u"""Déménagement effectué""")
return redirect(next)
except ValueError as e:
form._errors.setdefault('chbre', ErrorList()).append("Cette chambre n'est pas valide pour un club." )
except UniquenessError:
# La chambre est occupée
if not confirm:
# on demande confirmation
confirm = 'confirm'
form._errors.setdefault('chbre', ErrorList()).append("Cette chambre est déjà occupée, corrigez la saisie ou revalidez pour confirmer.")
else:
squatteur = conn_pool.get_conn(request.user).search(u'chbre=%s' % chbre, mode='w')[0]
squatteur['chbre'] = '????'
squatteur.save()
luser['chbre'] = chbre
luser.save()
messages.success(request, u"""Déménagement effectué""")
return redirect(next)
else:
luser['chbre'] = 'EXT'
luser['postalAddress'] = [form.cleaned_data['postalAddress'], form.cleaned_data['postalAddress2'], form.cleaned_data['postalAddress3'], form.cleaned_data['postalAddress4']]
lconn = conn_pool.get_conn(request.user)
res = form.apply(luser, confirm, lconn)
if res == 'confirm':
confirm = 'confirm'
elif res:
luser.save()
if form.cleaned_data['del_machines']:
for m in luser.machines():
m.delete(login = request.user.username)
messages.success(request, u"""Déménagement effectué""")
return redirect(next)
return render(request, self.template_name, {'form': form, 'ptype': ptype, 'ide': uid, 'confirm' : confirm})
demenagement = DemenagementView.as_view()
......@@ -692,31 +626,36 @@ delete = DeleteCompteView.as_view()
class CreateCompteView(CableurMixin, View):
"""
Classe pour la suppression d'un compte
Classe pour la création d'un compte crans
"""
template_name = "compte/create.html"
def get(self, request, *args, **kwargs):
form = NewCompteForm()
return render(request, self.template_name, {'form' : form})
def post(self, request, *args, **kwargs):
form = NewCompteForm(data=request.POST)
if form.is_valid():
aldif = {'chbre': ["????"]}
aldif['etudes'] = [unicode(form.cleaned_data['etabetudes']), unicode(form.cleaned_data['annetudes']), unicode(form.cleaned_data['dometudes'])]
_ = form.changed_data.remove('etabetudes')
_ = form.changed_data.remove('annetudes')
_ = form.changed_data.remove('dometudes')
# On boucle sur les champs "simples"
for field in form.changed_data:
aldif[field] = [form.cleaned_data[field]]
with conn_pool.get_conn(request.user).newAdherent(aldif) as adherent:
adherent.create()
return redirect(reverse('cablage:afficher'))
form1 = NewCompteForm()
form2 = EmenagementForm()
return render(request, self.template_name, {'form1' : form1, 'form2' : form2})
def post(self, request, confirm = "", *args, **kwargs):
form1 = NewCompteForm(data=request.POST)
form2 = EmenagementForm(data=request.POST)
form3 = None
if form1.is_valid() and form2.is_valid():
with conn_pool.get_conn(request.user).newAdherent({}) as adherent:
lconn = conn_pool.get_conn(request.user)
if 'step2' in request.POST.keys() and form1.apply(adherent):
form3 = ComptecransForm(ldap_user = adherent, ldap_conn=lconn, ptype = u"adh")
else:
form3 = ComptecransForm(data=request.POST)
if form3.is_valid():
if not form3.cleaned_data['login'] and not form1.cleaned_data['mail']:
messages.error(request, "Il faut soit un mail extérieur soit un compte crans")
elif form1.apply(adherent) and form3.apply(adherent):
res = form2.apply(adherent, confirm, lconn)
if res == 'confirm':
confirm = 'confirm'
elif res:
adherent.create()
messages.success(request, u"""Compte crée""")
return redirect(reverse('cablage:afficher'))
return render(request, self.template_name, {'form1' : form1, 'form2' : form2, 'form3' : form3, 'confirm' : confirm})
return render(request, self.template_name, {'form' : form})
create = CreateCompteView.as_view()
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment