- Add Dockerfile and .dockerignore- Fix initial DB creation- Fix seed permission

This commit is contained in:
Koncept Kit
2026-01-26 20:06:22 +07:00
parent b29bb641f5
commit ea87b3f6ee
7 changed files with 402 additions and 92 deletions

View File

@@ -1,38 +1,15 @@
#!/usr/bin/env python3
"""
Create Superadmin User Script
Generates a superadmin user with hashed password for LOAF membership platform
Directly creates a superadmin user in the database for LOAF membership platform
"""
import bcrypt
import sys
import os
from getpass import getpass
def generate_password_hash(password: str) -> str:
"""Generate bcrypt hash for password"""
return bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode()
def generate_sql(email: str, password_hash: str, first_name: str, last_name: str) -> str:
"""Generate SQL INSERT statement"""
return f"""
-- Create Superadmin User
INSERT INTO users (
id, email, password_hash, first_name, last_name,
status, role, email_verified, created_at, updated_at
) VALUES (
gen_random_uuid(),
'{email}',
'{password_hash}',
'{first_name}',
'{last_name}',
'active',
'superadmin',
true,
NOW(),
NOW()
);
"""
# Add the backend directory to path for imports
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
def main():
print("=" * 70)
@@ -40,6 +17,15 @@ def main():
print("=" * 70)
print()
# Check for DATABASE_URL
from dotenv import load_dotenv
load_dotenv()
database_url = os.getenv("DATABASE_URL")
if not database_url:
print("❌ DATABASE_URL not found in environment or .env file")
sys.exit(1)
# Get user input
email = input("Email address: ").strip()
if not email or '@' not in email:
@@ -68,31 +54,89 @@ def main():
sys.exit(1)
print()
print("Generating password hash...")
password_hash = generate_password_hash(password)
print("Creating superadmin user...")
print("✅ Password hash generated")
print()
print("=" * 70)
print("SQL STATEMENT")
print("=" * 70)
try:
# Import database dependencies
from sqlalchemy import create_engine, text
from passlib.context import CryptContext
sql = generate_sql(email, password_hash, first_name, last_name)
print(sql)
# Create password hash
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
password_hash = pwd_context.hash(password)
# Save to file
output_file = "create_superadmin.sql"
with open(output_file, 'w') as f:
f.write(sql)
# Connect to database
engine = create_engine(database_url)
print("=" * 70)
print(f"✅ SQL saved to: {output_file}")
print()
print("Run this command to create the user:")
print(f" psql -U postgres -d loaf_new -f {output_file}")
print()
print("Or copy the SQL above and run it directly in psql")
print("=" * 70)
with engine.connect() as conn:
# Check if user already exists
result = conn.execute(
text("SELECT id FROM users WHERE email = :email"),
{"email": email}
)
if result.fetchone():
print(f"❌ User with email '{email}' already exists")
sys.exit(1)
# Insert superadmin user
conn.execute(
text("""
INSERT INTO users (
id, email, password_hash, first_name, last_name,
phone, address, city, state, zipcode, date_of_birth,
status, role, email_verified,
newsletter_subscribed, accepts_tos,
created_at, updated_at
) VALUES (
gen_random_uuid(),
:email,
:password_hash,
:first_name,
:last_name,
'',
'',
'',
'',
'',
'1990-01-01',
'active',
'superadmin',
true,
false,
true,
NOW(),
NOW()
)
"""),
{
"email": email,
"password_hash": password_hash,
"first_name": first_name,
"last_name": last_name
}
)
conn.commit()
print()
print("=" * 70)
print("✅ Superadmin user created successfully!")
print("=" * 70)
print()
print(f" Email: {email}")
print(f" Name: {first_name} {last_name}")
print(f" Role: superadmin")
print(f" Status: active")
print()
print("You can now log in with these credentials.")
print("=" * 70)
except ImportError as e:
print(f"❌ Missing dependency: {e}")
print(" Run: pip install sqlalchemy psycopg2-binary passlib python-dotenv")
sys.exit(1)
except Exception as e:
print(f"❌ Database error: {e}")
sys.exit(1)
if __name__ == "__main__":
try:
@@ -100,6 +144,3 @@ if __name__ == "__main__":
except KeyboardInterrupt:
print("\n\n❌ Cancelled by user")
sys.exit(1)
except Exception as e:
print(f"\n❌ Error: {e}")
sys.exit(1)