ace05647755940e98d5a1ddeacb17b761f24dd88
[auf_savoirs_en_partage_django.git] / auf_savoirs_en_partage / chercheurs / views.py
1 # -*- encoding: utf-8 -*-
2 from chercheurs.decorators import chercheur_required
3 from chercheurs.forms import ChercheurSearchForm, SetPasswordForm, ChercheurFormGroup, AuthenticationForm, GroupeSearchForm, MessageForm
4 from chercheurs.models import Chercheur, Groupe, Message, AdhesionGroupe, AuthLDAP
5 from chercheurs.utils import get_django_user_for_email, create_ldap_hash
6 from datamaster_modeles.models import Etablissement, Region
7 from django.conf import settings
8 from django.shortcuts import render_to_response
9 from django.http import HttpResponseRedirect, HttpResponse, HttpResponseForbidden, HttpResponseNotFound
10 from django.template import Context, RequestContext
11 from django.template.loader import get_template
12 from django.core.urlresolvers import reverse as url
13 from django.core.mail import send_mail
14 from django.contrib.auth import REDIRECT_FIELD_NAME
15 from django.contrib.auth import login as auth_login
16 from django.contrib.auth.decorators import login_required
17 from django.contrib.sites.models import RequestSite, Site
18 from django.utils import simplejson
19 from django.utils.http import int_to_base36, base36_to_int
20 from django.views.decorators.cache import never_cache
21 from django.contrib.auth import authenticate
22 from django.shortcuts import get_object_or_404
23 from django.views.decorators.csrf import csrf_protect
24 from django.contrib.auth.forms import PasswordChangeForm
25 from savoirs.models import PageStatique, Discipline
26
27
28 def index(request):
29 """Répertoire des chercheurs"""
30 search_form = ChercheurSearchForm(request.GET)
31 search = search_form.save(commit=False)
32 chercheurs = search.run().select_related('etablissement')
33 sort = request.GET.get('tri')
34 if sort is not None and sort.endswith('_desc'):
35 sort = sort[:-5]
36 direction = '-'
37 else:
38 direction = ''
39 if sort == 'nom':
40 chercheurs = chercheurs.order_by_nom(direction)
41 elif sort == 'etablissement':
42 chercheurs = chercheurs.order_by_etablissement(direction)
43 elif sort == 'pays':
44 chercheurs = chercheurs.order_by_pays(direction)
45 else:
46 chercheurs = chercheurs.order_by('-date_modification')
47
48 try:
49 p = PageStatique.objects.get(id='repertoire')
50 entete = p.contenu
51 except PageStatique.DoesNotExist:
52 entete = u'<h1>Répertoire des chercheurs</h1>'
53
54 nb_chercheurs = chercheurs.count()
55
56 return render_to_response("chercheurs/index.html",
57 dict(chercheurs=chercheurs, nb_chercheurs=nb_chercheurs,
58 search_form=search_form, entete=entete),
59 context_instance=RequestContext(request))
60
61 def inscription(request):
62 if request.method == 'POST':
63 forms = ChercheurFormGroup(request.POST)
64 if forms.is_valid():
65 chercheur = forms.save()
66 id_base36 = int_to_base36(chercheur.id)
67 token = chercheur.activation_token()
68 template = get_template('chercheurs/activation_email.txt')
69 domain = RequestSite(request).domain
70 message = template.render(Context(dict(chercheur=chercheur, id_base36=id_base36, token=token, domain=domain)))
71 send_mail('Votre inscription à Savoirs en partage', message, None, [chercheur.courriel])
72 return HttpResponseRedirect(url('chercheurs-inscription-faite'))
73 else:
74 forms = ChercheurFormGroup()
75
76 return render_to_response("chercheurs/inscription.html",
77 dict(forms=forms),
78 context_instance=RequestContext(request))
79
80 def activation(request, id_base36, token):
81 """Activation d'un chercheur"""
82 id = base36_to_int(id_base36)
83 chercheur = get_object_or_404(Chercheur.all_objects, id=id)
84 if token == chercheur.activation_token():
85 validlink = True
86 if request.method == 'POST':
87 form = SetPasswordForm(request.POST)
88 if form.is_valid():
89 password = form.cleaned_data['password']
90 email = chercheur.courriel
91 chercheur.actif = True
92 chercheur.save()
93 user = get_django_user_for_email(email)
94 user.set_password(password)
95 user.save()
96
97 # Auto-login
98 auth_login(request, authenticate(username=email, password=password))
99 return HttpResponseRedirect(url('chercheurs.views.perso'))
100 else:
101 form = SetPasswordForm()
102 else:
103 form = None
104 validlink = False
105 return render_to_response('chercheurs/activation.html', dict(form=form, validlink=validlink),
106 context_instance=RequestContext(request))
107
108 @csrf_protect
109 @login_required
110 def password_change(request, template_name='registration/password_change_form.html',
111 post_change_redirect=None, password_change_form=PasswordChangeForm):
112 if post_change_redirect is None:
113 post_change_redirect = url('django.contrib.auth.views.password_change_done')
114 if request.method == "POST":
115 form = password_change_form(user=request.user, data=request.POST)
116 if form.is_valid():
117 form.save()
118
119 # Mot de passe pour LDAP
120 username = request.user.email
121 authldap, created = AuthLDAP.objects.get_or_create(username=username)
122 password = form.cleaned_data.get('new_password1')
123 ldap_hash = create_ldap_hash(password)
124 authldap.ldap_hash = ldap_hash
125 authldap.save()
126
127 return HttpResponseRedirect(post_change_redirect)
128 else:
129 form = password_change_form(user=request.user)
130 return render_to_response(template_name, {
131 'form': form,
132 }, context_instance=RequestContext(request))
133
134
135 @chercheur_required
136 def desinscription(request):
137 """Désinscription du chercheur"""
138 chercheur = request.chercheur
139 if request.method == 'POST':
140 if request.POST.get('confirmer'):
141 chercheur.actif = False
142 chercheur.save()
143 request.flash['message'] = "Vous avez été désinscrit du répertoire des chercheurs."
144 return HttpResponseRedirect(url('django.contrib.auth.views.logout'))
145 else:
146 request.flash['message'] = "Opération annulée."
147 return HttpResponseRedirect(url('chercheurs.views.perso'))
148 return render_to_response("chercheurs/desinscription.html", {},
149 context_instance=RequestContext(request))
150
151 @chercheur_required
152 @never_cache
153 def edit(request):
154 """Edition d'un chercheur"""
155 chercheur = request.chercheur
156 if request.method == 'POST':
157 forms = ChercheurFormGroup(request.POST, chercheur=chercheur)
158 if forms.is_valid():
159 forms.save()
160 request.flash['message'] = "Votre fiche a bien été enregistrée."
161 return HttpResponseRedirect(url('chercheurs.views.perso'))
162 else:
163 forms = ChercheurFormGroup(chercheur=chercheur)
164
165 return render_to_response("chercheurs/edit.html",
166 dict(forms=forms, chercheur=chercheur),
167 context_instance=RequestContext(request))
168
169 @chercheur_required
170 def perso(request):
171 """Espace chercheur (espace personnel du chercheur)"""
172 chercheur = request.chercheur
173 modification = request.GET.get('modification')
174 return render_to_response("chercheurs/perso.html",
175 dict(chercheur=chercheur, modification=modification),
176 context_instance=RequestContext(request))
177
178 def retrieve(request, id):
179 """Fiche du chercheur"""
180 chercheur = get_object_or_404(Chercheur, id=id)
181 return render_to_response("chercheurs/retrieve.html",
182 dict(chercheur=chercheur),
183 context_instance=RequestContext(request))
184
185 def conversion(request):
186 return render_to_response("chercheurs/conversion.html", {},
187 context_instance=RequestContext(request))
188
189 def etablissements_autocomplete(request, pays=None):
190 term = request.GET.get('term')
191 noms = Etablissement.objects.all().filter(membre=True, actif=True)
192 for word in term.split():
193 noms = noms.filter(nom__icontains=word)
194 if pays:
195 noms = noms.filter(pays=pays)
196 noms = list(noms.values_list('nom', flat=True)[:20])
197 json = simplejson.dumps(noms)
198 return HttpResponse(json, mimetype='application/json')
199
200 def login(request, template_name='registration/login.html', redirect_field_name=REDIRECT_FIELD_NAME):
201 "The Django login view, but using a custom form."
202 redirect_to = request.REQUEST.get(redirect_field_name, '')
203
204 if request.method == "POST":
205 form = AuthenticationForm(data=request.POST)
206 if form.is_valid():
207 # Light security check -- make sure redirect_to isn't garbage.
208 if not redirect_to or ' ' in redirect_to:
209 redirect_to = settings.LOGIN_REDIRECT_URL
210
211 # Heavier security check -- redirects to http://example.com should
212 # not be allowed, but things like /view/?param=http://example.com
213 # should be allowed. This regex checks if there is a '//' *before* a
214 # question mark.
215 elif '//' in redirect_to and re.match(r'[^\?]*//', redirect_to):
216 redirect_to = settings.LOGIN_REDIRECT_URL
217
218 # Mot de passe pour LDAP
219 username = form.cleaned_data.get('username')
220 authldap, created = AuthLDAP.objects.get_or_create(username=username)
221 if created:
222 password = form.cleaned_data.get('password')
223 ldap_hash = create_ldap_hash(password)
224 authldap.ldap_hash = ldap_hash
225 authldap.save()
226
227 # Okay, security checks complete. Log the user in.
228 auth_login(request, form.get_user())
229
230 if request.session.test_cookie_worked():
231 request.session.delete_test_cookie()
232
233 return HttpResponseRedirect(redirect_to)
234
235 else:
236 form = AuthenticationForm(request)
237 request.session.set_test_cookie()
238
239 if Site._meta.installed:
240 current_site = Site.objects.get_current()
241 else:
242 current_site = RequestSite(request)
243
244 return render_to_response(template_name, {
245 'form': form,
246 redirect_field_name: redirect_to,
247 'site': current_site,
248 'site_name': current_site.name,
249 }, context_instance=RequestContext(request))
250 login = never_cache(login)
251
252 # groupes
253 def groupe_index(request):
254 search_form = GroupeSearchForm(request.GET)
255 search = search_form.save(commit=False)
256 groupes = search.run()
257 nb_resultats = groupes.count()
258 try:
259 p = PageStatique.objects.get(id='groupes')
260 entete = p.contenu
261 except PageStatique.DoesNotExist:
262 entete = '<h1>Liste des groupes</h1>'
263
264 est_chercheur, mesgroupes, messages = False, None, None
265 if request.user.is_authenticated():
266 try:
267 chercheur = Chercheur.objects.get(courriel=request.user.email)
268 mesgroupes = chercheur.groupes.all().filter(membership__statut='accepte')
269 messages = Message.objects.all().filter(groupe__in=mesgroupes)[:10]
270 est_chercheur = True
271 except Chercheur.DoesNotExist:
272 pass
273
274 return render_to_response("chercheurs/groupe_index.html", {
275 'search_form': search_form,
276 'groupes': groupes.order_by('nom'),
277 'nb_resultats': nb_resultats,
278 'entete': entete,
279 'mesgroupes': mesgroupes,
280 'messages': messages,
281 'est_chercheur': est_chercheur,
282 }, context_instance=RequestContext(request))
283
284 def groupe_adhesion(request, id):
285 try:
286 groupe = get_object_or_404(Groupe, id=id)
287 chercheur = Chercheur.objects.get(courriel=request.user.email)
288 adhesion, created = AdhesionGroupe.objects.get_or_create(chercheur=chercheur, groupe=groupe)
289 if created:
290 adhesion.actif = 0
291 adhesion.save()
292 except:
293 pass
294
295 return HttpResponseRedirect(url('groupe_retrieve', kwargs={'id': id}))
296
297 def groupe_retrieve(request, id):
298 groupe = get_object_or_404(Groupe, id=id)
299 membres = groupe.membership.all().filter(statut='accepte').order_by('-date_modification')
300 plus_que_20 = True if membres.count() > 20 else False
301 membres_20 = membres[:20]
302 messages = groupe.message_set.all()[:5]
303
304 est_chercheur, est_membre, est_membre_actif = False, False, False
305 if request.user.is_authenticated():
306 try:
307 chercheur = Chercheur.objects.get(courriel=request.user.email)
308 est_chercheur = True
309 est_membre = chercheur in groupe.membres.all()
310 est_membre_actif = bool(len(groupe.membership.filter(chercheur=chercheur, statut='accepte')))
311 except Chercheur.DoesNotExist:
312 pass
313
314 return render_to_response(
315 "chercheurs/groupe_retrieve.html", {
316 'groupe': groupe,
317 'membres': membres_20,
318 'plus_que_20': plus_que_20,
319 'messages': messages,
320 'est_chercheur': est_chercheur,
321 'est_membre': est_membre,
322 'est_membre_actif': est_membre_actif,
323 }, context_instance=RequestContext(request)
324 )
325
326 def groupe_membres(request, id):
327 groupe = get_object_or_404(Groupe, id=id)
328 membres = groupe.membership.all().filter(statut='accepte').order_by('chercheur__nom')
329
330 return render_to_response(
331 "chercheurs/groupe_membres.html", {
332 'groupe': groupe,
333 'membres': membres,
334 }, context_instance=RequestContext(request)
335 )
336
337 def groupe_messages(request, id):
338
339 groupe = get_object_or_404(Groupe, id=id)
340
341 est_chercheur, est_membre, est_membre_actif = False, False, False
342 if request.user.is_authenticated():
343 try:
344 chercheur = Chercheur.objects.get(courriel=request.user.email)
345 est_chercheur = True
346 est_membre = chercheur in groupe.membres.all()
347 est_membre_actif = bool(len(groupe.membership.filter(chercheur=chercheur, statut='accepte')))
348 except Chercheur.DoesNotExist:
349 pass
350
351 if est_membre_actif and request.method == 'POST':
352 form = MessageForm(request.POST)
353 if form.is_valid():
354 message = form.save(commit=False)
355 message.groupe = groupe
356 message.chercheur = chercheur
357 message.save()
358
359 form = MessageForm()
360
361 else:
362 form = MessageForm()
363
364 messages = groupe.message_set.all()
365
366 return render_to_response(
367 "chercheurs/groupe_message.html", {
368 'groupe': groupe,
369 'messages': messages,
370 'form': form,
371 'est_chercheur': est_chercheur,
372 'est_membre': est_membre,
373 'est_membre_actif': est_membre_actif,
374 }, context_instance=RequestContext(request)
375 )