File size: 5,267 Bytes
f201243
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
#!/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())