updated roles ant permissions
This commit is contained in:
110
py_app/app/db_create_scripts/add_email_column.py
Normal file
110
py_app/app/db_create_scripts/add_email_column.py
Normal file
@@ -0,0 +1,110 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import mariadb
|
||||
import os
|
||||
import sys
|
||||
|
||||
def get_external_db_connection():
|
||||
"""Reads the external_server.conf file and returns a MariaDB database connection."""
|
||||
# Get the instance folder path
|
||||
current_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
instance_folder = os.path.join(current_dir, '../../instance')
|
||||
settings_file = os.path.join(instance_folder, 'external_server.conf')
|
||||
|
||||
if not os.path.exists(settings_file):
|
||||
raise FileNotFoundError(f"The external_server.conf file is missing: {settings_file}")
|
||||
|
||||
# Read settings from the configuration file
|
||||
settings = {}
|
||||
with open(settings_file, 'r') as f:
|
||||
for line in f:
|
||||
line = line.strip()
|
||||
if line and '=' in line:
|
||||
key, value = line.split('=', 1)
|
||||
settings[key] = value
|
||||
|
||||
print(f"Connecting to MariaDB:")
|
||||
print(f" Host: {settings.get('server_domain', 'N/A')}")
|
||||
print(f" Port: {settings.get('port', 'N/A')}")
|
||||
print(f" Database: {settings.get('database_name', 'N/A')}")
|
||||
|
||||
return mariadb.connect(
|
||||
user=settings['username'],
|
||||
password=settings['password'],
|
||||
host=settings['server_domain'],
|
||||
port=int(settings['port']),
|
||||
database=settings['database_name']
|
||||
)
|
||||
|
||||
def main():
|
||||
try:
|
||||
print("=== Adding Email Column to Users Table ===")
|
||||
conn = get_external_db_connection()
|
||||
cursor = conn.cursor()
|
||||
|
||||
# First, check the current table structure
|
||||
print("\n1. Checking current table structure...")
|
||||
cursor.execute("DESCRIBE users")
|
||||
columns = cursor.fetchall()
|
||||
|
||||
has_email = False
|
||||
for column in columns:
|
||||
print(f" Column: {column[0]} ({column[1]})")
|
||||
if column[0] == 'email':
|
||||
has_email = True
|
||||
|
||||
if not has_email:
|
||||
print("\n2. Adding email column...")
|
||||
cursor.execute("ALTER TABLE users ADD COLUMN email VARCHAR(255)")
|
||||
conn.commit()
|
||||
print(" ✓ Email column added successfully")
|
||||
else:
|
||||
print("\n2. Email column already exists")
|
||||
|
||||
# Now check and display all users
|
||||
print("\n3. Current users in database:")
|
||||
cursor.execute("SELECT id, username, role, email FROM users")
|
||||
users = cursor.fetchall()
|
||||
|
||||
if users:
|
||||
print(f" Found {len(users)} users:")
|
||||
for user in users:
|
||||
email = user[3] if user[3] else "No email"
|
||||
print(f" - ID: {user[0]}, Username: {user[1]}, Role: {user[2]}, Email: {email}")
|
||||
else:
|
||||
print(" No users found - creating test users...")
|
||||
|
||||
# Create some test users
|
||||
test_users = [
|
||||
('admin_user', 'admin123', 'admin', 'admin@company.com'),
|
||||
('manager_user', 'manager123', 'manager', 'manager@company.com'),
|
||||
('warehouse_user', 'warehouse123', 'warehouse_manager', 'warehouse@company.com'),
|
||||
('quality_user', 'quality123', 'quality_manager', 'quality@company.com')
|
||||
]
|
||||
|
||||
for username, password, role, email in test_users:
|
||||
try:
|
||||
cursor.execute("""
|
||||
INSERT INTO users (username, password, role, email)
|
||||
VALUES (%s, %s, %s, %s)
|
||||
""", (username, password, role, email))
|
||||
print(f" ✓ Created user: {username} ({role})")
|
||||
except mariadb.IntegrityError as e:
|
||||
print(f" ⚠ User {username} already exists: {e}")
|
||||
|
||||
conn.commit()
|
||||
print(" ✓ Test users created successfully")
|
||||
|
||||
conn.close()
|
||||
print("\n=== Database Update Complete ===")
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ Error: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
return 1
|
||||
|
||||
return 0
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
105
py_app/app/db_create_scripts/check_external_db_users.py
Normal file
105
py_app/app/db_create_scripts/check_external_db_users.py
Normal file
@@ -0,0 +1,105 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import mariadb
|
||||
import os
|
||||
import sys
|
||||
|
||||
def get_external_db_connection():
|
||||
"""Reads the external_server.conf file and returns a MariaDB database connection."""
|
||||
# Get the instance folder path
|
||||
current_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
instance_folder = os.path.join(current_dir, '../../instance')
|
||||
settings_file = os.path.join(instance_folder, 'external_server.conf')
|
||||
|
||||
if not os.path.exists(settings_file):
|
||||
raise FileNotFoundError(f"The external_server.conf file is missing: {settings_file}")
|
||||
|
||||
# Read settings from the configuration file
|
||||
settings = {}
|
||||
with open(settings_file, 'r') as f:
|
||||
for line in f:
|
||||
line = line.strip()
|
||||
if line and '=' in line:
|
||||
key, value = line.split('=', 1)
|
||||
settings[key] = value
|
||||
|
||||
print(f"Connecting to MariaDB with settings:")
|
||||
print(f" Host: {settings.get('server_domain', 'N/A')}")
|
||||
print(f" Port: {settings.get('port', 'N/A')}")
|
||||
print(f" Database: {settings.get('database_name', 'N/A')}")
|
||||
print(f" Username: {settings.get('username', 'N/A')}")
|
||||
|
||||
# Create a database connection
|
||||
return mariadb.connect(
|
||||
user=settings['username'],
|
||||
password=settings['password'],
|
||||
host=settings['server_domain'],
|
||||
port=int(settings['port']),
|
||||
database=settings['database_name']
|
||||
)
|
||||
|
||||
def main():
|
||||
try:
|
||||
print("=== Checking External MariaDB Database ===")
|
||||
conn = get_external_db_connection()
|
||||
cursor = conn.cursor()
|
||||
|
||||
# Create users table if it doesn't exist
|
||||
print("\n1. Creating/verifying users table...")
|
||||
cursor.execute('''
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
username VARCHAR(50) UNIQUE NOT NULL,
|
||||
password VARCHAR(255) NOT NULL,
|
||||
role VARCHAR(50) NOT NULL,
|
||||
email VARCHAR(255)
|
||||
)
|
||||
''')
|
||||
print(" ✓ Users table created/verified")
|
||||
|
||||
# Check existing users
|
||||
print("\n2. Checking existing users...")
|
||||
cursor.execute("SELECT id, username, role, email FROM users")
|
||||
users = cursor.fetchall()
|
||||
|
||||
if users:
|
||||
print(f" Found {len(users)} existing users:")
|
||||
for user in users:
|
||||
email = user[3] if user[3] else "No email"
|
||||
print(f" - ID: {user[0]}, Username: {user[1]}, Role: {user[2]}, Email: {email}")
|
||||
else:
|
||||
print(" No users found in external database")
|
||||
|
||||
# Create some test users
|
||||
print("\n3. Creating test users...")
|
||||
test_users = [
|
||||
('admin_user', 'admin123', 'admin', 'admin@company.com'),
|
||||
('manager_user', 'manager123', 'manager', 'manager@company.com'),
|
||||
('warehouse_user', 'warehouse123', 'warehouse_manager', 'warehouse@company.com'),
|
||||
('quality_user', 'quality123', 'quality_manager', 'quality@company.com')
|
||||
]
|
||||
|
||||
for username, password, role, email in test_users:
|
||||
try:
|
||||
cursor.execute("""
|
||||
INSERT INTO users (username, password, role, email)
|
||||
VALUES (%s, %s, %s, %s)
|
||||
""", (username, password, role, email))
|
||||
print(f" ✓ Created user: {username} ({role})")
|
||||
except mariadb.IntegrityError as e:
|
||||
print(f" ⚠ User {username} already exists: {e}")
|
||||
|
||||
conn.commit()
|
||||
print(" ✓ Test users created successfully")
|
||||
|
||||
conn.close()
|
||||
print("\n=== Database Check Complete ===")
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ Error: {e}")
|
||||
return 1
|
||||
|
||||
return 0
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
141
py_app/app/db_create_scripts/create_permissions_tables.py
Normal file
141
py_app/app/db_create_scripts/create_permissions_tables.py
Normal file
@@ -0,0 +1,141 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import mariadb
|
||||
import os
|
||||
import sys
|
||||
|
||||
def get_external_db_connection():
|
||||
"""Reads the external_server.conf file and returns a MariaDB database connection."""
|
||||
# Get the instance folder path
|
||||
current_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
instance_folder = os.path.join(current_dir, '../../instance')
|
||||
settings_file = os.path.join(instance_folder, 'external_server.conf')
|
||||
|
||||
if not os.path.exists(settings_file):
|
||||
raise FileNotFoundError(f"The external_server.conf file is missing: {settings_file}")
|
||||
|
||||
# Read settings from the configuration file
|
||||
settings = {}
|
||||
with open(settings_file, 'r') as f:
|
||||
for line in f:
|
||||
line = line.strip()
|
||||
if line and '=' in line:
|
||||
key, value = line.split('=', 1)
|
||||
settings[key] = value
|
||||
|
||||
return mariadb.connect(
|
||||
user=settings['username'],
|
||||
password=settings['password'],
|
||||
host=settings['server_domain'],
|
||||
port=int(settings['port']),
|
||||
database=settings['database_name']
|
||||
)
|
||||
|
||||
def main():
|
||||
try:
|
||||
print("=== Creating Permission Management Tables ===")
|
||||
conn = get_external_db_connection()
|
||||
cursor = conn.cursor()
|
||||
|
||||
# 1. Create permissions table
|
||||
print("\n1. Creating permissions table...")
|
||||
cursor.execute('''
|
||||
CREATE TABLE IF NOT EXISTS permissions (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
permission_key VARCHAR(255) UNIQUE NOT NULL,
|
||||
page VARCHAR(100) NOT NULL,
|
||||
page_name VARCHAR(255) NOT NULL,
|
||||
section VARCHAR(100) NOT NULL,
|
||||
section_name VARCHAR(255) NOT NULL,
|
||||
action VARCHAR(50) NOT NULL,
|
||||
action_name VARCHAR(255) NOT NULL,
|
||||
description TEXT,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
|
||||
)
|
||||
''')
|
||||
print(" ✓ Permissions table created/verified")
|
||||
|
||||
# 2. Create role_permissions table
|
||||
print("\n2. Creating role_permissions table...")
|
||||
cursor.execute('''
|
||||
CREATE TABLE IF NOT EXISTS role_permissions (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
role VARCHAR(50) NOT NULL,
|
||||
permission_key VARCHAR(255) NOT NULL,
|
||||
granted BOOLEAN DEFAULT TRUE,
|
||||
granted_by VARCHAR(50),
|
||||
granted_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
UNIQUE KEY unique_role_permission (role, permission_key),
|
||||
FOREIGN KEY (permission_key) REFERENCES permissions(permission_key) ON DELETE CASCADE
|
||||
)
|
||||
''')
|
||||
print(" ✓ Role permissions table created/verified")
|
||||
|
||||
# 3. Create role_hierarchy table for role management
|
||||
print("\n3. Creating role_hierarchy table...")
|
||||
cursor.execute('''
|
||||
CREATE TABLE IF NOT EXISTS role_hierarchy (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
role_name VARCHAR(50) UNIQUE NOT NULL,
|
||||
display_name VARCHAR(255) NOT NULL,
|
||||
description TEXT,
|
||||
level INT DEFAULT 0,
|
||||
is_active BOOLEAN DEFAULT TRUE,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
|
||||
)
|
||||
''')
|
||||
print(" ✓ Role hierarchy table created/verified")
|
||||
|
||||
# 4. Create permission_audit_log table for tracking changes
|
||||
print("\n4. Creating permission_audit_log table...")
|
||||
cursor.execute('''
|
||||
CREATE TABLE IF NOT EXISTS permission_audit_log (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
role VARCHAR(50) NOT NULL,
|
||||
permission_key VARCHAR(255) NOT NULL,
|
||||
action ENUM('granted', 'revoked') NOT NULL,
|
||||
changed_by VARCHAR(50) NOT NULL,
|
||||
changed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
reason TEXT,
|
||||
ip_address VARCHAR(45)
|
||||
)
|
||||
''')
|
||||
print(" ✓ Permission audit log table created/verified")
|
||||
|
||||
conn.commit()
|
||||
|
||||
# 5. Check if we need to populate initial data
|
||||
print("\n5. Checking for existing data...")
|
||||
cursor.execute("SELECT COUNT(*) FROM permissions")
|
||||
permission_count = cursor.fetchone()[0]
|
||||
|
||||
if permission_count == 0:
|
||||
print(" No permissions found - will need to populate with default data")
|
||||
print(" Run 'populate_permissions.py' to initialize the permission system")
|
||||
else:
|
||||
print(f" Found {permission_count} existing permissions")
|
||||
|
||||
cursor.execute("SELECT COUNT(*) FROM role_hierarchy")
|
||||
role_count = cursor.fetchone()[0]
|
||||
|
||||
if role_count == 0:
|
||||
print(" No roles found - will need to populate with default roles")
|
||||
else:
|
||||
print(f" Found {role_count} existing roles")
|
||||
|
||||
conn.close()
|
||||
print("\n=== Permission Database Schema Created Successfully ===")
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ Error: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
return 1
|
||||
|
||||
return 0
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
143
py_app/app/db_create_scripts/populate_permissions.py
Normal file
143
py_app/app/db_create_scripts/populate_permissions.py
Normal file
@@ -0,0 +1,143 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import mariadb
|
||||
import os
|
||||
import sys
|
||||
|
||||
# Add the app directory to the path so we can import our permissions module
|
||||
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
|
||||
|
||||
from permissions import APP_PERMISSIONS, ROLE_HIERARCHY, ACTIONS, get_all_permissions, get_default_permissions_for_role
|
||||
|
||||
def get_external_db_connection():
|
||||
"""Reads the external_server.conf file and returns a MariaDB database connection."""
|
||||
current_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
instance_folder = os.path.join(current_dir, '../../instance')
|
||||
settings_file = os.path.join(instance_folder, 'external_server.conf')
|
||||
|
||||
if not os.path.exists(settings_file):
|
||||
raise FileNotFoundError(f"The external_server.conf file is missing: {settings_file}")
|
||||
|
||||
settings = {}
|
||||
with open(settings_file, 'r') as f:
|
||||
for line in f:
|
||||
line = line.strip()
|
||||
if line and '=' in line:
|
||||
key, value = line.split('=', 1)
|
||||
settings[key] = value
|
||||
|
||||
return mariadb.connect(
|
||||
user=settings['username'],
|
||||
password=settings['password'],
|
||||
host=settings['server_domain'],
|
||||
port=int(settings['port']),
|
||||
database=settings['database_name']
|
||||
)
|
||||
|
||||
def main():
|
||||
try:
|
||||
print("=== Populating Permission System ===")
|
||||
conn = get_external_db_connection()
|
||||
cursor = conn.cursor()
|
||||
|
||||
# 1. Populate all permissions
|
||||
print("\n1. Populating permissions...")
|
||||
permissions = get_all_permissions()
|
||||
|
||||
for perm in permissions:
|
||||
try:
|
||||
cursor.execute('''
|
||||
INSERT INTO permissions (permission_key, page, page_name, section, section_name, action, action_name)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s)
|
||||
ON DUPLICATE KEY UPDATE
|
||||
page_name = VALUES(page_name),
|
||||
section_name = VALUES(section_name),
|
||||
action_name = VALUES(action_name),
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
''', (
|
||||
perm['key'],
|
||||
perm['page'],
|
||||
perm['page_name'],
|
||||
perm['section'],
|
||||
perm['section_name'],
|
||||
perm['action'],
|
||||
perm['action_name']
|
||||
))
|
||||
except Exception as e:
|
||||
print(f" ⚠ Error inserting permission {perm['key']}: {e}")
|
||||
|
||||
conn.commit()
|
||||
print(f" ✓ Populated {len(permissions)} permissions")
|
||||
|
||||
# 2. Populate role hierarchy
|
||||
print("\n2. Populating role hierarchy...")
|
||||
for role_name, role_data in ROLE_HIERARCHY.items():
|
||||
try:
|
||||
cursor.execute('''
|
||||
INSERT INTO role_hierarchy (role_name, display_name, description, level)
|
||||
VALUES (%s, %s, %s, %s)
|
||||
ON DUPLICATE KEY UPDATE
|
||||
display_name = VALUES(display_name),
|
||||
description = VALUES(description),
|
||||
level = VALUES(level),
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
''', (
|
||||
role_name,
|
||||
role_data['name'],
|
||||
role_data['description'],
|
||||
role_data['level']
|
||||
))
|
||||
except Exception as e:
|
||||
print(f" ⚠ Error inserting role {role_name}: {e}")
|
||||
|
||||
conn.commit()
|
||||
print(f" ✓ Populated {len(ROLE_HIERARCHY)} roles")
|
||||
|
||||
# 3. Set default permissions for each role
|
||||
print("\n3. Setting default role permissions...")
|
||||
for role_name in ROLE_HIERARCHY.keys():
|
||||
default_permissions = get_default_permissions_for_role(role_name)
|
||||
|
||||
print(f" Setting permissions for {role_name}: {len(default_permissions)} permissions")
|
||||
|
||||
for permission_key in default_permissions:
|
||||
try:
|
||||
cursor.execute('''
|
||||
INSERT INTO role_permissions (role, permission_key, granted, granted_by)
|
||||
VALUES (%s, %s, TRUE, 'system')
|
||||
ON DUPLICATE KEY UPDATE
|
||||
granted = TRUE,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
''', (role_name, permission_key))
|
||||
except Exception as e:
|
||||
print(f" ⚠ Error setting permission {permission_key} for {role_name}: {e}")
|
||||
|
||||
conn.commit()
|
||||
|
||||
# 4. Show summary
|
||||
print("\n4. Permission Summary:")
|
||||
cursor.execute('''
|
||||
SELECT r.role_name, r.display_name, COUNT(rp.permission_key) as permission_count
|
||||
FROM role_hierarchy r
|
||||
LEFT JOIN role_permissions rp ON r.role_name = rp.role AND rp.granted = TRUE
|
||||
GROUP BY r.role_name, r.display_name
|
||||
ORDER BY r.level DESC
|
||||
''')
|
||||
|
||||
results = cursor.fetchall()
|
||||
for role_name, display_name, count in results:
|
||||
print(f" {display_name} ({role_name}): {count} permissions")
|
||||
|
||||
conn.close()
|
||||
print("\n=== Permission System Initialization Complete ===")
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ Error: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
return 1
|
||||
|
||||
return 0
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user