Coverage for website/views/SignUpView.py: 79%
53 statements
« prev ^ index » next coverage.py v7.5.0, created at 2025-09-13 15:29 -0300
« prev ^ index » next coverage.py v7.5.0, created at 2025-09-13 15:29 -0300
1import unicodedata
3from django.contrib import messages
4from django.contrib.auth.password_validation import validate_password
5from django.core.exceptions import ValidationError
6from django.shortcuts import redirect, render
8from website.forms import UserCreationForm
9from website.models import Author, Reader, User
12def sign_up_user(request):
13 user_form = UserCreationForm()
14 if request.POST:
15 user_form = UserCreationForm(request.POST)
16 cont = len(User.objects.all()) + 1
18 request_name = treat_accentuation(request.POST.get("nome", None))
20 treated_username = request_name.split(" ")[0].lower() + f"-user{cont}"
22 password1 = request.POST.get("password1", None)
23 password2 = request.POST.get("password2", None)
24 is_staff = True if request.POST.get("tipo-user") == "author" else False
26 # Use Django's validate_password to run the configured validators
27 try:
28 validate_password(password2)
29 password_ok = True
30 except ValidationError:
31 password_ok = False
33 # require passwords to match and pass Django validators
34 if password_ok and (password1 == password2):
35 user = User.objects.create_user(
36 username=treated_username,
37 email=request.POST.get("email", None),
38 phone_number=request.POST.get("phone", None),
39 password=request.POST.get("password2", None),
40 is_staff=is_staff,
41 )
43 if user.is_staff:
44 create_author(request, user)
45 else:
46 create_reader(request, user)
47 messages.success(
48 request, f"O usuário {user.username} foi registrado com sucesso."
49 )
50 return redirect("login")
51 else:
52 messages.error(
53 request, "A senha digitada não confere ou não satisfaz as regras."
54 )
56 context = {
57 "form": user_form,
58 }
59 return render(
60 request, template_name="sign-up/sign-up.html", context=context, status=200
61 )
64def create_author(request, user):
65 author_name = request.POST.get("nome", None)
66 author_name_replaced = treat_accentuation(author_name)
68 slug = str()
69 for n in author_name_replaced.split(" "):
70 if n == author_name_replaced.split(" ")[-1]:
71 slug += n.lower()
72 else:
73 slug += f"{n.lower()}-"
75 author = Author(
76 user=user,
77 author_name=author_name,
78 author_url_slug=slug,
79 access_level=1,
80 )
81 author.save()
82 return author
85def create_reader(request, user):
86 reader_name = request.POST.get("nome", None)
87 reader = Reader(
88 user=user,
89 reader_name=reader_name,
90 access_level=2,
91 )
92 reader.save()
93 return reader
96def treat_accentuation(request_name):
97 replace_accentuation = unicodedata.normalize("NFD", request_name)
98 replace_accentuation = replace_accentuation.encode("ascii", "ignore")
99 author_name_replaced = replace_accentuation.decode("utf-8")
100 return author_name_replaced