-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate_admin.py
More file actions
59 lines (45 loc) · 1.69 KB
/
create_admin.py
File metadata and controls
59 lines (45 loc) · 1.69 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
import asyncio
import getpass
import secrets
import hashlib
import bcrypt
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker
from app.database.models import User
from app.config import get_config
from app.database.connection import get_database_url
async def create_admin():
"""Create an admin user."""
print("Creating admin user...")
# Get config and database URL
config = get_config()
database_url = get_database_url(config)
# Create async engine
engine = create_async_engine(database_url)
async_session = sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
# Get admin credentials
email = input("Admin email: ")
name = input("Admin name: ")
password = getpass.getpass("Admin password: ")
# Hash password
hashed_password = bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode()
# Create user
async with async_session() as session:
async with session.begin():
# Check if admin already exists
from sqlalchemy import select
query = select(User).where(User.email == email)
result = await session.execute(query)
existing_user = result.scalar_one_or_none()
if existing_user:
print(f"User with email {email} already exists.")
return
# Create new admin user
user = User(
email=email, name=name, password_hash=hashed_password, role="admin"
)
session.add(user)
await session.commit()
print(f"Admin user {email} created successfully!")
if __name__ == "__main__":
asyncio.run(create_admin())