0fabd3c0757db1a97e02132f863370e5169c8a27
[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(direction + 'personne__nom', 'personne__prenom', '-date_modification')
132 elif sort == 'etablissement':
133 chercheurs = chercheurs.extra(select=dict(nom_etablissement='IFNULL(ref_etablissement.nom, chercheurs_chercheur.etablissement_autre_nom)'),
134 order_by=[direction + 'nom_etablissement', '-date_modification'])
135 elif sort == 'pays':
136 chercheurs = chercheurs.extra(select=dict(
137 pays_etablissement='(SELECT nom FROM ref_pays WHERE ref_pays.code = IFNULL(ref_etablissement.pays, chercheurs_chercheur.etablissement_autre_pays))'
138 ), order_by=[direction + 'pays_etablissement', '-date_modification'])
139 else:
140 chercheurs = chercheurs.order_by('-date_modification')
141
142 nb_chercheurs = chercheurs.count()
143 return render_to_response("chercheurs/index.html",
144 dict(chercheurs=chercheurs, nb_chercheurs=nb_chercheurs, search_form=search_form),
145 context_instance=RequestContext(request))
146
147 def inscription(request):
148 if request.method == 'POST':
149 forms = ChercheurFormGroup(request.POST)
150 if forms.is_valid():
151 forms.save()
152 # login automatique
153 login(request, authenticate(username=forms.personne.cleaned_data['courriel'],
154 password=forms.personne.cleaned_data['password']))
155 return HttpResponseRedirect(url('chercheurs.views.perso'))
156 else:
157 forms = ChercheurFormGroup()
158
159 return render_to_response("chercheurs/inscription.html",
160 dict(forms=forms),
161 context_instance=RequestContext(request))
162
163 @login_required()
164 def desinscription(request):
165 """Désinscription du chercheur"""
166 try:
167 chercheur = Chercheur.objects.get(personne__courriel=request.user.email, personne__actif=True)
168 except Chercheur.DoesNotExist:
169 return HttpResponseRedirect(url('chercheurs.views.chercheur_login'))
170 if request.method == 'POST':
171 if request.POST.get('confirmer'):
172 chercheur.personne.actif = False
173 chercheur.personne.save()
174 User.objects.filter(username=chercheur.personne.courriel).delete()
175 request.flash['message'] = "Vous avez été désinscrit du répertoire des chercheurs."
176 return HttpResponseRedirect(url('django.contrib.auth.views.logout'))
177 else:
178 request.flash['message'] = "Opération annulée."
179 return HttpResponseRedirect(url('chercheurs.views.perso'))
180 return render_to_response("chercheurs/desinscription.html", {},
181 context_instance=RequestContext(request))
182
183 @login_required()
184 @never_cache
185 def edit(request):
186 """Edition d'un chercheur"""
187 context_instance = RequestContext(request)
188 chercheur = context_instance['user_chercheur']
189 if request.method == 'POST':
190 forms = ChercheurFormGroup(request.POST, chercheur=chercheur)
191 if forms.is_valid():
192 forms.save()
193 return HttpResponseRedirect(url('chercheurs.views.perso') + '?modification=1')
194 else:
195 forms = ChercheurFormGroup(chercheur=chercheur)
196
197 return render_to_response("chercheurs/edit.html",
198 dict(forms=forms, chercheur=chercheur),
199 context_instance=RequestContext(request))
200
201 @login_required()
202 def perso(request):
203 """Espace chercheur (espace personnel du chercheur)"""
204 context_instance = RequestContext(request)
205 chercheur = context_instance['user_chercheur']
206 modification = request.GET.get('modification')
207 if not chercheur:
208 return HttpResponseRedirect(url('chercheurs.views.chercheur_login'))
209 return render_to_response("chercheurs/perso.html",
210 dict(chercheur=chercheur, modification=modification),
211 context_instance=context_instance)
212
213 def retrieve(request, id):
214 """Fiche du chercheur"""
215 chercheur = get_object_or_404(Chercheur, id=id)
216 return render_to_response("chercheurs/retrieve.html",
217 dict(chercheur=chercheur),
218 context_instance=RequestContext(request))
219
220 def conversion(request):
221 return render_to_response("chercheurs/conversion.html", {},
222 context_instance=RequestContext(request))
223
224 def etablissements_autocomplete(request, pays=None):
225 term = request.GET.get('term')
226 noms = Etablissement.objects.all()
227 for word in term.split():
228 noms = noms.filter(nom__icontains=word)
229 if pays:
230 noms = noms.filter(pays=pays)
231 noms = list(noms.values_list('nom', flat=True)[:20])
232 json = simplejson.dumps(noms)
233 return HttpResponse(json, mimetype='application/json')