Creative_Breakthrough / create_user.py
sushilideaclan01's picture
Initial commit of the Ad Generator Lite project, including backend services, frontend components, and configuration files. Added core functionalities for ad generation, user management, and image processing, along with a structured matrix system for ad testing.
f201243
#!/usr/bin/env python3
"""
CLI script to create users manually.
This script is for backend-only user creation (not exposed in frontend).
Usage:
python create_user.py <username> <password>
Example:
python create_user.py admin mypassword123
"""
import asyncio
import sys
import os
# Add current directory to path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from services.database import db_service
from services.auth import auth_service
async def create_user(username: str, password: str):
"""Create a new user."""
# Connect to database
print("Connecting to database...")
connected = await db_service.connect()
if not connected:
print("❌ Failed to connect to database. Please check your MONGODB_URL configuration.")
return False
try:
# Check if user already exists
existing_user = await db_service.get_user(username)
if existing_user:
print(f"❌ User '{username}' already exists!")
return False
# Hash password
print(f"Creating user '{username}'...")
hashed_password = auth_service.hash_password(password)
# Create user
user_id = await db_service.create_user(username, hashed_password)
if user_id:
print(f"βœ… User '{username}' created successfully!")
print(f" User ID: {user_id}")
print(f"\nYou can now login with:")
print(f" Username: {username}")
print(f" Password: {password}")
return True
else:
print(f"❌ Failed to create user '{username}'")
return False
except Exception as e:
print(f"❌ Error creating user: {e}")
return False
finally:
await db_service.disconnect()
async def list_users():
"""List all users."""
print("Connecting to database...")
connected = await db_service.connect()
if not connected:
print("❌ Failed to connect to database. Please check your MONGODB_URL configuration.")
return
try:
users = await db_service.list_users()
if not users:
print("No users found.")
else:
print(f"\nFound {len(users)} user(s):\n")
for user in users:
print(f" - {user['username']}")
print(f" Created: {user.get('created_at', 'N/A')}")
print()
except Exception as e:
print(f"❌ Error listing users: {e}")
finally:
await db_service.disconnect()
async def delete_user(username: str):
"""Delete a user."""
print("Connecting to database...")
connected = await db_service.connect()
if not connected:
print("❌ Failed to connect to database. Please check your MONGODB_URL configuration.")
return False
try:
# Confirm deletion
confirm = input(f"Are you sure you want to delete user '{username}'? (yes/no): ")
if confirm.lower() != "yes":
print("Cancelled.")
return False
deleted = await db_service.delete_user(username)
if deleted:
print(f"βœ… User '{username}' deleted successfully!")
return True
else:
print(f"❌ User '{username}' not found or could not be deleted.")
return False
except Exception as e:
print(f"❌ Error deleting user: {e}")
return False
finally:
await db_service.disconnect()
def print_usage():
"""Print usage instructions."""
print("""
User Management Script
Usage:
python create_user.py create <username> <password> - Create a new user
python create_user.py list - List all users
python create_user.py delete <username> - Delete a user
Examples:
python create_user.py create admin mypassword123
python create_user.py list
python create_user.py delete admin
""")
async def main():
"""Main entry point."""
if len(sys.argv) < 2:
print_usage()
return
command = sys.argv[1].lower()
if command == "create":
if len(sys.argv) != 4:
print("❌ Error: Username and password required")
print("Usage: python create_user.py create <username> <password>")
return
username = sys.argv[2]
password = sys.argv[3]
if len(username) < 3:
print("❌ Error: Username must be at least 3 characters")
return
if len(password) < 6:
print("❌ Error: Password must be at least 6 characters")
return
await create_user(username, password)
elif command == "list":
await list_users()
elif command == "delete":
if len(sys.argv) != 3:
print("❌ Error: Username required")
print("Usage: python create_user.py delete <username>")
return
username = sys.argv[2]
await delete_user(username)
else:
print(f"❌ Unknown command: {command}")
print_usage()
if __name__ == "__main__":
asyncio.run(main())