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