Gestion mot de passe oublié et changement de mdp
[auf_savoirs_en_partage_django.git] / auf_savoirs_en_partage / chercheurs / views.py
1 # -*- encoding: utf-8 -*-
2 import hashlib
3 from django.shortcuts import render_to_response
4 from django.http import HttpResponseRedirect, HttpResponse
5 from django.template import Context, RequestContext
6 from django.template.loader import get_template
7 from django.core.urlresolvers import reverse
8 from django.core.mail import send_mail
9 from django.conf import settings
10
11 from forms import *
12 from django.forms.models import inlineformset_factory
13
14 from auf_references_client.models import Discipline, TypeImplantation
15 from models import Personne, Utilisateur, Groupe, ChercheurGroupe
16
17 from django.contrib.auth.decorators import login_required
18
19 from django.db.models import Q
20 from django.shortcuts import get_object_or_404
21
22 from django.utils.translation import ugettext_lazy as _
23 from django.contrib.auth.forms import AuthenticationForm as OriginalAuthenticationForm
24
25 #TODO: Migrer tout ce qui a rapport aux users dans une nouvelle app
26
27 class AuthenticationForm(OriginalAuthenticationForm):
28 username = forms.CharField(label=_("Username"), max_length=255)
29
30 def send_password(request):
31 if request.method == "POST":
32 form = SendPasswordForm(data=request.POST)
33 if form.is_valid():
34 u = Utilisateur.objects.get(courriel=form.cleaned_data['email'])
35 code = hashlib.md5(u.courriel+u.password).hexdigest()
36 code = code[0:6]
37 link = "%saccounts/new_password/%s/%s/" % (settings.SITE_ROOT_URL, u.courriel, code)
38
39 variables = { 'user': u,
40 'link': link,
41 'SITE_ROOT_URL': settings.SITE_ROOT_URL
42 }
43 t = get_template('accounts/email_password.html')
44 content = t.render(Context(variables))
45
46 send_mail('Savoirs en partage: changement de mot de passe',
47 content, settings.CONTACT_EMAIL,
48 [u.courriel], fail_silently=False)
49 else:
50 form = SendPasswordForm()
51
52 variables = { 'form': form,
53 }
54 return render_to_response ("accounts/send_password.html", \
55 Context (variables),
56 context_instance = RequestContext(request))
57
58 def new_password(request, email, code):
59 u = Utilisateur.objects.get(courriel=email)
60 original_code = hashlib.md5(u.courriel+u.password).hexdigest()
61 original_code = original_code[0:6]
62 message=""
63 if(code == original_code):
64 if request.method == "POST":
65 form = NewPasswordForm(data=request.POST)
66 if form.is_valid():
67 new_password = form.cleaned_data['password']
68 u.password = hashlib.md5(new_password).hexdigest()
69 u.save()
70 message = "Votre mot de passe a été modifié."
71 else:
72 form = NewPasswordForm()
73 else:
74 return HttpResponseRedirect('/')
75 variables = { 'form': form,
76 'message': message,
77 }
78 return render_to_response ("accounts/new_password.html", \
79 Context (variables),
80 context_instance = RequestContext(request))
81
82 @login_required()
83 def change_password(request):
84 context_instance = RequestContext(request)
85 u = context_instance['user_sep']
86 message = ""
87 if request.method == "POST":
88 form = NewPasswordForm(data=request.POST)
89 if form.is_valid():
90 new_password = form.cleaned_data['password']
91 u.password = hashlib.md5(new_password).hexdigest()
92 u.save()
93 message = "Votre mot de passe a été modifié."
94 else:
95 form = NewPasswordForm()
96 variables = { 'form': form,
97 'message': message,
98 }
99 return render_to_response ("accounts/new_password.html", \
100 Context (variables),
101 context_instance = RequestContext(request))
102
103 def chercheur_login(request, template_name='registration/login.html', redirect_field_name='next'):
104 "Displays the login form and handles the login action."
105 redirect_to = request.REQUEST.get(redirect_field_name, '')
106 if request.method == "POST":
107 form = AuthenticationForm(data=request.POST)
108 if form.is_valid():
109 # Light security check -- make sure redirect_to isn't garbage.
110 if not redirect_to or '//' in redirect_to or ' ' in redirect_to:
111 redirect_to = settings.LOGIN_REDIRECT_URL
112 from django.contrib.auth import login
113 login(request, form.get_user())
114 if request.session.test_cookie_worked():
115 request.session.delete_test_cookie()
116 return HttpResponseRedirect(redirect_to)
117 else:
118 form = AuthenticationForm(request)
119 request.session.set_test_cookie()
120 return render_to_response(template_name, {
121 'form': form,
122 redirect_field_name: redirect_to,
123 }, context_instance=RequestContext(request))
124
125
126 def chercheur_queryset (request):
127 list = Chercheur.objects.order_by("id")
128 pays = ""
129
130 simpleForm = RepertoireSearchForm (request.GET)
131 if simpleForm.is_valid ():
132 pays = simpleForm.cleaned_data["pays"]
133 if pays:
134 list = list.filter(Q(etablissement__pays = pays.pk) | Q(etablissement_autre_pays = pays.pk))
135 fonction = simpleForm.cleaned_data["fonction"]
136 if fonction:
137 list = list.filter(fonction = fonction)
138 discipline = simpleForm.cleaned_data["discipline"]
139 if discipline:
140 list = list.filter(discipline=discipline)
141 domaine = simpleForm.cleaned_data["domaine"]
142 if domaine:
143 list = list.filter(groupes=domaine)
144 mots_cles = simpleForm.cleaned_data["mots_cles"]
145 if mots_cles:
146 list = list.filter( Q(personne__nom__search=mots_cles)
147 | Q(personne__prenom__search=mots_cles)
148 | Q(expertise__search=mots_cles)
149 | Q(etablissement_autre_nom__search=mots_cles)
150 | Q(etablissement__nom__search=mots_cles) )
151 return list
152
153 def index(request):
154 """Répertoire des chercheurs"""
155
156 chercheurs = chercheur_queryset (request)
157 repertoire_form = RepertoireSearchForm (request.GET)
158
159 nb_chercheurs = chercheurs.count()
160 variables = { 'chercheurs': chercheurs,
161 'nb_chercheurs': nb_chercheurs,
162 'repertoire_form': repertoire_form,
163 }
164 return render_to_response ("chercheurs/index.html", \
165 Context (variables),
166 context_instance = RequestContext(request))
167
168 def inscription(request):
169 if request.method == 'POST':
170 personne_form = PersonneForm (request.POST, prefix="personne")
171 chercheur_form = ChercheurForm (request.POST, prefix="chercheur")
172 etablissement_form = EtablissementForm (request.POST, prefix="etablissement")
173 etablissement_autre_form = EtablissementAutreForm(request.POST, prefix="etablissement_autre")
174 discipline_form = DisciplineForm (request.POST, prefix="discipline")
175 publication1_form = PublicationForm (request.POST, prefix="publication1")
176 publication2_form = PublicationForm (request.POST, prefix="publication2")
177 publication3_form = PublicationForm (request.POST, prefix="publication3")
178 publication4_form = PublicationForm (request.POST, prefix="publication4")
179 these_form = TheseForm(request.POST, prefix="these")
180 groupe_form = GroupeForm(request.POST, prefix="groupe")
181
182 if personne_form.is_valid():
183 if chercheur_form.is_valid() and groupe_form.is_valid():
184 c = chercheur_form.save(commit=False)
185
186 etablissement_form = EtablissementForm (request.POST, prefix="etablissement", instance=c)
187 etablissement_autre_form = EtablissementAutreForm (request.POST, prefix="etablissement_autre", instance=c)
188 discipline_form = DisciplineForm (request.POST, prefix="discipline", instance=c)
189
190 if etablissement_form.is_valid() and discipline_form.is_valid() and these_form.is_valid():
191 if publication1_form.is_valid() and publication1_form.cleaned_data['titre']:
192 pub = publication1_form.save()
193 c.publication1 = pub
194 if publication2_form.is_valid() and publication2_form.cleaned_data['titre']:
195 pub = publication2_form.save()
196 c.publication2 = pub
197 if publication3_form.is_valid() and publication3_form.cleaned_data['titre']:
198 pub = publication3_form.save()
199 c.publication3 = pub
200 if publication4_form.is_valid() and publication4_form.cleaned_data['titre']:
201 pub = publication4_form.save()
202 c.publication4 = pub
203 these = these_form.save()
204 c.these = these
205 etablissement_form.save(commit=False)
206 etablissement_autre_form.save(commit=False)
207 discipline_form.save(commit=False)
208 #encodage du mot de passe de l'utilisateur (refactorer car c'est pas clean
209 #et c'est pas la bonne place pour faire ca - AJ
210 personne_form.cleaned_data['password'] = hashlib.md5(personne_form.cleaned_data['password']).hexdigest()
211 p = personne_form.save()
212 c.personne = p
213 c.save()
214
215 #sauvegarde des groupes
216 groupes = request.POST.getlist('groupe-groupes')
217 for g in groupes:
218 g = Groupe.objects.get(pk=g)
219 ChercheurGroupe.objects.get_or_create(chercheur=c, groupe=g, actif=1)
220 return HttpResponseRedirect("/chercheurs/%d/?inscription=1" % c.id)
221 #return HttpResponseRedirect(reverse('chercheurs.views.retrieve', args=(c.id,)))
222 else:
223 personne_form = PersonneForm(prefix="personne")
224 chercheur_form = ChercheurForm(prefix="chercheur")
225 etablissement_form = EtablissementForm(prefix="etablissement")
226 etablissement_autre_form = EtablissementAutreForm(prefix="etablissement_autre")
227 discipline_form = DisciplineForm(prefix="discipline")
228 publication1_form = PublicationForm(prefix="publication1")
229 publication2_form = PublicationForm(prefix="publication2")
230 publication3_form = PublicationForm(prefix="publication3")
231 publication4_form = PublicationForm(prefix="publication4")
232 these_form = TheseForm(prefix="these")
233 groupe_form = GroupeForm(prefix="groupe")
234
235 variables = { 'personne_form': personne_form,
236 'chercheur_form': chercheur_form,
237 'etablissement_form': etablissement_form,
238 'discipline_form': discipline_form,
239 'etablissement_autre_form': etablissement_autre_form,
240 'publication1_form': publication1_form,
241 'publication2_form': publication2_form,
242 'publication3_form': publication3_form,
243 'publication4_form': publication4_form,
244 'these_form': these_form,
245 'groupe_form': groupe_form,
246 }
247
248 return render_to_response ("chercheurs/inscription.html", \
249 Context (variables),
250 context_instance = RequestContext(request))
251
252 @login_required()
253 def edit(request):
254 """Edition d'un chercheur"""
255 context_instance = RequestContext(request)
256 chercheur = context_instance['user_chercheur']
257 #GroupeFormset = inlineformset_factory(Chercheur, ChercheurGroupe)
258
259 if request.method == 'POST':
260 personne_form = PersonneEditForm(request.POST, prefix="personne", instance=chercheur.personne)
261 chercheur_form = ChercheurForm (request.POST, prefix="chercheur", instance=chercheur)
262 etablissement_form = EtablissementForm(request.POST, prefix="etablissement", instance=chercheur)
263 etablissement_autre_form = EtablissementAutreForm(request.POST, prefix="etablissement_autre", instance=chercheur)
264 discipline_form = DisciplineForm(request.POST, prefix="discipline", instance=chercheur)
265 publication1_form = PublicationForm(request.POST, prefix="publication1", instance=chercheur.publication1)
266 publication2_form = PublicationForm(request.POST, prefix="publication2", instance=chercheur.publication2)
267 publication3_form = PublicationForm(request.POST, prefix="publication3", instance=chercheur.publication3)
268 publication4_form = PublicationForm(request.POST, prefix="publication4", instance=chercheur.publication4)
269 these_form = TheseForm(request.POST, prefix="these", instance=chercheur.these)
270 groupe_form = GroupeForm(request.POST, prefix="groupe", instance=chercheur)
271
272 #formset = GroupeFormset(request.POST, prefix="groupes", instance = chercheur)
273
274 if( personne_form.is_valid() and discipline_form.is_valid() and chercheur_form.is_valid() and these_form.is_valid()
275 and etablissement_form.is_valid() and etablissement_autre_form.save() and groupe_form.is_valid() ):
276 personne_form.save()
277 discipline_form.save()
278 chercheur_form.save()
279 etablissement_form.save()
280 etablissement_autre_form.save()
281
282 if publication1_form.is_valid() and publication1_form.cleaned_data['titre']:
283 chercheur.publication1 = publication1_form.save()
284 if publication2_form.is_valid() and publication2_form.cleaned_data['titre']:
285 chercheur.publication2 = publication2_form.save()
286 if publication3_form.is_valid() and publication3_form.cleaned_data['titre']:
287 chercheur.publication3 = publication3_form.save()
288 if publication4_form.is_valid() and publication4_form.cleaned_data['titre']:
289 chercheur.publication4 = publication4_form.save()
290 chercheur.these = these_form.save()
291 chercheur.save()
292 #Gestion des groupes
293 groupes = request.POST.getlist('groupe-groupes')
294 #On delete les chercheurs deselectionnés
295 ChercheurGroupe.objects.filter(chercheur=chercheur).exclude(groupe__in=groupes).delete()
296 #Sauvegarde des groupes...
297 for g in groupes:
298 g = Groupe.objects.get(pk=g)
299 ChercheurGroupe.objects.get_or_create(chercheur=chercheur, groupe=g, actif=1)
300
301
302 #formset.save()
303
304 else:
305 personne_form = PersonneEditForm(prefix="personne", instance=chercheur.personne)
306 chercheur_form = ChercheurForm (prefix="chercheur", instance=chercheur)
307 etablissement_form = EtablissementForm(prefix="etablissement", instance=chercheur)
308 etablissement_autre_form = EtablissementAutreForm(prefix="etablissement_autre", instance=chercheur)
309 discipline_form = DisciplineForm(prefix="discipline", instance=chercheur)
310 publication1_form = PublicationForm(prefix="publication1", instance=chercheur.publication1)
311 publication2_form = PublicationForm(prefix="publication2", instance=chercheur.publication2)
312 publication3_form = PublicationForm(prefix="publication3", instance=chercheur.publication3)
313 publication4_form = PublicationForm(prefix="publication4", instance=chercheur.publication4)
314 these_form = TheseForm(prefix="these", instance=chercheur.these)
315 groupe_form = GroupeForm(prefix="groupe", instance=chercheur)
316 #formset = GroupeFormset(prefix="groupes", instance = chercheur)
317
318 variables = { 'chercheur': chercheur,
319 'personne_form':personne_form,
320 'chercheur_form': chercheur_form,
321 'etablissement_form': etablissement_form,
322 'discipline_form': discipline_form,
323 'etablissement_autre_form': etablissement_autre_form,
324 'publication1_form': publication1_form,
325 'publication2_form': publication2_form,
326 'publication3_form': publication3_form,
327 'publication4_form': publication4_form,
328 'these_form': these_form,
329 'groupe_form': groupe_form,
330 #'formset' : formset
331 }
332 return render_to_response ("chercheurs/edit.html", \
333 Context (variables),
334 context_instance = RequestContext(request))
335
336
337 @login_required()
338 def perso(request):
339 """Espace chercheur (espace personnel du chercheur)"""
340 context_instance = RequestContext(request)
341 chercheur = context_instance['user_chercheur']
342 if not chercheur:
343 return HttpResponseRedirect(reverse('chercheurs.views.chercheur_login'))
344 variables = { 'chercheur': chercheur,
345 }
346 return render_to_response ("chercheurs/perso.html", \
347 Context (variables),
348 context_instance = RequestContext(request))
349
350 def retrieve(request, id):
351 """Fiche du chercheur"""
352 #chercheur = Chercheur.objects.get(id=id)
353 inscription = request.GET.get('inscription')
354 chercheur = get_object_or_404(Chercheur, id=id)
355 variables = { 'chercheur': chercheur,
356 'inscription': inscription,
357 }
358 return render_to_response ("chercheurs/retrieve.html", \
359 Context (variables),
360 context_instance = RequestContext(request))