function create_admin_panel_v1
Factory function that creates and initializes an AdminPanel instance with optional session management, parent application integration, and embedded mode support.
/tf/active/vicechatdev/CDocs single class/ui/admin_panel.py
1448 - 1483
moderate
Purpose
This function serves as the primary entry point for creating admin panel instances in the Controlled Documents system. It handles initialization of the Panel-based UI template, sets up session management, integrates with parent applications, and performs initial authorization checks. The function supports both standalone and embedded deployment modes, automatically detecting the appropriate configuration based on provided parameters. It also handles user authentication state transfer from parent applications and loads the admin dashboard if the user has appropriate permissions.
Source Code
def create_admin_panel(session_manager=None, parent_app=None, embedded=False):
"""Create and initialize an admin panel instance"""
try:
# Create template for admin panel (only used in standalone mode)
admin_bp = pn.template.BootstrapTemplate(
site="Controlled Documents",
title="Admin Panel",
sidebar_width=300,
)
# Create and initialize panel - session_manager is now optional
panel = AdminPanel(
template=admin_bp,
session_manager=session_manager, # This may be None, handle it in the class
parent_app=parent_app,
embedded=embedded or parent_app is not None # Auto-detect embedded mode
)
# If parent_app has a current_user, set it directly
if parent_app and hasattr(parent_app, 'current_user') and parent_app.current_user:
logger.debug(f"Setting user from parent app: {parent_app.current_user.username if hasattr(parent_app.current_user, 'username') else 'Unknown'}")
panel.user = parent_app.current_user
# Check if user has admin permissions
if panel._verify_admin_access():
# Load dashboard if authorized
logger.debug("User has admin access, loading dashboard")
panel._load_admin_dashboard()
else:
logger.warning("User does not have admin access")
panel.notification_area.object = "**Error:** You do not have permission to access the admin panel."
return panel
except Exception as e:
logger.error(f"Error creating admin panel: {e}")
return None
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
session_manager |
- | None | positional_or_keyword |
parent_app |
- | None | positional_or_keyword |
embedded |
- | False | positional_or_keyword |
Parameter Details
session_manager: Optional SessionManager instance for handling user authentication and session state. If None, the AdminPanel will need to handle authentication internally or operate without session management. Expected type: SessionManager or None.
parent_app: Optional reference to a parent application object that may contain user authentication state and other shared resources. If provided, the function will attempt to extract current_user information and automatically set embedded mode. Expected type: Application object with optional 'current_user' attribute, or None.
embedded: Boolean flag indicating whether the admin panel should run in embedded mode (as part of a larger application) or standalone mode. When True, the panel adapts its behavior for integration. Automatically set to True if parent_app is provided. Default: False.
Return Value
Returns an initialized AdminPanel instance if successful, or None if an error occurs during creation. The AdminPanel object will have its template configured, user authentication state set (if available from parent_app), and dashboard loaded (if user has admin permissions). Type: AdminPanel or None.
Dependencies
panelloggingtracebacktypingdatetimejsonparampandasnumpymatplotlibhashlibuuid
Required Imports
import panel as pn
import logging
from CDocs.models.user_extensions import DocUser
from CDocs.auth.session_manager import SessionManager
from CDocs.controllers.admin_controller import get_system_stats, get_users, create_user, update_user, delete_user, get_departments, get_user_activity, get_document_stats
from CDocs.controllers import ResourceNotFoundError, ValidationError, PermissionError, BusinessRuleError
from CDocs.config import settings, permissions
from CDocs.db.db_operations import run_query
Conditional/Optional Imports
These imports are only needed under specific conditions:
from panel.template import BootstrapTemplate
Condition: Required for creating the admin panel template in standalone mode
Required (conditional)from panel.widgets import Button, Select, TextInput, TextAreaInput, DatePicker, FileInput, Tabulator, CheckBoxGroup, RadioButtonGroup, MultiSelect, Switch, IntSlider, NumberInput
Condition: Required by AdminPanel class for UI components
Required (conditional)from panel.layout import Column, Row, Card, GridBox, Tabs
Condition: Required by AdminPanel class for layout management
Required (conditional)from panel.pane import Markdown, HTML, JSON, DataFrame
Condition: Required by AdminPanel class for content display
Required (conditional)Usage Example
# Standalone mode with session manager
from CDocs.auth.session_manager import SessionManager
session_mgr = SessionManager()
panel = create_admin_panel(session_manager=session_mgr)
if panel:
panel.servable()
# Embedded mode with parent app
class MyApp:
def __init__(self):
self.current_user = DocUser(username='admin', role='admin')
parent = MyApp()
admin_panel = create_admin_panel(parent_app=parent, embedded=True)
# Minimal standalone mode
admin_panel = create_admin_panel()
if admin_panel:
admin_panel.servable()
Best Practices
- Always check if the returned panel is not None before using it, as creation may fail
- When using embedded mode, ensure the parent_app has a properly configured current_user attribute
- The function automatically detects embedded mode if parent_app is provided, so explicit embedded=True is optional in that case
- Ensure the AdminPanel class is properly defined before calling this function
- The logger variable must be defined in the module scope for error logging to work
- Session manager is optional but recommended for production use to handle authentication properly
- Admin access verification happens automatically if a user is provided via parent_app
- Handle the case where user lacks admin permissions by checking the notification_area for error messages
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function create_admin_panel 86.6% similar
-
function create_approval_panel 79.7% similar
-
function create_approval_panel_v2 79.2% similar
-
function create_embedded_admin_panel 78.1% similar
-
function create_approval_panel_v1 72.8% similar