Recherches sauvegardées
[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
4 from chercheurs.models import Chercheur
5 from chercheurs.utils import get_django_user_for_email
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, login
22 from django.shortcuts import get_object_or_404
23 from savoirs.models import PageStatique, Discipline
24
25 def index(request):
26 """Répertoire des chercheurs"""
27 search_form = ChercheurSearchForm(request.GET)
28 search = search_form.save(commit=False)
29 chercheurs = search.run().select_related('etablissement')
30 sort = request.GET.get('tri')
31 if sort is not None and sort.endswith('_desc'):
32 sort = sort[:-5]
33 direction = '-'
34 else:
35 direction = ''
36 if sort == 'nom':
37 chercheurs = chercheurs.order_by_nom(direction)
38 elif sort == 'etablissement':
39 chercheurs = chercheurs.order_by_etablissement(direction)
40 elif sort == 'pays':
41 chercheurs = chercheurs.order_by_pays(direction)
42 else:
43 chercheurs = chercheurs.order_by('-date_modification')
44
45 try:
46 p = PageStatique.objects.get(id='repertoire')
47 entete = p.contenu
48 except PageStatique.DoesNotExist:
49 entete = u'<h1>Répertoire des chercheurs</h1>'
50
51 nb_chercheurs = chercheurs.count()
52
53 return render_to_response("chercheurs/index.html",
54 dict(chercheurs=chercheurs, nb_chercheurs=nb_chercheurs,
55 search_form=search_form, entete=entete),
56 context_instance=RequestContext(request))
57
58 def inscription(request):
59 if request.method == 'POST':
60 forms = ChercheurFormGroup(request.POST)
61 if forms.is_valid():
62 chercheur = forms.save()
63 id_base36 = int_to_base36(chercheur.id)
64 token = chercheur.activation_token()
65 template = get_template('chercheurs/activation_email.txt')
66 domain = RequestSite(request).domain
67 message = template.render(Context(dict(chercheur=chercheur, id_base36=id_base36, token=token, domain=domain)))
68 send_mail('Votre inscription à Savoirs en partage', message, None, [chercheur.courriel])
69 return HttpResponseRedirect(url('chercheurs-inscription-faite'))
70 else:
71 forms = ChercheurFormGroup()
72
73 return render_to_response("chercheurs/inscription.html",
74 dict(forms=forms),
75 context_instance=RequestContext(request))
76
77 def activation(request, id_base36, token):
78 """Activation d'un chercheur"""
79 id = base36_to_int(id_base36)
80 chercheur = get_object_or_404(Chercheur.all_objects, id=id)
81 if token == chercheur.activation_token():
82 validlink = True
83 if request.method == 'POST':
84 form = SetPasswordForm(request.POST)
85 if form.is_valid():
86 password = form.cleaned_data['password']
87 email = chercheur.courriel
88 chercheur.actif = True
89 chercheur.save()
90 user = get_django_user_for_email(email)
91 user.set_password(password)
92 user.save()
93
94 # Auto-login
95 auth_login(request, authenticate(username=email, password=password))
96 return HttpResponseRedirect(url('chercheurs.views.perso'))
97 else:
98 form = SetPasswordForm()
99 else:
100 form = None
101 validlink = False
102 return render_to_response('chercheurs/activation.html', dict(form=form, validlink=validlink),
103 context_instance=RequestContext(request))
104
105 @chercheur_required
106 def desinscription(request):
107 """Désinscription du chercheur"""
108 chercheur = request.chercheur
109 if request.method == 'POST':
110 if request.POST.get('confirmer'):
111 chercheur.actif = False
112 chercheur.save()
113 request.flash['message'] = "Vous avez été désinscrit du répertoire des chercheurs."
114 return HttpResponseRedirect(url('django.contrib.auth.views.logout'))
115 else:
116 request.flash['message'] = "Opération annulée."
117 return HttpResponseRedirect(url('chercheurs.views.perso'))
118 return render_to_response("chercheurs/desinscription.html", {},
119 context_instance=RequestContext(request))
120
121 @chercheur_required
122 @never_cache
123 def edit(request):
124 """Edition d'un chercheur"""
125 chercheur = request.chercheur
126 if request.method == 'POST':
127 forms = ChercheurFormGroup(request.POST, chercheur=chercheur)
128 if forms.is_valid():
129 forms.save()
130 request.flash['message'] = "Votre fiche a bien été enregistrée."
131 return HttpResponseRedirect(url('chercheurs.views.perso'))
132 else:
133 forms = ChercheurFormGroup(chercheur=chercheur)
134
135 return render_to_response("chercheurs/edit.html",
136 dict(forms=forms, chercheur=chercheur),
137 context_instance=RequestContext(request))
138
139 @chercheur_required
140 def perso(request):
141 """Espace chercheur (espace personnel du chercheur)"""
142 chercheur = request.chercheur
143 modification = request.GET.get('modification')
144 return render_to_response("chercheurs/perso.html",
145 dict(chercheur=chercheur, modification=modification),
146 context_instance=RequestContext(request))
147
148 def retrieve(request, id):
149 """Fiche du chercheur"""
150 chercheur = get_object_or_404(Chercheur, id=id)
151 return render_to_response("chercheurs/retrieve.html",
152 dict(chercheur=chercheur),
153 context_instance=RequestContext(request))
154
155 def conversion(request):
156 return render_to_response("chercheurs/conversion.html", {},
157 context_instance=RequestContext(request))
158
159 def etablissements_autocomplete(request, pays=None):
160 term = request.GET.get('term')
161 noms = Etablissement.objects.all().filter(membre=True, actif=True)
162 for word in term.split():
163 noms = noms.filter(nom__icontains=word)
164 if pays:
165 noms = noms.filter(pays=pays)
166 noms = list(noms.values_list('nom', flat=True)[:20])
167 json = simplejson.dumps(noms)
168 return HttpResponse(json, mimetype='application/json')
169
170 def login(request, template_name='registration/login.html', redirect_field_name=REDIRECT_FIELD_NAME):
171 "The Django login view, but using a custom form."
172 redirect_to = request.REQUEST.get(redirect_field_name, '')
173
174 if request.method == "POST":
175 form = AuthenticationForm(data=request.POST)
176 if form.is_valid():
177 # Light security check -- make sure redirect_to isn't garbage.
178 if not redirect_to or ' ' in redirect_to:
179 redirect_to = settings.LOGIN_REDIRECT_URL
180
181 # Heavier security check -- redirects to http://example.com should
182 # not be allowed, but things like /view/?param=http://example.com
183 # should be allowed. This regex checks if there is a '//' *before* a
184 # question mark.
185 elif '//' in redirect_to and re.match(r'[^\?]*//', redirect_to):
186 redirect_to = settings.LOGIN_REDIRECT_URL
187
188 # Okay, security checks complete. Log the user in.
189 auth_login(request, form.get_user())
190
191 if request.session.test_cookie_worked():
192 request.session.delete_test_cookie()
193
194 return HttpResponseRedirect(redirect_to)
195
196 else:
197 form = AuthenticationForm(request)
198 request.session.set_test_cookie()
199
200 if Site._meta.installed:
201 current_site = Site.objects.get_current()
202 else:
203 current_site = RequestSite(request)
204
205 return render_to_response(template_name, {
206 'form': form,
207 redirect_field_name: redirect_to,
208 'site': current_site,
209 'site_name': current_site.name,
210 }, context_instance=RequestContext(request))
211 login = never_cache(login)