Correction de l'indexation des chercheurs.
[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 as url
8 from django.core.mail import send_mail
9 from django.conf import settings
10 from django.utils import simplejson
11 from django.views.decorators.cache import never_cache
12
13 from forms import *
14 from django.forms.models import inlineformset_factory
15
16 from auf_references_client.models import Discipline, TypeImplantation
17 from models import Personne, Utilisateur, Groupe, ChercheurGroupe
18
19 from django.contrib.auth import authenticate, login
20 from django.contrib.auth.decorators import login_required
21 from django.contrib.auth.forms import AuthenticationForm as OriginalAuthenticationForm
22 from django.contrib.auth.models import User
23
24 from django.db.models import Q
25 from django.shortcuts import get_object_or_404
26
27 from django.utils.translation import ugettext_lazy as _
28
29 #TODO: Migrer tout ce qui a rapport aux users dans une nouvelle app
30
31 class AuthenticationForm(OriginalAuthenticationForm):
32 username = forms.CharField(label='Adresse électronique', max_length=255)
33
34 def send_password(request):
35 if request.method == "POST":
36 form = SendPasswordForm(data=request.POST)
37 if form.is_valid():
38 u = Utilisateur.objects.get(courriel=form.cleaned_data['email'], actif=True)
39 code = u.get_new_password_code()
40 link = "%s/accounts/new_password/%s/%s/" % (settings.SITE_ROOT_URL, u.courriel, code)
41
42 variables = { 'user': u,
43 'link': link,
44 'SITE_ROOT_URL': settings.SITE_ROOT_URL,
45 'CONTACT_EMAIL': settings.CONTACT_EMAIL,
46 }
47 t = get_template('accounts/email_password.html')
48 content = t.render(Context(variables))
49
50 send_mail('Savoirs en partage: changement de mot de passe',
51 content, settings.CONTACT_EMAIL,
52 [u.courriel], fail_silently=False)
53 else:
54 form = SendPasswordForm()
55
56 variables = { 'form': form,
57 }
58 return render_to_response ("accounts/send_password.html", \
59 Context (variables),
60 context_instance = RequestContext(request))
61
62 def new_password(request, email, code):
63 u = Utilisateur.objects.get(courriel=email, actif=True)
64 original_code = u.get_new_password_code()
65 message=""
66 if(code == original_code):
67 if request.method == "POST":
68 form = NewPasswordForm(data=request.POST)
69 if form.is_valid():
70 u.set_password(form.cleaned_data['password'])
71 u.save()
72 message = "Votre mot de passe a été modifié."
73 else:
74 form = NewPasswordForm()
75 else:
76 return HttpResponseRedirect('/')
77 variables = { 'form': form,
78 'message': message,
79 }
80 return render_to_response ("accounts/new_password.html", \
81 Context (variables),
82 context_instance = RequestContext(request))
83
84 @login_required()
85 def change_password(request):
86 context_instance = RequestContext(request)
87 u = context_instance['user_sep']
88 message = ""
89 if request.method == "POST":
90 form = NewPasswordForm(data=request.POST)
91 if form.is_valid():
92 u.set_password(form.cleaned_data['password'])
93 u.save()
94 message = "Votre mot de passe a été modifié."
95 else:
96 form = NewPasswordForm()
97 variables = { 'form': form,
98 'message': message,
99 }
100 return render_to_response ("accounts/new_password.html", \
101 Context (variables),
102 context_instance = RequestContext(request))
103
104 def chercheur_login(request):
105 "Displays the login form and handles the login action."
106 if request.method == "POST":
107 form = AuthenticationForm(data=request.POST)
108 if form.is_valid():
109 from django.contrib.auth import login
110 login(request, form.get_user())
111 if request.session.test_cookie_worked():
112 request.session.delete_test_cookie()
113 return HttpResponseRedirect(url('chercheurs.views.perso'))
114 else:
115 form = AuthenticationForm(request)
116 request.session.set_test_cookie()
117 return render_to_response('accounts/login.html', dict(form=form),
118 context_instance=RequestContext(request))
119
120 def index(request):
121 """Répertoire des chercheurs"""
122 search_form = RepertoireSearchForm(request.GET)
123 chercheurs = search_form.get_query_set().select_related('personne', 'etablissement')
124 sort = request.GET.get('tri')
125 if sort is not None and sort.endswith('_desc'):
126 sort = sort[:-5]
127 direction = '-'
128 else:
129 direction = ''
130 if sort == 'nom':
131 chercheurs = chercheurs.order_by_nom(direction)
132 elif sort == 'etablissement':
133 chercheurs = chercheurs.order_by_etablissement(direction)
134 elif sort == 'pays':
135 chercheurs = chercheurs.order_by_pays(direction)
136 else:
137 chercheurs = chercheurs.order_by('-date_modification')
138
139 nb_chercheurs = chercheurs.count()
140 return render_to_response("chercheurs/index.html",
141 dict(chercheurs=chercheurs, nb_chercheurs=nb_chercheurs, search_form=search_form),
142 context_instance=RequestContext(request))
143
144 def inscription(request):
145 if request.method == 'POST':
146 forms = ChercheurFormGroup(request.POST)
147 if forms.is_valid():
148 forms.save()
149 # login automatique
150 login(request, authenticate(username=forms.personne.cleaned_data['courriel'],
151 password=forms.personne.cleaned_data['password']))
152 return HttpResponseRedirect(url('chercheurs.views.perso'))
153 else:
154 forms = ChercheurFormGroup()
155
156 return render_to_response("chercheurs/inscription.html",
157 dict(forms=forms),
158 context_instance=RequestContext(request))
159
160 @login_required()
161 def desinscription(request):
162 """Désinscription du chercheur"""
163 try:
164 chercheur = Chercheur.objects.get(personne__courriel=request.user.email, personne__actif=True)
165 except Chercheur.DoesNotExist:
166 return HttpResponseRedirect(url('chercheurs.views.chercheur_login'))
167 if request.method == 'POST':
168 if request.POST.get('confirmer'):
169 chercheur.personne.actif = False
170 chercheur.personne.save()
171 User.objects.filter(username=chercheur.personne.courriel).delete()
172 request.flash['message'] = "Vous avez été désinscrit du répertoire des chercheurs."
173 return HttpResponseRedirect(url('django.contrib.auth.views.logout'))
174 else:
175 request.flash['message'] = "Opération annulée."
176 return HttpResponseRedirect(url('chercheurs.views.perso'))
177 return render_to_response("chercheurs/desinscription.html", {},
178 context_instance=RequestContext(request))
179
180 @login_required()
181 @never_cache
182 def edit(request):
183 """Edition d'un chercheur"""
184 context_instance = RequestContext(request)
185 chercheur = context_instance['user_chercheur']
186 if request.method == 'POST':
187 forms = ChercheurFormGroup(request.POST, chercheur=chercheur)
188 if forms.is_valid():
189 forms.save()
190 return HttpResponseRedirect(url('chercheurs.views.perso') + '?modification=1')
191 else:
192 forms = ChercheurFormGroup(chercheur=chercheur)
193
194 return render_to_response("chercheurs/edit.html",
195 dict(forms=forms, chercheur=chercheur),
196 context_instance=RequestContext(request))
197
198 @login_required()
199 def perso(request):
200 """Espace chercheur (espace personnel du chercheur)"""
201 context_instance = RequestContext(request)
202 chercheur = context_instance['user_chercheur']
203 modification = request.GET.get('modification')
204 if not chercheur:
205 return HttpResponseRedirect(url('chercheurs.views.chercheur_login'))
206 return render_to_response("chercheurs/perso.html",
207 dict(chercheur=chercheur, modification=modification),
208 context_instance=context_instance)
209
210 def retrieve(request, id):
211 """Fiche du chercheur"""
212 chercheur = get_object_or_404(Chercheur, id=id)
213 return render_to_response("chercheurs/retrieve.html",
214 dict(chercheur=chercheur),
215 context_instance=RequestContext(request))
216
217 def conversion(request):
218 return render_to_response("chercheurs/conversion.html", {},
219 context_instance=RequestContext(request))
220
221 def etablissements_autocomplete(request, pays=None):
222 term = request.GET.get('term')
223 noms = Etablissement.objects.all()
224 for word in term.split():
225 noms = noms.filter(nom__icontains=word)
226 if pays:
227 noms = noms.filter(pays=pays)
228 noms = list(noms.values_list('nom', flat=True)[:20])
229 json = simplejson.dumps(noms)
230 return HttpResponse(json, mimetype='application/json')