Jelajahi Sumber

validate rut

latapp 9 bulan lalu
induk
melakukan
3c631cf810
3 mengubah file dengan 45 tambahan dan 0 penghapusan
  1. 1 0
      config/messages.py
  2. 3 0
      routes/users.py
  3. 41 0
      utils/rut.py

+ 1 - 0
config/messages.py

@@ -12,6 +12,7 @@ class ErrorResponse:
     INVALID_PIN = "El PIN es inválido."
     INVALID_VERIFICATION_CODE = "El código de verificación es inválido."
     PRODDUCT_NOT_FOUND = "Producto con ID '{product_id}' no encontrado."
+    INVALID_RUT = "El RUT proporcionado es inválido. Por favor, verifique el formato y los dígitos."
 
 class SuccessResponse:
     """Class to handle success messages in the response."""

+ 3 - 0
routes/users.py

@@ -21,6 +21,7 @@ from services.email_service import send_email
 from config.mails import REGISTER_MAIL
 from config.settings import APPNAME
 from config.messages import ErrorResponse, SuccessResponse, UserResponse
+from utils.rut import validate_rut
 fernet = Fernet(PIN_KEY.encode())
 logger = getLogger(__name__)
 user_data_service = UserDataService()
@@ -46,6 +47,8 @@ async def exists_user(request: UserIDRequest):
 @user_router.post("/register")
 async def register_user(request: RegisterUserRequest):
     """Register a new user"""
+    if not validate_rut(request.rut):
+        return JSONResponse(status_code=400, content={"message": ErrorResponse.INVALID_RUT})
     user = user_data_service.get_by_email(request.email)
     if user:
         return JSONResponse(status_code=400, content={"message": UserResponse.USER_ALREADY_EXISTS})

+ 41 - 0
utils/rut.py

@@ -0,0 +1,41 @@
+def validate_rut(rut):
+    """
+    Validates a Chilean RUT (Rol Único Tributario).
+    
+    Args:
+        rut (str): The RUT to validate, formatted as '12345678-9'.
+    
+    Returns:
+        bool: True if the RUT is valid, False otherwise.
+    """
+    if not rut or '-' not in rut:
+        return False
+    
+    try:
+        body, dv = rut.split('-')
+        body = int(body)
+        dv = dv.upper()
+    except ValueError:
+        return False
+    
+    if len(str(body)) < 7 or len(str(body)) > 8:
+        return False
+    
+    # Calculate the expected DV
+    total = 0
+    factor = 2
+    for digit in reversed(str(body)):
+        total += int(digit) * factor
+        factor = factor + 1 if factor < 7 else 2
+    
+    expected_dv = str((11 - (total % 11)) % 11)
+    if expected_dv == '10':
+        expected_dv = 'K'
+    
+    return dv == expected_dv
+
+if __name__ == "__main__":
+    # Example usage
+    print(validate_rut("1234567-10"))  # Should return False, invalid
+    print(validate_rut("21382334-5"))  # Should return True, validity
+    print(validate_rut("21975985-1"))  # Should return True, validity