Browse Source

Faz a criacao do usuario Autor por meio das tabelas auxiliares

pull/508/head
Eduardo Calil 9 years ago
parent
commit
365f4cc641
  1. 9
      sapl/base/templatetags/common_tags.py
  2. 2
      sapl/base/urls.py
  3. 15
      sapl/materia/forms.py
  4. 4
      sapl/materia/urls.py
  5. 44
      sapl/materia/views.py
  6. 1
      sapl/settings.py
  7. 7
      sapl/templates/confirma_email.html

9
sapl/base/templatetags/common_tags.py

@ -48,7 +48,10 @@ def get_add_perm(value, arg):
perm = value perm = value
view = arg view = arg
try:
nome_app = view.__class__.model._meta.app_label nome_app = view.__class__.model._meta.app_label
except AttributeError:
return None
nome_model = view.__class__.model.__name__.lower() nome_model = view.__class__.model.__name__.lower()
can_add = '.add_' + nome_model can_add = '.add_' + nome_model
@ -60,7 +63,10 @@ def get_change_perm(value, arg):
perm = value perm = value
view = arg view = arg
try:
nome_app = view.__class__.model._meta.app_label nome_app = view.__class__.model._meta.app_label
except AttributeError:
return None
nome_model = view.__class__.model.__name__.lower() nome_model = view.__class__.model.__name__.lower()
can_change = '.change_' + nome_model can_change = '.change_' + nome_model
@ -72,7 +78,10 @@ def get_delete_perm(value, arg):
perm = value perm = value
view = arg view = arg
try:
nome_app = view.__class__.model._meta.app_label nome_app = view.__class__.model._meta.app_label
except AttributeError:
return None
nome_model = view.__class__.model.__name__.lower() nome_model = view.__class__.model.__name__.lower()
can_delete = '.delete_' + nome_model can_delete = '.delete_' + nome_model

2
sapl/base/urls.py

@ -21,7 +21,7 @@ urlpatterns = [
url(r'^login/$', views.login, { url(r'^login/$', views.login, {
'template_name': 'base/login.html', 'authentication_form': LoginForm}, 'template_name': 'base/login.html', 'authentication_form': LoginForm},
name='login'), name='login'),
url(r'^logout/$', views.logout, {'next_page': '/login'}, name='logout') url(r'^logout/$', views.logout, {'next_page': '/login'}, name='logout'),
] ]
# Fix a static asset finding error on Django 1.9 + gunicorn: # Fix a static asset finding error on Django 1.9 + gunicorn:

15
sapl/materia/forms.py

@ -4,7 +4,7 @@ import django_filters
from crispy_forms.helper import FormHelper from crispy_forms.helper import FormHelper
from crispy_forms.layout import HTML, Button, Column, Fieldset, Layout from crispy_forms.layout import HTML, Button, Column, Fieldset, Layout
from django import forms from django import forms
from django.contrib.auth.models import User from django.contrib.auth.models import Group, User
from django.contrib.auth.password_validation import validate_password from django.contrib.auth.password_validation import validate_password
from django.core.exceptions import ObjectDoesNotExist, ValidationError from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.db import models from django.db import models
@ -584,6 +584,10 @@ class AutorForm(ModelForm):
return User.objects.filter( return User.objects.filter(
email=self.cleaned_data['email']).exists() email=self.cleaned_data['email']).exists()
def usuario_existente(self):
return User.objects.filter(
username=self.cleaned_data['username']).exists()
def clean(self): def clean(self):
if ('senha' not in self.cleaned_data or if ('senha' not in self.cleaned_data or
'senha_confirma' not in self.cleaned_data): 'senha_confirma' not in self.cleaned_data):
@ -608,7 +612,11 @@ class AutorForm(ModelForm):
email_existente = self.valida_email_existente() email_existente = self.valida_email_existente()
if email_existente: if email_existente:
msg = _('Esse email já foi cadastrado.') msg = _('Este email já foi cadastrado.')
raise ValidationError(msg)
if self.usuario_existente():
msg = _('Este nome de usuario já foi cadastrado.')
raise ValidationError(msg) raise ValidationError(msg)
try: try:
@ -635,4 +643,7 @@ class AutorForm(ModelForm):
autor.save() autor.save()
grupo = Group.objects.filter(name='Autor')[0]
u.groups.add(grupo)
return autor return autor

4
sapl/materia/urls.py

@ -4,6 +4,7 @@ from sapl.materia.views import (AcompanhamentoConfirmarView,
AcompanhamentoExcluirView, AcompanhamentoExcluirView,
AcompanhamentoMateriaView, AnexadaCrud, AcompanhamentoMateriaView, AnexadaCrud,
AutorCrud, AutoriaCrud, DespachoInicialCrud, AutorCrud, AutoriaCrud, DespachoInicialCrud,
ConfirmarEmailView,
DocumentoAcessorioCrud, LegislacaoCitadaCrud, DocumentoAcessorioCrud, LegislacaoCitadaCrud,
MateriaLegislativaCrud, MateriaLegislativaCrud,
MateriaLegislativaPesquisaView, MateriaTaView, MateriaLegislativaPesquisaView, MateriaTaView,
@ -30,6 +31,9 @@ urlpatterns = [
RelatoriaCrud.get_urls() + RelatoriaCrud.get_urls() +
DocumentoAcessorioCrud.get_urls())), DocumentoAcessorioCrud.get_urls())),
url(r'^confirmar/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})$',
ConfirmarEmailView.as_view(), name='confirmar_email'),
url(r'^proposicao/', include(ProposicaoCrud.get_urls())), url(r'^proposicao/', include(ProposicaoCrud.get_urls())),
# Integração com Compilação # Integração com Compilação

44
sapl/materia/views.py

@ -4,13 +4,18 @@ from string import ascii_letters, digits
from crispy_forms.helper import FormHelper from crispy_forms.helper import FormHelper
from crispy_forms.layout import HTML, Button from crispy_forms.layout import HTML, Button
from django.conf import settings
from django.contrib import messages from django.contrib import messages
from django.contrib.auth.mixins import PermissionRequiredMixin from django.contrib.auth.mixins import PermissionRequiredMixin
from django.contrib.auth.tokens import default_token_generator
from django.contrib.auth.models import User
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
from django.core.exceptions import ObjectDoesNotExist from django.core.exceptions import ObjectDoesNotExist
from django.core.mail import send_mail from django.core.mail import send_mail
from django.core.urlresolvers import reverse from django.core.urlresolvers import reverse
from django.http.response import HttpResponseRedirect from django.http.response import HttpResponseRedirect
from django.template import Context, loader from django.template import Context, loader
from django.utils.encoding import force_bytes
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
from django.views.generic import CreateView, TemplateView, UpdateView from django.views.generic import CreateView, TemplateView, UpdateView
from django_filters.views import FilterView from django_filters.views import FilterView
@ -112,6 +117,45 @@ class AutorCrud(Crud):
form_class = AutorForm form_class = AutorForm
layout_key = 'AutorCreate' layout_key = 'AutorCreate'
def get_success_url(self):
pk_autor = Autor.objects.get(
email=self.request.POST.get('email')).id
kwargs = {}
user = User.objects.get(email=self.request.POST.get('email'))
kwargs['token'] = default_token_generator.make_token(user)
kwargs['uidb64'] = urlsafe_base64_encode(force_bytes(user.pk))
assunto = "SAPL - Confirmação de Conta"
full_url = self.request.get_raw_uri()
url_base = full_url[:full_url.find('sistema') - 1]
mensagem = ("Este e-mail foi utilizado para fazer cadastro no " +
"SAPL com o perfil de Autor. Agora você pode " +
"criar/editar/enviar Proposições.\n" +
"Seu nome de usuário é: " +
self.request.POST['username'] + "\n"
"Caso você não tenha feito este cadastro, por favor " +
"ignore esta mensagem. Caso tenha, clique " +
"no link abaixo\n" + url_base +
reverse('sapl.materia:confirmar_email', kwargs=kwargs))
remetente = settings.EMAIL_SEND_USER
destinatario = [self.request.POST.get('email')]
send_mail(assunto, mensagem, remetente, destinatario,
fail_silently=False)
return reverse('sapl.materia:autor_detail',
kwargs={'pk': pk_autor})
class ConfirmarEmailView(TemplateView):
template_name = "confirma_email.html"
def get(self, request, *args, **kwargs):
uid = urlsafe_base64_decode(self.kwargs['uidb64'])
user = User.objects.get(id=uid)
user.is_active = True
user.save()
context = self.get_context_data(**kwargs)
return self.render_to_response(context)
class OrgaoCrud(Crud): class OrgaoCrud(Crud):
model = Orgao model = Orgao

1
sapl/settings.py

@ -129,6 +129,7 @@ EMAIL_PORT = config('EMAIL_PORT', cast=int, default=587)
EMAIL_HOST_USER = config('EMAIL_HOST_USER', default='') EMAIL_HOST_USER = config('EMAIL_HOST_USER', default='')
EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD', default='') EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD', default='')
EMAIL_USE_TLS = config('EMAIL_USE_TLS', cast=bool, default=True) EMAIL_USE_TLS = config('EMAIL_USE_TLS', cast=bool, default=True)
EMAIL_SEND_USER = config('EMAIL_SEND_USER', cast=str, default='')
MAX_DOC_UPLOAD_SIZE = 5 * 1024 * 1024 # 5MB MAX_DOC_UPLOAD_SIZE = 5 * 1024 * 1024 # 5MB
MAX_IMAGE_UPLOAD_SIZE = 2 * 1024 * 1024 # 2MB MAX_IMAGE_UPLOAD_SIZE = 2 * 1024 * 1024 # 2MB

7
sapl/templates/confirma_email.html

@ -0,0 +1,7 @@
{% extends "crud/detail.html" %}
{% load i18n %}
{% block detail_content %}
Sua conta foi confirmada via e-mail. Clique <a href="{% url 'base:login' %}">aqui</a> para fazer seu login.
{% endblock %}
Loading…
Cancel
Save