conferindo senha
[cascardo/eventmanager.git] / views.py
1 # -*- coding: utf8; -*-
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
21 from django.template import RequestContext, Context
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.forms import AuthenticationForm
25 from django.contrib.auth import login
26 from django.db import transaction
27
28 from eventmanager.decorators import enable_login_form
29 from eventmanager.forms import *
30 from eventmanager.conteudo.models import Noticia, Menu, Secao
31 from eventmanager.eventos.models import *
32
33 def build_response(request, template, extra={}):
34     """
35     Shortcut to build a response based on a C{template} and build a standard
36     context to this template. This context contains news itens, a list of menus
37     and a list of sections to be shown on index. But don't worry, this context
38     is extensible through the C{extra} parameter.
39
40     @param template: Contains the name of a template found in django
41      C{TEMPLATE_DIRS}
42     @type template: C{str}
43
44     @param extra: Extra variables to be passed to the context being built.
45     @type extra: C{dict}
46     """
47     news = Noticia.objects.order_by('-data_criacao')
48     menus = Menu.objects.all()
49     index_sections = Secao.objects.filter(index=True)
50     c = {'news': news, 'menu': menus,
51         'index_sections': index_sections}
52     c.update(extra)
53     return render_to_response(template, Context(c),
54             context_instance=RequestContext(request))
55
56
57 @enable_login_form
58 def index(request):
59     return build_response(request, 'index.html')
60
61
62 @transaction.commit_manually
63 @enable_login_form
64 def cadastro_palestrante(request):
65     c = {}
66     if request.POST:
67         # django's newforms lib requires a new instance of a form to be bounded
68         # with data, to be validated and used.
69         form = CadastroPalestrante(request.POST)
70         if form.is_valid():
71             cd = form.cleaned_data
72             badattr = form.errors
73             wrong = False
74
75             if not cd['telefone'] and not cd['celular']:
76                 badattr['telefone_comercial'] = ['Algum número de telefone '
77                                                  'precisa ser informado']
78                 wrong = True
79
80             # don't save duplicated users...
81             try:
82                 User.objects.get(username=cd['nome_usuario'])
83                 badattr['nome_usuario'] = ['Este nome de usuário já existe!']
84                 wrong = True
85                 transaction.rollback()
86             except User.DoesNotExist:
87                 pass
88
89             if cd['senha'] != cd['senha_2']:
90                 badattr['senha_2'] = ['A senha não confere']
91                 wrong = True
92                 transaction.rollback()
93
94             if not wrong:
95                 group = Group.objects.get_or_create(name='palestrantes')[0]
96
97                 user = User(username=cd['nome_usuario'], email=cd['email'])
98                 user.set_password(cd['senha'])
99                 user.save()
100                 user.groups.add(group)
101
102                 p = Palestrante()
103                 p.usuario = user
104
105                 p.nome = cd['nome_completo']
106                 p.email = cd['email']
107                 p.telefone = cd['telefone']
108                 p.celular = cd['celular']
109                 p.rua = cd['rua']
110                 p.numero = cd['numero']
111                 p.bairro = cd['bairro']
112                 p.cidade = cd['cidade']
113                 p.uf = cd['uf']
114                 p.minicurriculo = cd['minicurriculo']
115                 p.save()
116
117                 for i in cd.get('area_interesse', []):
118                     p.area_interesse.add(i)
119
120                 c.update({'ok': 1})
121
122                 fakepost = request.POST.copy()
123                 fakepost['username'] = cd['nome_usuario']
124                 fakepost['password'] = cd['senha']
125
126                 manipulator = AuthenticationForm(request)
127                 errors = manipulator.get_validation_errors(fakepost)
128                 got_user = manipulator.get_user()
129                 login(request, got_user)
130                 transaction.commit()
131     else:
132         form = CadastroPalestrante()
133     c.update({'form': form})
134     return build_response(request, 'cadastro.html', c)
135
136
137 @enable_login_form
138 def inscricao(request):
139     if request.POST:
140         form = Inscricao(request.POST)
141     else:
142         form = Inscricao()
143     return build_response(request, 'inscricao.html', {'form': form})
144
145
146 @login_required
147 @user_passes_test(lambda u:u.palestrante_set.count() == 1, login_url='/')
148 def submeter_trabalho(request):
149     c = {}
150     if request.POST:
151         form = SubmeterTrabalho(request.POST)
152         if form.is_valid():
153             cd = form.cleaned_data
154             p = Trabalho()
155             p.titulo = cd['titulo']
156             p.tipo = TipoTrabalho.objects.get(pk=cd['tipo'])
157             p.categoria = CategoriaTrabalho.objects.get(pk=cd['categoria'])
158             p.descricao_curta = cd['descricao_curta']
159             p.descricao_longa = cd['descricao_longa']
160             p.recursos = cd['recursos']
161             p.evento = Evento.objects.get(pk=1) # let the hammer play arround!
162             p.save()
163
164             logged_in = request.user.palestrante_set.get()
165             p.palestrante.add(logged_in)
166             for i in cd.get('outros_palestrantes', []):
167                 up = Palestrante.objects.get(pk=int(i))
168                 p.palestrante.add(up)
169             c.update({'ok': 1})
170     else:
171         form = SubmeterTrabalho()
172     c.update({'form': form})
173     return build_response(request, 'inscrever_palestra.html', c)
174
175
176 @login_required
177 @user_passes_test(lambda u:u.palestrante_set.count() == 1, login_url='/')
178 def meus_trabalhos(request):
179     try:
180         p = Palestrante.objects.get(usuario=request.user)
181     except Palestrante.DoesNotExist:
182         # não palestrante...
183         c = {'palestrante': 0}
184         return build_response(request, 'meus_trabalhos.html', c)
185
186     t = Trabalho.objects.filter(palestrante=p)
187     c = {'trabalhos': t, 'palestrante': 1}
188     return build_response(request, 'meus_trabalhos.html', c)
189
190
191 @enable_login_form
192 def chamada_trabalhos(request):
193     return build_response(request, 'chamada_trabalhos.html')