Découpler un peu les chercheurs et l'authentification Django
[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 RepertoireSearchForm, SetPasswordForm, ChercheurFormGroup
4 from chercheurs.models import Chercheur
5 from chercheurs.utils import get_django_user_for_email
6 from datamaster_modeles.models import Etablissement
7 from django.shortcuts import render_to_response
8 from django.http import HttpResponseRedirect, HttpResponse
9 from django.template import Context, RequestContext
10 from django.template.loader import get_template
11 from django.core.urlresolvers import reverse as url
12 from django.core.mail import send_mail
13 from django.contrib.sites.models import RequestSite
14 from django.utils import simplejson
15 from django.utils.http import int_to_base36, base36_to_int
16 from django.views.decorators.cache import never_cache
17 from django.contrib.auth import authenticate, login
18 from django.shortcuts import get_object_or_404
19
20 def index(request):
21 """Répertoire des chercheurs"""
22 search_form = RepertoireSearchForm(request.GET)
23 chercheurs = search_form.get_query_set().select_related('etablissement')
24 sort = request.GET.get('tri')
25 if sort is not None and sort.endswith('_desc'):
26 sort = sort[:-5]
27 direction = '-'
28 else:
29 direction = ''
30 if sort == 'nom':
31 chercheurs = chercheurs.order_by_nom(direction)
32 elif sort == 'etablissement':
33 chercheurs = chercheurs.order_by_etablissement(direction)
34 elif sort == 'pays':
35 chercheurs = chercheurs.order_by_pays(direction)
36 else:
37 chercheurs = chercheurs.order_by('-date_modification')
38
39 nb_chercheurs = chercheurs.count()
40 return render_to_response("chercheurs/index.html",
41 dict(chercheurs=chercheurs, nb_chercheurs=nb_chercheurs, search_form=search_form),
42 context_instance=RequestContext(request))
43
44 def inscription(request):
45 if request.method == 'POST':
46 forms = ChercheurFormGroup(request.POST)
47 if forms.is_valid():
48 chercheur = forms.save()
49 id_base36 = int_to_base36(chercheur.id)
50 token = chercheur.activation_token()
51 template = get_template('chercheurs/activation_email.txt')
52 domain = RequestSite(request).domain
53 message = template.render(Context(dict(chercheur=chercheur, id_base36=id_base36, token=token, domain=domain)))
54 send_mail('Votre inscription à Savoirs en partage', message, None, [chercheur.courriel])
55 return HttpResponseRedirect(url('chercheurs-inscription-faite'))
56 else:
57 forms = ChercheurFormGroup()
58
59 return render_to_response("chercheurs/inscription.html",
60 dict(forms=forms),
61 context_instance=RequestContext(request))
62
63 def activation(request, id_base36, token):
64 """Activation d'un chercheur"""
65 id = base36_to_int(id_base36)
66 chercheur = get_object_or_404(Chercheur, id=id)
67 if token == chercheur.activation_token():
68 validlink = True
69 if request.method == 'POST':
70 form = SetPasswordForm(request.POST)
71 if form.is_valid():
72 password = form.cleaned_data['password']
73 email = chercheur.courriel
74 chercheur.actif = True
75 chercheur.save()
76 user = get_django_user_for_email(email)
77 user.set_password(password)
78 user.save()
79
80 # Auto-login
81 login(request, authenticate(username=email, password=password))
82 return HttpResponseRedirect(url('chercheurs.views.perso'))
83 else:
84 form = SetPasswordForm()
85 else:
86 form = None
87 validlink = False
88 return render_to_response('chercheurs/activation.html', dict(form=form, validlink=validlink),
89 context_instance=RequestContext(request))
90
91 @chercheur_required
92 def desinscription(request):
93 """Désinscription du chercheur"""
94 chercheur = request.chercheur
95 if request.method == 'POST':
96 if request.POST.get('confirmer'):
97 chercheur.actif = False
98 chercheur.save()
99 request.flash['message'] = "Vous avez été désinscrit du répertoire des chercheurs."
100 return HttpResponseRedirect(url('django.contrib.auth.views.logout'))
101 else:
102 request.flash['message'] = "Opération annulée."
103 return HttpResponseRedirect(url('chercheurs.views.perso'))
104 return render_to_response("chercheurs/desinscription.html", {},
105 context_instance=RequestContext(request))
106
107 @chercheur_required
108 @never_cache
109 def edit(request):
110 """Edition d'un chercheur"""
111 chercheur = request.chercheur
112 if request.method == 'POST':
113 forms = ChercheurFormGroup(request.POST, chercheur=chercheur)
114 if forms.is_valid():
115 forms.save()
116 request.flash['message'] = "Votre fiche a bien été enregistrée."
117 return HttpResponseRedirect(url('chercheurs.views.perso'))
118 else:
119 forms = ChercheurFormGroup(chercheur=chercheur)
120
121 return render_to_response("chercheurs/edit.html",
122 dict(forms=forms, chercheur=chercheur),
123 context_instance=RequestContext(request))
124
125 @chercheur_required
126 def perso(request):
127 """Espace chercheur (espace personnel du chercheur)"""
128 chercheur = request.chercheur
129 modification = request.GET.get('modification')
130 return render_to_response("chercheurs/perso.html",
131 dict(chercheur=chercheur, modification=modification),
132 context_instance=RequestContext(request))
133
134 def retrieve(request, id):
135 """Fiche du chercheur"""
136 chercheur = get_object_or_404(Chercheur, id=id)
137 return render_to_response("chercheurs/retrieve.html",
138 dict(chercheur=chercheur),
139 context_instance=RequestContext(request))
140
141 def conversion(request):
142 return render_to_response("chercheurs/conversion.html", {},
143 context_instance=RequestContext(request))
144
145 def etablissements_autocomplete(request, pays=None):
146 term = request.GET.get('term')
147 noms = Etablissement.objects.all().filter(membre=True)
148 for word in term.split():
149 noms = noms.filter(nom__icontains=word)
150 if pays:
151 noms = noms.filter(pays=pays)
152 noms = list(noms.values_list('nom', flat=True)[:20])
153 json = simplejson.dumps(noms)
154 return HttpResponse(json, mimetype='application/json')