-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate_admin_fixed.py
More file actions
240 lines (205 loc) Β· 7.49 KB
/
create_admin_fixed.py
File metadata and controls
240 lines (205 loc) Β· 7.49 KB
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
"""
Fixed script to create a new admin user
This script fixes the admin_id null issue and email validation
"""
import os
import sys
import logging
from pathlib import Path
import getpass
# Add the project root to the Python path
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
try:
from app.db.base import SessionLocal
from app.db.admin_models import Admin, AdminRole
from app.schemas.admin import AdminCreate
from app.core.security import get_password_hash
from sqlalchemy import or_
import uuid
except ImportError as e:
print(f"β Import error: {e}")
print("Make sure you're running this from the project root directory")
sys.exit(1)
def get_admin_input():
"""Get admin details from user input"""
print("π§ Create New Admin Account")
print("=" * 30)
# Get admin details
admin_username = input("Enter admin username: ").strip()
if not admin_username:
print("β Username cannot be empty!")
return None
# Get email with validation
while True:
admin_email = input("Enter admin email (use a real email format like admin@gmail.com): ").strip()
if not admin_email:
print("β Email cannot be empty!")
continue
if "@" not in admin_email or "." not in admin_email.split("@")[1]:
print("β Please enter a valid email address!")
continue
if admin_email.endswith(".local"):
print("β .local domain is not allowed. Use a real domain like .com, .org, etc.")
continue
break
full_name = input("Enter full name: ").strip()
if not full_name:
print("β Full name cannot be empty!")
return None
# Get password
while True:
password = getpass.getpass("Enter password: ")
if len(password) < 6:
print("β Password must be at least 6 characters long!")
continue
confirm_password = getpass.getpass("Confirm password: ")
if password != confirm_password:
print("β Passwords do not match!")
continue
break
# Get role
print("\nAvailable roles:")
print("1. SUPER_ADMIN (all permissions)")
print("2. ADMIN (most permissions)")
print("3. MODERATOR (basic permissions)")
while True:
role_choice = input("Enter role choice (1-3): ").strip()
if role_choice == "1":
role = AdminRole.SUPER_ADMIN
break
elif role_choice == "2":
role = AdminRole.ADMIN
break
elif role_choice == "3":
role = AdminRole.MODERATOR
break
else:
print("β Please enter 1, 2, or 3!")
return {
"admin_username": admin_username,
"admin_email": admin_email,
"full_name": full_name,
"password": password,
"role": role
}
def check_existing_admin(db, username, email):
"""Check if admin with username or email already exists"""
existing_admin = db.query(Admin).filter(
or_(
Admin.admin_username == username,
Admin.admin_email == email
)
).first()
return existing_admin
def create_admin_direct(admin_data):
"""Create admin directly without using the service to avoid logging issues"""
try:
db = SessionLocal()
# Check if admin already exists
existing = check_existing_admin(db, admin_data["admin_username"], admin_data["admin_email"])
if existing:
logger.error(f"β Admin with username '{admin_data['admin_username']}' or email '{admin_data['admin_email']}' already exists!")
return False
# Create admin directly
hashed_password = get_password_hash(admin_data["password"])
admin = Admin(
id=str(uuid.uuid4()),
admin_username=admin_data["admin_username"],
admin_email=admin_data["admin_email"],
full_name=admin_data["full_name"],
hashed_password=hashed_password,
role=admin_data["role"],
is_super_admin=(admin_data["role"] == AdminRole.SUPER_ADMIN)
)
db.add(admin)
db.commit()
db.refresh(admin)
logger.info("β
Admin created successfully!")
logger.info("=" * 40)
logger.info(f"Username: {admin.admin_username}")
logger.info(f"Email: {admin.admin_email}")
logger.info(f"Full Name: {admin.full_name}")
logger.info(f"Role: {admin.role.value}")
logger.info(f"Super Admin: {admin.is_super_admin}")
logger.info("=" * 40)
logger.info("You can now login at: http://localhost:8001/admin/login")
return True
except Exception as e:
logger.error(f"β Error creating admin: {e}")
if 'db' in locals():
db.rollback()
return False
finally:
if 'db' in locals():
db.close()
def create_default_super_admin():
"""Create a default super admin with valid email"""
admin_data = {
"admin_username": "superadmin",
"admin_email": "admin@example.com", # Use a valid email format
"full_name": "Super Administrator",
"password": "admin123",
"role": AdminRole.SUPER_ADMIN
}
logger.info("π§ Creating default super admin...")
return create_admin_direct(admin_data)
def list_existing_admins():
"""List all existing admins"""
try:
db = SessionLocal()
admins = db.query(Admin).all()
if not admins:
logger.info("π No admins found in the database")
return
logger.info("π Existing admins:")
logger.info("-" * 80)
for admin in admins:
status = "Active" if admin.is_active else "Inactive"
super_admin = "Yes" if admin.is_super_admin else "No"
logger.info(f"Username: {admin.admin_username:<15} | Email: {admin.admin_email:<25} | Role: {admin.role.value:<12} | Super: {super_admin:<3} | Status: {status}")
logger.info("-" * 80)
except Exception as e:
logger.error(f"β Error listing admins: {e}")
finally:
if 'db' in locals():
db.close()
def main():
"""Main function"""
logger.info("π Admin Management Script (Fixed)")
logger.info("=" * 50)
# List existing admins first
list_existing_admins()
print("\nOptions:")
print("1. Create a new admin (interactive)")
print("2. Create default super admin (admin@example.com)")
print("3. Exit")
while True:
choice = input("\nEnter your choice (1-3): ").strip()
if choice == "1":
admin_data = get_admin_input()
if admin_data:
success = create_admin_direct(admin_data)
if success:
break
elif choice == "2":
success = create_default_super_admin()
if success:
break
elif choice == "3":
logger.info("π Goodbye!")
break
else:
print("β Please enter 1, 2, or 3!")
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
logger.info("\nβ οΈ Script interrupted by user")
sys.exit(1)
except Exception as e:
logger.error(f"\nβ Unexpected error: {e}")
sys.exit(1)