Only forbid people to send comments not to view them
[cascardo/ema.git] / eventos / views.py
1 # -*- coding: utf-8 -*-
2 # Copyright (C) 2008 Lincoln de Sousa <lincoln@minaslivre.org>
3 #
4 # This program is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU General Public License as
6 # published by the Free Software Foundation; either version 2 of the
7 # License, or (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12 # General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public
15 # License along with this program; if not, write to the
16 # Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 # Boston, MA 02111-1307, USA.
18 from django.conf import settings
19 from django.http import HttpResponseRedirect, HttpResponseForbidden
20 from django.contrib.auth import authenticate, login as login_django, \
21     logout as logout_django
22 from django.contrib.auth.models import User, Group
23 from django.forms import HiddenInput, ModelForm
24 from django.shortcuts import render_to_response, get_object_or_404
25 from django.template import RequestContext, Context, loader
26 from eventos.models import Palestrante, Trabalho, TipoTrabalho, Trilha, Evento, Improve
27 from eventos.forms import RegisterSpeaker
28 from django.db.models import Q
29
30 forbidden = \
31     HttpResponseForbidden('<h2>You are not allowed to do this action.<h2>')
32
33 class SpeakerForm(ModelForm):
34     class Meta:
35         model = Palestrante
36         exclude = ('usuario',)
37
38 class TalkForm(ModelForm):
39     class Meta:
40         model = Trabalho
41
42 class ImproveForm(ModelForm):
43     class Meta:
44         model = Improve
45
46 def login(request):
47     """This is a function that will be used as a front-end to the
48     django's login system. It receives username and password fields
49     from a POST request and tries to login the user.
50
51     If login is successful, user will be redirected to the referer
52     address, otherwise will be redirected to /?login_failed.
53     """
54     username = request.POST['username']
55     password = request.POST['password']
56     user = authenticate(username=username, password=password)
57
58     if user is not None:
59         if user.is_active:
60             login_django(request, user)
61             try:
62                 request.session.delete_test_cookie()
63             except KeyError:
64                 pass
65             return HttpResponseRedirect('/')
66         else:
67             return HttpResponseRedirect('/?login_failed')
68     else:
69         return HttpResponseRedirect('/?login_failed')
70
71     request.session.set_test_cookie()
72     return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
73
74 def logout(request):
75     """Simple front-end to django's logout stuff. This function should
76     be mapped to an url and simply called without any parameter.
77     """
78     logout_django(request)
79     return HttpResponseRedirect('/')
80
81 def speaker_add(request):
82     """Adds a new speaker to the system.
83     """
84     uform = RegisterSpeaker(request.POST or None)
85
86     form = SpeakerForm(request.POST or None)
87
88     if request.POST and form.is_valid() and uform.is_valid():
89         cd = uform.cleaned_data
90         group = Group.objects.get_or_create(name='palestrantes')[0]
91
92         # creating the user that will be set as the user of the
93         # speaker.
94         user = User(username=cd['username'])
95         user.set_password(cd['password1'])
96         user.is_active = True
97         user.save()
98         user.groups.add(group)
99
100         # this commit=False is to avoid IntegritErrors, because at
101         # this point, the speaker doesn't have an user associated
102         # with it.
103         instance = form.save(commit=False)
104         instance.usuario = user
105         instance.save()
106         return HttpResponseRedirect('/')
107
108     c = {'form': form, 'uform': uform}
109     return render_to_response('eventos/speaker-add.html', Context(c),
110                               context_instance=RequestContext(request))
111
112 def speaker_details(request, lid):
113     """Shows a simple form containing all editable fields of a
114     speaker and gives the speaker the possibility to save them =)
115     """
116     if not hasattr(request.user, 'palestrante_set'):
117         return forbidden
118
119     entity = request.user.palestrante_set.get()
120     if entity.id != int(lid):
121         return forbidden
122
123     form = SpeakerForm(request.POST or None, instance=entity)
124
125     if request.POST and form.is_valid():
126         form.save()
127
128     c = {'form': form}
129     return render_to_response('eventos/speaker-details.html', Context(c),
130                               context_instance=RequestContext(request))
131
132 def speaker_talks(request, lid):
133     """Lists all talks of a speaker (based on speaker id -- lid
134     parameter).
135     """
136     if not hasattr(request.user, 'palestrante_set'):
137         return forbidden
138
139     entity = request.user.palestrante_set.get()
140     if entity.id != int(lid):
141         return forbidden
142
143     talks = Trabalho.objects.filter(
144         Q(palestrante=entity) | Q(outros_palestrantes=entity) )
145
146     c = {'speaker': entity, 'talks': talks}
147     return render_to_response('eventos/talk-list.html', Context(c),
148                               context_instance=RequestContext(request))
149
150 def talk_details(request, tid):
151     """Shows a form to edit a talk
152     """
153     # If the user is not a speaker we should not try to show anything.
154     if not hasattr(request.user, 'palestrante_set'):
155         return forbidden
156
157     # Selected in settings.py (SITE_ID) variable, because an event can
158     # be linked with only one site.
159     event = Evento.objects.get(site__id__exact=settings.SITE_ID)
160
161     # building the form
162     entity = get_object_or_404(Trabalho, pk=tid)
163     form = TalkForm(request.POST or None, instance=entity)
164
165     # These fields should not be shown to the user.
166     form.fields['palestrante'].widget = HiddenInput()
167     form.fields['evento'].widget = HiddenInput()
168
169     # These fields are event specific
170     trilhas = Trilha.objects.filter(evento=event)
171     form.fields['trilha']._set_queryset(trilhas)
172
173     tipos = TipoTrabalho.objects.filter(evento=event)
174     form.fields['tipo']._set_queryset(tipos)
175
176     # hidding the owner in the other speakers list
177     other = Palestrante.objects.exclude(pk=entity.id)
178     form.fields['outros_palestrantes']._set_queryset(other)
179     if other.count() == 0:
180         # I need set the value to '', otherwise the wise django
181         # newforms will fill the field with the invalid string '[]'
182         form.fields['outros_palestrantes'].initial = ''
183         form.fields['outros_palestrantes'].widget = HiddenInput()
184
185     # avoiding smart people trying to se talks of other speakers.
186     speaker = request.user.palestrante_set.get()
187     if speaker.id != entity.palestrante.id \
188             and speaker not in entity.outros_palestrantes.all():
189         return forbidden
190
191     if request.POST and form.is_valid():
192         form.save()
193
194     c = {'form': form}
195     return render_to_response('eventos/talk-details.html', Context(c),
196                               context_instance=RequestContext(request))
197
198 def talk_delete(request, tid):
199     """Drops a talk but only if the logged in user is its owner.
200     """
201     if not hasattr(request.user, 'palestrante_set'):
202         return forbidden
203
204     entity = request.user.palestrante_set.get()
205     talk = Trabalho.objects.filter(pk=tid, palestrante=entity)
206     if not talk:
207         return forbidden
208
209     talk.delete()
210     return HttpResponseRedirect('/speaker/%d/talks/' % entity.id)
211
212 def talk_add(request):
213     """Shows a form to the speaker send a talk
214     """
215     if not hasattr(request.user, 'palestrante_set'):
216         return forbidden
217
218     # building the form
219     form = TalkForm(request.POST or None)
220
221     # These fields should not be shown to the user.
222
223     # Selected in settings.py (SITE_ID) variable, because an event can
224     # be linked with only one site.
225     entity = request.user.palestrante_set.get()
226     form.fields['palestrante'].widget = HiddenInput(attrs={'value' : entity.id})
227
228     event = Evento.objects.get(site__id__exact=settings.SITE_ID)
229     form.fields['evento'].widget = HiddenInput(attrs={'value' : event.id})
230
231     # These fields are event specific
232     trilhas = Trilha.objects.filter(evento=event)
233     form.fields['trilha']._set_queryset(trilhas)
234
235     tipos = TipoTrabalho.objects.filter(evento=event)
236     form.fields['tipo']._set_queryset(tipos)
237
238     # hidding the owner in the other speakers list
239     other = Palestrante.objects.exclude(pk=entity.id)
240     form.fields['outros_palestrantes']._set_queryset(other)
241     if other.count() == 0:
242         form.fields['outros_palestrantes'].widget = HiddenInput()
243
244     if request.POST and form.is_valid():
245         # validation
246         cleaned = form.cleaned_data
247         if cleaned['tipo'].evento.id != event.id:
248             return forbidden
249
250         if cleaned['trilha'].evento.id != event.id:
251             return forbidden
252
253         instance = form.save()
254         return HttpResponseRedirect('/speaker/%d/talks/' % entity.id)
255
256     c = {'form': form}
257     return render_to_response('eventos/talk-add.html', Context(c),
258                               context_instance=RequestContext(request))
259
260 def list_all_talks(request):
261     event = Evento.objects.get(site__id__exact=settings.SITE_ID)
262     trilhas = Trilha.objects.filter(evento=event)
263
264     improve = []
265     for t in trilhas:
266         talks = Trabalho.objects.filter(trilha=t)
267         aux = {'trilha':t.nome, 'talks':talks}
268         improve.append(aux)
269
270     c = {'improve': improve,}
271     return render_to_response('eventos/improve.html', Context(c),
272                               context_instance=RequestContext(request))
273
274 def talk_improve(request, tid):
275     if not hasattr(request.user, 'palestrante_set') and request.POST:
276         return forbidden
277
278     talk = get_object_or_404(Trabalho, pk=tid)
279     improve = Improve.objects.filter(trabalho=talk)
280
281     # building the form
282     form = ImproveForm(request.POST or None)
283     form.fields['trabalho'].widget = HiddenInput(attrs={'value':talk.id})
284     form.fields['usuario'].widget = HiddenInput(attrs={'value':request.user.id})
285
286     if request.POST and form.is_valid():
287         event = Evento.objects.get(site__id__exact=settings.SITE_ID)
288         # validation
289         cleaned = form.cleaned_data
290         if cleaned['trabalho'].evento.id != event.id:
291             return forbidden
292
293         instance = form.save()
294         return HttpResponseRedirect('/improve/%d/' % talk.id)
295
296     c = {'talk': talk, 'form': form, 'improve': improve}
297     return render_to_response('eventos/talk_improve.html', Context(c),
298                               context_instance=RequestContext(request))