autenticando o cara depois de cadastrar como participante
[cascardo/eventmanager.git] / views.py
1 # -*- coding: utf-8; -*-
2 """
3 Copyright (C) 2007 Lincoln de Sousa <lincoln@archlinux-br.org>
4
5 This program is free software; you can redistribute it and/or
6 modify it under the terms of the GNU General Public License as
7 published by the Free Software Foundation; either version 2 of the
8 License, or (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 General Public License for more details.
14
15 You should have received a copy of the GNU General Public
16 License along with this program; if not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
19 """
20 from django.shortcuts import render_to_response, get_object_or_404
21 from django.template import RequestContext, Context, loader
22 from django.contrib.auth.decorators import login_required, user_passes_test
23 from django.contrib.auth.models import Group, User
24 from django.contrib.auth import authenticate, login
25 from django.newforms import form_for_instance
26 from django.core.mail import EmailMessage
27 from django.db import transaction
28 from django.http import get_host
29
30 from eventmanager.decorators import enable_login_form
31 from eventmanager.forms import *
32 from eventmanager.conteudo.models import Noticia, Menu, Secao
33 from eventmanager.eventos.models import *
34 import sha
35
36 FROM_EMAIL = 'Emsl 2007 <noreply@minaslivre.org>'
37
38 def build_response(request, template, extra={}):
39     """
40     Shortcut to build a response based on a C{template} and build a standard
41     context to this template. This context contains news itens, a list of menus
42     and a list of sections to be shown on index. But don't worry, this context
43     is extensible through the C{extra} parameter.
44
45     @param template: Contains the name of a template found in django
46      C{TEMPLATE_DIRS}
47     @type template: C{str}
48
49     @param extra: Extra variables to be passed to the context being built.
50     @type extra: C{dict}
51     """
52     news = Noticia.objects.order_by('-data_criacao')
53     menus = Menu.objects.all()
54     index_sections = Secao.objects.filter(index=True)
55     login_failed = 'login_failed' in request.GET
56     c = {'news': news, 'menu': menus,
57         'index_sections': index_sections,
58         'login_failed': login_failed}
59     c.update(extra)
60     return render_to_response(template, Context(c),
61             context_instance=RequestContext(request))
62
63
64 @enable_login_form
65 def index(request):
66     return build_response(request, 'index.html')
67
68
69 @transaction.commit_manually
70 @enable_login_form
71 def cadastro_palestrante(request):
72     form = CadastroPalestrante(request.POST or None)
73     ok = False
74     c = {'form': form}
75     if request.POST and form.is_valid():
76         cd = form.cleaned_data
77         badattr = form.errors
78
79         group = Group.objects.get_or_create(name='palestrantes')[0]
80
81         user = User(username=cd['nome_usuario'], email=cd['email'])
82         user.set_password(cd['senha'])
83         user.is_active = False
84         user.save()
85         user.groups.add(group)
86
87         p = Palestrante()
88         p.usuario = user
89
90         p.nome = cd['nome_completo']
91         p.email = cd['email']
92         p.telefone = cd['telefone']
93         p.celular = cd['celular']
94         p.instituicao = cd['instituicao']
95         p.rua = cd['rua']
96         p.numero = cd['numero']
97         p.bairro = cd['bairro']
98         p.cidade = cd['cidade']
99         p.uf = cd['uf']
100         p.minicurriculo = cd['minicurriculo']
101         p.curriculo = cd['curriculo']
102         p.save()
103
104         for i in cd.get('area_interesse', []):
105             p.area_interesse.add(i)
106
107         pid = p.id
108         md5_email = sha.new(cd['email']).hexdigest()
109         email = '%s <%s>' % (cd['nome_completo'], cd['email'])
110         link = '%s/verificar?c=%s&c1=%s' % (get_host(request),
111                 pid, md5_email)
112         t = loader.get_template('email-palestrante.html')
113         ec = Context(dict(fulano=['nome_usuario'], link=link))
114
115         # to be shown in template...
116         c.update({'email': email})
117         try:
118             # XXX: maybe is not a good so prety put things hardcoded =(
119             m = EmailMessage('Encontro Mineiro de Software Livre',
120                 t.render(ec), FROM_EMAIL, [email])
121             m.send()
122         except Exception:
123             badattr['email'] = \
124                 ['Desculpe mas não pude enviar o email de confirmação']
125             transaction.rollback()
126         else:
127             ok = True
128             c.update({'ok': ok})
129             transaction.commit()
130
131     return build_response(request, 'cadastro.html', c)
132
133
134 @enable_login_form
135 def inscricao(request):
136     return build_response(request, 'inscricao.html')
137
138
139 @enable_login_form
140 @transaction.commit_manually
141 def inscricao_individual(request):
142     form = Inscricao(request.POST or None)
143     ok = False
144     if request.POST and form.is_valid():
145         cd = form.cleaned_data
146
147         group = Group.objects.get_or_create(name='participantes')[0]
148
149         user = User(username=cd['nome_usuario'], email=cd['email'])
150         user.set_password(cd['senha'])
151         user.is_active = False
152         user.save()
153         user.groups.add(group)
154
155         p = Participante()
156         p.usuario = user
157         p.nome = cd['nome_completo']
158         p.rg = cd['rg']
159         p.email = cd['email']
160         p.rua = cd['rua']
161         p.numero = cd['numero']
162         p.bairro = cd['bairro']
163         p.cidade = cd['cidade']
164         p.uf = cd['uf']
165         p.telefone = cd['telefone']
166         p.home_page = cd['home_page']
167         p.save()
168
169         u = authenticate(username=cd['nome_usuario'], password=cd['senha'])
170         login(request, u)
171         transaction.commit()
172         ok = True
173
174     c = {'form': form, 'ok': ok}
175     return build_response(request, 'inscricao_individual.html', c)
176
177
178 @enable_login_form
179 @transaction.commit_manually
180 def inscricao_caravana(request):
181     form = InscricaoCaravana(request.POST or None)
182     ok = False
183     if request.POST and form.is_valid():
184         cd = form.cleaned_data
185         group = Group.objects.get_or_create(name='participantes')[0]
186
187         user = User(username=cd['nome_usuario'], email=cd['email'])
188         user.set_password(cd['senha'])
189         user.is_active = False
190         user.save()
191         user.groups.add(group)
192
193         p = Participante()
194         p.usuario = user
195         p.nome = cd['nome_completo']
196         p.rg = cd['rg']
197         p.email = cd['email']
198         p.rua = cd['rua']
199         p.numero = cd['numero']
200         p.bairro = cd['bairro']
201         p.cidade = cd['cidade']
202         p.uf = cd['uf']
203         p.telefone = cd['telefone']
204         p.home_page = cd['home_page']
205         p.save()
206
207         c = Caravana()
208         c.coordenador = p
209         c.participantes = cd['lista_nomes']
210         c.save()
211
212         ok = True
213         u = authenticate(username=cd['nome_usuario'], password=cd['senha'])
214         login(request, u)
215         transaction.commit()
216
217     c = {'form': form, 'ok': ok}
218     return build_response(request, 'inscricao_caravana.html', c)
219
220
221 @login_required
222 @user_passes_test(lambda u:u.palestrante_set.count() == 1, login_url='/')
223 def submeter_trabalho(request):
224     form = SubmeterTrabalho(request, request.POST or None)
225     ok = False
226
227     if request.POST and form.is_valid():
228         cd = form.cleaned_data
229         t = Trabalho()
230         t.titulo = cd['titulo']
231         t.tipo = TipoTrabalho.objects.get(pk=cd['tipo'])
232         t.categoria = CategoriaTrabalho.objects.get_or_create(nome='Pendente')[0]
233         t.descricao_curta = cd['descricao_curta']
234         t.descricao_longa = cd['descricao_longa']
235         t.recursos = cd['recursos']
236         t.evento = Evento.objects.get(pk=1) # XXX: let the hammer play arround!
237         t.save()
238
239         logged_in = request.user.palestrante_set.get()
240         t.palestrante.add(logged_in)
241         for i in cd.get('outros_palestrantes', []):
242             up = Palestrante.objects.get(pk=int(i))
243             t.palestrante.add(up)
244         ok = True
245
246     c = {'form': form, 'ok': ok}
247     return build_response(request, 'inscrever_palestra.html', c)
248
249
250 @login_required
251 @user_passes_test(lambda u:u.palestrante_set.count() == 1, login_url='/')
252 def meus_trabalhos(request):
253     try:
254         p = Palestrante.objects.get(usuario=request.user)
255     except Palestrante.DoesNotExist:
256         # não palestrante...
257         c = {'palestrante': 0}
258         return build_response(request, 'meus_trabalhos.html', c)
259
260     t = Trabalho.objects.filter(palestrante=p)
261     c = {'trabalhos': t, 'palestrante': 1}
262     return build_response(request, 'meus_trabalhos.html', c)
263
264
265 @login_required
266 @user_passes_test(lambda u:u.palestrante_set.count() == 1, login_url='/')
267 def editar_trabalho(request, codigo):
268     try:
269         p = Palestrante.objects.get(usuario=request.user)
270     except Palestrante.DoesNotExist:
271         # não palestrante...
272         c = {'palestrante': 0}
273         return build_response(request, 'meus_trabalhos.html', c)
274
275     trabalho = get_object_or_404(Trabalho, id=codigo, palestrante=p)
276     Formulario = form_for_instance(trabalho)
277
278     form = Formulario(request.POST or None)
279     if request.POST and form.is_valid():
280         form.save()
281         t = Trabalho.objects.filter(palestrante=p)
282         c = {'trabalhos': t, 'palestrante': 1}
283         c['editado_sucesso'] = trabalho.titulo
284         return build_response(request, 'meus_trabalhos.html', c)
285     
286     c = {'formulario': form}
287     return build_response(request, 'editar_trabalho.html', c)
288
289
290 @login_required
291 def meus_dados(request):
292     form = EditarPalestrante(request.POST or None)
293     palestrante = request.user.palestrante_set.get()
294     ok = False
295
296     for name, field in form.fields.items():
297         field.initial = getattr(palestrante, name)
298
299     if request.POST and form.is_valid():
300         cd = form.cleaned_data
301         for name, field in form.fields.items():
302             setattr(palestrante, name, cd[name])
303         palestrante.save()
304         ok = True
305
306     c = {'form': form, 'ok': ok}
307     return build_response(request, 'editar_palestrante.html', c)
308
309
310 @enable_login_form
311 def chamada_trabalhos(request):
312     return build_response(request, 'chamada_trabalhos.html')
313
314 @enable_login_form
315 def avaliacao(request):
316     return build_response(request, 'avaliacao.html')