User service module with various tech debt examples
from typing import Dict, List, Any, Optional
# TODO: Move this to configuration file
DATABASE_URL = "postgresql://user:password123@localhost:5432/mydb"
API_KEY = "sk-1234567890abcdef" # FIXME: This should be in environment variables
# HACK: Using dict for now, should be proper database connection
self.db_connection = None
def create_user(self, name, email, password, age, phone, address, city, state, zip_code, country, preferences, notifications, billing_info):
# Function with too many parameters - should use User dataclass
# Duplicate validation logic - should be extracted
print("User must be at least 13 years old")
if not self.validate_email(email):
print("Invalid email format")
# Password validation - duplicated elsewhere
print("Password too short")
if not re.search(r"[A-Z]", password):
print("Password must contain uppercase letter")
if not re.search(r"[a-z]", password):
print("Password must contain lowercase letter")
if not re.search(r"\d", password):
print("Password must contain digit")
if 'notifications' in preferences:
if preferences['notifications']:
if 'email' in preferences['notifications']:
if preferences['notifications']['email']:
if 'frequency' in preferences['notifications']['email']:
if preferences['notifications']['email']['frequency'] == 'daily':
print("Daily email notifications enabled")
elif preferences['notifications']['email']['frequency'] == 'weekly':
print("Weekly email notifications enabled")
print("Invalid notification frequency")
# TODO: Implement proper user ID generation
user_id = str(hash(email)) # XXX: This is terrible for production
# Magic numbers everywhere
password_hash = hashlib.sha256((password + "salt123").encode()).hexdigest()
"password_hash": password_hash,
"preferences": preferences,
"notifications": notifications,
"billing_info": billing_info,
"created_at": time.time(),
"updated_at": time.time(),
"verification_token": None,
"failed_login_attempts": 0,
"subscription_level": "free",
self.users[user_id] = user_data
def validate_email(self, email):
# Duplicate validation logic - should be in utils
def authenticate_user(self, email, password):
# More duplicate validation
# Linear search through users - O(n) complexity
for user_id, user_data in self.users.items():
if user_data["email"] == email:
# Same password hashing logic duplicated
password_hash = hashlib.sha256((password + "salt123").encode()).hexdigest()
if user_data["password_hash"] == password_hash:
user_data["last_login"] = time.time()
user_data["login_count"] += 1
user_data["failed_login_attempts"] = 0
user_data["failed_login_attempts"] += 1
if user_data["failed_login_attempts"] >= 5: # Magic number
user_data["locked_until"] = time.time() + 1800 # 30 minutes
def get_user(self, user_id):
return self.users[user_id]
def update_user(self, user_id, updates):
# Empty catch block - bad practice
user = self.users[user_id]
# More validation duplication
print("User must be at least 13 years old")
if not self.validate_email(updates["email"]):
print("Invalid email format")
# Direct dictionary manipulation without validation
for key, value in updates.items():
user["updated_at"] = time.time()
def delete_user(self, user_id):
# print("Deleting user", user_id) # Commented out code
# TODO: Implement soft delete instead
def search_users(self, query):
# Inefficient search algorithm - O(n*m)
for user_id, user_data in self.users.items():
if query.lower() in user_data["name"].lower():
results.append(user_data)
elif query.lower() in user_data["email"].lower():
results.append(user_data)
elif query in user_data.get("phone", ""):
results.append(user_data)
# Security risk - no access control
return json.dumps(self.users, indent=2)
def import_users(self, json_data):
# No validation of imported data
imported_users = json.loads(json_data)
self.users.update(imported_users)
# def old_create_user(self, name, email):
# # Old implementation kept as comment
# return {"name": name, "email": email}
def calculate_user_score(self, user_id):
user = self.users[user_id]
# Complex scoring logic with magic numbers
if user["login_count"] > 10:
elif user["login_count"] > 5:
elif user["login_count"] > 1:
if user["subscription_level"] == "premium":
elif user["subscription_level"] == "pro":
elif user["subscription_level"] == "basic":
# Age-based scoring with arbitrary rules
if user["age"] >= 18 and user["age"] <= 65:
# Global variable - should be encapsulated
user_service_instance = UserService()
return user_service_instance
# Utility function that should be in separate module
def hash_password(password, salt="salt123"):
# Hardcoded salt - security issue
return hashlib.sha256((password + salt).encode()).hexdigest()
# Another utility function with duplicate logic
def validate_password(password):
return False, "Password too short"
if not re.search(r"[A-Z]", password):
return False, "Password must contain uppercase letter"
if not re.search(r"[a-z]", password):
return False, "Password must contain lowercase letter"
if not re.search(r"\d", password):
return False, "Password must contain digit"
return True, "Valid password"