feat(user): adds registration logic and validation

This commit is contained in:
2024-11-16 23:26:35 -03:00
parent 7541548acf
commit be03c55e89
4 changed files with 112 additions and 2 deletions

View File

@@ -0,0 +1,39 @@
from werkzeug.datastructures import ImmutableMultiDict
from flask import flash
from app.models.user import User
from app.extensions import db
from app.utils.alert_type import AlertType
from app.utils.errors.users.user_register_errors import UserRegisterErrors
from app.utils.flash_message import FlashMessage
from app.utils.validators import UserValidators
class UserService:
@staticmethod
def register_user(form: ImmutableMultiDict):
try:
name: str = UserValidators.is_valid_user_name(form.get("name"))
lastname: str = UserValidators.is_valid_user_name(form.get("lastname"),True)
birth_date = UserValidators.is_valid_birth_date(form.get("birthdate"))
phone_number: str = UserValidators.is_valid_phone_number(form.get("phonenumber"))
email: str = UserValidators.is_valid_email(form.get("email"))
password: str = form.get("password")
password_confirmation: str = form.get("password_confirmation")
address: str = UserValidators.is_valid_address(form.get("address"))
new_user = User(
username="test",
name=name,
lastname=lastname,
email=email,
password=UserValidators.passwords_match(password, password_confirmation),
birth_date= birth_date,
address=address,
phone_number=phone_number
)
db.session.add(new_user)
db.session.commit()
db.session.flush()
except UserRegisterErrors as e:
flash(FlashMessage(e.message, AlertType.DANGER.value ))
db.session.rollback()

View File

@@ -1,4 +1,5 @@
from flask import render_template
from flask import request, render_template
from app.services.user_service import UserService
from app.users import bp
from app.utils.form_errors_dict import FORM_ERRORS
@bp.route('/')
@@ -9,6 +10,8 @@ def index():
def login():
return render_template("users/login.html")
@bp.route('/register')
@bp.route('/register', methods=["GET", "POST"])
def register():
if request.method == 'POST':
UserService.register_user(request.form)
return render_template("users/register.html", FORM_ERRORS=FORM_ERRORS)

View File

@@ -0,0 +1,4 @@
class UserRegisterErrors(Exception):
def __init__(self, message):
self.message = message
super().__init__(self.message)

64
app/utils/validators.py Normal file
View File

@@ -0,0 +1,64 @@
from datetime import date
from typing import Optional
from app.utils.errors.users.user_register_errors import UserRegisterErrors
import re
class UserValidators:
@staticmethod
def is_valid_user_name(name: Optional[str], isLastname=False):
if(UserValidators.is_valid_str_and_pattern(name, '^[A-Za-z ]{2,255}$')):
return name
if(isLastname):
raise UserRegisterErrors("Invalid user lastname")
raise UserRegisterErrors("Invalid user name")
@staticmethod
def is_valid_birth_date(birth_date: Optional[str]):
if(UserValidators.is_valid_str_and_pattern(birth_date, '^\d{4}-\d{2}-\d{2}$')):
try:
birth_date = [int(n) for n in (str(birth_date)).split("-")]
return date(birth_date[0], birth_date[1], birth_date[2])
except:
raise UserRegisterErrors("Invalid user birthdate")
raise UserRegisterErrors("Invalid user birthdate")
@staticmethod
def is_valid_phone_number(phone_number: Optional[str]):
if(UserValidators.is_valid_str_and_pattern(phone_number, '^(\+\d{1,3}){0,1}[0-9]{7,255}$')):
return phone_number
raise UserRegisterErrors("Invalid user phone number")
@staticmethod
def is_valid_email(email: Optional[str]):
if(UserValidators.is_valid_str_and_pattern(email, '^[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$')):
if(len(email) <= 255):
return email
raise UserRegisterErrors("Invalid user email")
@staticmethod
def is_valid_address(address: Optional[str]):
if(isinstance(address, str) and len(address) <= 255):
return address
raise UserRegisterErrors("Invalid user address")
@staticmethod
def is_valid_str_and_pattern(string: Optional[str], pattern: str):
if(isinstance(string, str)):
regex = re.compile(pattern)
if(regex.match(string) is not None):
return True
return False
@staticmethod
def is_valid_password(password: str):
if(isinstance(password, str)):
password_len = len(password)
if(password_len >= 6 and password_len <= 255):
return password
raise UserRegisterErrors("Invalid user password")
@staticmethod
def passwords_match(password: str, password_confirmation: str):
if(UserValidators.is_valid_password(password) == UserValidators.is_valid_password(password_confirmation)):
return password
raise UserRegisterErrors("User password and password confirmation don't match")