Skip to content

Commit 1b02b5e

Browse files
committed
security: Secure admin access - Remove regex promotion, seed default admin instead
1 parent 8b8a36b commit 1b02b5e

File tree

3 files changed

+38
-3
lines changed

3 files changed

+38
-3
lines changed

backend/auth.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -85,8 +85,8 @@ def get_current_user(token: str = Depends(oauth2_scheme), db: Session = Depends(
8585

8686
def is_admin(user: models.User) -> bool:
8787
"""Check if user has admin privileges."""
88-
# Check both username='admin' for backward compatibility and role field
89-
return user.username == "admin" or user.username.startswith("admin_") or getattr(user, 'role', 'patient') == 'admin'
88+
# Strict Role-Based Access Control
89+
return getattr(user, 'role', 'patient') == 'admin'
9090

9191
# --- Endpoints ---
9292

backend/main.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,9 +79,42 @@ def run_migrations():
7979

8080
run_migrations()
8181

82+
# --- Seeding ---
83+
def create_default_admin():
84+
"""Create a default admin user if one does not exist."""
85+
session = database.SessionLocal()
86+
try:
87+
# Check if any admin exists
88+
admin = session.query(models.User).filter(models.User.role == "admin").first()
89+
if not admin:
90+
logger.warning("No admin found. Creating default 'admin' user...")
91+
92+
# Secure default admin
93+
hashed_pw = auth.get_password_hash("admin123")
94+
default_admin = models.User(
95+
username="admin",
96+
hashed_password=hashed_pw,
97+
email="admin@hospital.com",
98+
role="admin",
99+
full_name="System Administrator",
100+
allow_data_collection=0
101+
)
102+
session.add(default_admin)
103+
session.commit()
104+
logger.info("✅ Default Admin Created: username='admin', password='admin123'")
105+
else:
106+
logger.info("Admin account already exists.")
107+
except Exception as e:
108+
logger.error(f"Failed to seed admin: {e}")
109+
finally:
110+
session.close()
111+
82112
# --- App ---
83113
@asynccontextmanager
84114
async def lifespan(app: FastAPI):
115+
# Run Seeding
116+
create_default_admin()
117+
85118
logger.info("Loading AI models...")
86119
prediction.initialize_models()
87120
yield

frontend/components/sidebar.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,9 @@ def render_sidebar():
7777
]
7878

7979
# Admin option
80-
if username == "admin" or username.startswith("admin_"):
80+
# Strict Check: Only show if role is explicitly 'admin'
81+
user_role = st.session_state.get('role', 'patient')
82+
if user_role == 'admin':
8183
nav_options.append(i18n.get_text("admin"))
8284
nav_icons.append("shield-lock")
8385

0 commit comments

Comments
 (0)