#!/usr/bin/env python3 """ Seed script to create an admin user in the Newzy database. Run this once after initial setup. Usage: python seed_admin.py # or with custom username: python seed_admin.py --username my_admin_user """ import os import sys from sqlalchemy import create_engine, inspect from sqlalchemy.orm import Session # Add the project root to the path sys.path.insert(0, os.path.dirname(__file__)) from db.session import engine, Base, get_db from models.author import Author # Import to check if tables exist from app.models import User from app.auth import hash_password, SECRET_KEY def main(): """Create admin user in the database.""" # Check for command line args username = "admin" password = os.environ.get("ADMIN_PASSWORD", "admin123") if len(sys.argv) > 1: username = sys.argv[1] print(f"Creating admin user: {username}") print(f"Password: {password}") print() # Create engine and session db_url = os.environ.get("DATABASE_URL", "sqlite:///data/db/newzy.db") print(f"Connecting to database at: {db_url}") try: # Check if database exists with Session(engine) as session: tables = inspect(engine).get_table_names() if not tables: print("Error: No tables found in database. Please initialize the database first.") return if "users" not in tables: print("Error: Users table not found. Please create the database schema first.") print("Run: python -c 'from db.session import engine, Base; Base.metadata.create_all(engine)'") return # Check if user already exists existing_user = session.query(User).filter(User.username == username).first() if existing_user: is_admin = getattr(existing_user, "is_admin", False) print(f"User '{username}' already exists.") if is_admin: print("This user is already an admin. Nothing to do.") sys.exit(0) else: print(f"Upgrading user to admin...") existing_user.is_admin = True session.commit() print(f"User '{username}' is now an admin.") sys.exit(0) # Create new admin user print("Creating new admin user...") new_user = User( username=username, password_hash=hash_password(password), is_admin=True ) session.add(new_user) session.commit() print(f"Successfully created admin user '{username}'!") print("You can now login with username:", username) print("Password: ", password) print("\nNote: In production, change the default password immediately.") except Exception as e: print(f"Error: {e}") sys.exit(1) if __name__ == "__main__": main()