forked from andika/membership-be
RBAC, Permissions, and Export/Import
This commit is contained in:
147
roles_seed.py
Normal file
147
roles_seed.py
Normal file
@@ -0,0 +1,147 @@
|
||||
"""
|
||||
Role Seeding Script
|
||||
|
||||
This script populates the database with system roles for the dynamic RBAC system.
|
||||
Creates 4 system roles: Superadmin, Finance, Member, and Guest.
|
||||
|
||||
Usage:
|
||||
python roles_seed.py
|
||||
|
||||
Environment Variables:
|
||||
DATABASE_URL - PostgreSQL connection string
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from database import Base
|
||||
from models import Role
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables
|
||||
load_dotenv()
|
||||
|
||||
# Database connection
|
||||
DATABASE_URL = os.getenv("DATABASE_URL")
|
||||
if not DATABASE_URL:
|
||||
print("Error: DATABASE_URL environment variable not set")
|
||||
sys.exit(1)
|
||||
|
||||
engine = create_engine(DATABASE_URL)
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
# ============================================================
|
||||
# System Role Definitions
|
||||
# ============================================================
|
||||
|
||||
SYSTEM_ROLES = [
|
||||
{
|
||||
"code": "superadmin",
|
||||
"name": "Superadmin",
|
||||
"description": "Full system access with all permissions. Can manage roles, permissions, and all platform features.",
|
||||
"is_system_role": True
|
||||
},
|
||||
{
|
||||
"code": "admin",
|
||||
"name": "Admin",
|
||||
"description": "Administrative access to most platform features. Can manage users, events, and content.",
|
||||
"is_system_role": True
|
||||
},
|
||||
{
|
||||
"code": "finance",
|
||||
"name": "Finance Manager",
|
||||
"description": "Access to financial features including subscriptions, payments, and financial reports.",
|
||||
"is_system_role": True
|
||||
},
|
||||
{
|
||||
"code": "member",
|
||||
"name": "Member",
|
||||
"description": "Standard member access. Can view events, manage profile, and participate in community features.",
|
||||
"is_system_role": True
|
||||
},
|
||||
{
|
||||
"code": "guest",
|
||||
"name": "Guest",
|
||||
"description": "Limited access for unverified or pending users. Can view basic information and complete registration.",
|
||||
"is_system_role": True
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
def seed_roles():
|
||||
"""Seed system roles into the database"""
|
||||
db = SessionLocal()
|
||||
|
||||
try:
|
||||
print("🌱 Starting role seeding...")
|
||||
print("="*60)
|
||||
|
||||
# Check if roles already exist
|
||||
existing_roles = db.query(Role).filter(Role.is_system_role == True).all()
|
||||
if existing_roles:
|
||||
print(f"\n⚠️ Found {len(existing_roles)} existing system roles:")
|
||||
for role in existing_roles:
|
||||
print(f" • {role.name} ({role.code})")
|
||||
|
||||
response = input("\nDo you want to recreate system roles? This will delete existing system roles. (yes/no): ")
|
||||
if response.lower() != 'yes':
|
||||
print("\n❌ Seeding cancelled by user")
|
||||
return
|
||||
|
||||
print("\n🗑️ Deleting existing system roles...")
|
||||
for role in existing_roles:
|
||||
db.delete(role)
|
||||
db.commit()
|
||||
print("✓ Deleted existing system roles")
|
||||
|
||||
# Create system roles
|
||||
print(f"\n📝 Creating {len(SYSTEM_ROLES)} system roles...")
|
||||
created_roles = []
|
||||
|
||||
for role_data in SYSTEM_ROLES:
|
||||
role = Role(
|
||||
code=role_data["code"],
|
||||
name=role_data["name"],
|
||||
description=role_data["description"],
|
||||
is_system_role=role_data["is_system_role"],
|
||||
created_by=None # System roles have no creator
|
||||
)
|
||||
db.add(role)
|
||||
created_roles.append(role)
|
||||
print(f" ✓ Created: {role.name} ({role.code})")
|
||||
|
||||
db.commit()
|
||||
print(f"\n✅ Created {len(created_roles)} system roles")
|
||||
|
||||
# Display summary
|
||||
print("\n" + "="*60)
|
||||
print("📊 Seeding Summary:")
|
||||
print("="*60)
|
||||
print("\nSystem Roles Created:")
|
||||
for role in created_roles:
|
||||
print(f"\n • {role.name} ({role.code})")
|
||||
print(f" {role.description}")
|
||||
|
||||
print("\n" + "="*60)
|
||||
print("✅ Role seeding completed successfully!")
|
||||
print("="*60)
|
||||
|
||||
print("\n📝 Next Steps:")
|
||||
print(" 1. Migrate existing users to use role_id (Phase 3)")
|
||||
print(" 2. Migrate role_permissions to use role_id (Phase 3)")
|
||||
print(" 3. Update authentication logic to use dynamic roles (Phase 3)")
|
||||
print(" 4. Remove legacy enum columns (Phase 4)")
|
||||
|
||||
except Exception as e:
|
||||
db.rollback()
|
||||
print(f"\n❌ Error seeding roles: {str(e)}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
raise
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
seed_roles()
|
||||
Reference in New Issue
Block a user