hotspot / App /Mikrotik /utils /helperfx.py
Mbonea's picture
vpn ready?
afbb33a
raw
history blame
1.97 kB
from .api import MikrotikAPI
from .Config import RouterConfig
from fastapi import HTTPException
import re
from typing import Tuple
class PhoneValidator:
"""Validator for Tanzanian phone numbers"""
# Valid Tanzanian mobile operator prefixes
VALID_PREFIXES = [
"071",
"074",
"075",
"076",
"077", # Vodacom
"068",
"069", # Airtel
"065",
"067", # Tigo
"078",
"079", # TTCL
"073", # Zantel
"061",
"062", # Halotel
]
@staticmethod
def validate_and_format(phone: str) -> Tuple[bool, str]:
"""
Validates and formats Tanzanian phone numbers.
Returns (is_valid, formatted_number)
Valid format:
- 255712345678 (12 digits starting with 255)
"""
# Remove any spaces or special characters
phone = re.sub(r"[\s\-\(\)]", "", phone)
# Convert all formats to 255 format
if phone.startswith("+255"):
phone = "255" + phone[4:]
elif phone.startswith("0"):
phone = "255" + phone[1:]
elif not phone.startswith("255"):
return False, ""
# Check if it matches the basic pattern (12 digits starting with 255)
if not re.match(r"^255\d{9}$", phone):
return False, ""
# Check if the prefix is valid (check the digits after 255)
prefix = "0" + phone[3:5]
if prefix not in PhoneValidator.VALID_PREFIXES:
return False, ""
return True, phone
# Dependency to get MikrotikAPI instance
def get_mikrotik():
config = RouterConfig()
mikrotik = MikrotikAPI(config)
try:
if mikrotik.connect():
yield mikrotik
else:
raise HTTPException(
status_code=503,
detail={"success": False, "message": "Could not connect to router"},
)
finally:
mikrotik.close()