Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

Add admin panel with user, settings, and audit log management

Juan Denis893df4753b5f
diff --git a/backend/app/__init__.py b/backend/app/__init__.py
index 2e74ce2f..3314d28b 100644
--- a/backend/app/__init__.py
+++ b/backend/app/__init__.py
@@ -149,10 +149,19 @@ def create_app(config_name=None):
from app.api.two_factor import two_factor_bp
app.register_blueprint(two_factor_bp, url_prefix='/api/v1/auth/2fa')
+ # Register blueprints - Admin (User Management, Settings, Audit Logs)
+ from app.api.admin import admin_bp
+ app.register_blueprint(admin_bp, url_prefix='/api/v1/admin')
+
# Create database tables
with app.app_context():
db.create_all()
+ # Initialize default settings and migrate legacy roles
+ from app.services.settings_service import SettingsService
+ SettingsService.initialize_defaults()
+ SettingsService.migrate_legacy_roles()
+
# Serve frontend for root path
@app.route('/')
def serve_index():
diff --git a/backend/app/api/admin.py b/backend/app/api/admin.py
new file mode 100644
index 00000000..b626e5c6
--- /dev/null
+++ b/backend/app/api/admin.py
@@ -0,0 +1,381 @@
+"""Admin API endpoints for user management, settings, and audit logs."""
+from datetime import datetime
+from flask import Blueprint, request, jsonify
+from flask_jwt_extended import get_jwt_identity
+from app import db
+from app.models import User, AuditLog
+from app.middleware.rbac import admin_required, get_current_user
+from app.services.audit_service import AuditService
+from app.services.settings_service import SettingsService
+
+admin_bp = Blueprint('admin', __name__)
+
+
+# ============================================
+# User Management Endpoints
+# ============================================
+
+@admin_bp.route('/users', methods=['GET'])
+@admin_required
+def list_users():
+ """List all users."""
+ users = User.query.order_by(User.created_at.desc()).all()
+ return jsonify({
+ 'users': [user.to_dict() for user in users]
+ }), 200
+
+
+@admin_bp.route('/users', methods=['POST'])
+@admin_required
+def create_user():
+ """Create a new user."""
+ data = request.get_json()
+ current_user_id = get_jwt_identity()
+
+ if not data:
+ return jsonify({'error': 'No data provided'}), 400
+
+ email = data.get('email')
+ username = data.get('username')
+ password = data.get('password')
+ role = data.get('role', User.ROLE_DEVELOPER)
+
+ if not all([email, username, password]):
+ return jsonify({'error': 'Missing required fields: email, username, password'}), 400
+
+ if role not in User.VALID_ROLES:
+ return jsonify({'error': f'Invalid role. Must be one of: {", ".join(User.VALID_ROLES)}'}), 400
+
+ if User.query.filter_by(email=email).first():
+ return jsonify({'error': 'Email already registered'}), 409
+
+ if User.query.filter_by(username=username).first():
+ return jsonify({'error': 'Username already taken'}), 409
+
+ if len(password) < 8:
+ return jsonify({'error': 'Password must be at least 8 characters'}), 400
+
+ user = User(
+ email=email,
+ username=username,
+ role=role,
+ created_by=current_user_id,
+ is_active=data.get('is_active', True)
+ )
+ user.set_password(password)
+
+ db.session.add(user)
+ db.session.commit()
+
+ # Log the action
+ AuditService.log_user_action(
+ action=AuditLog.ACTION_USER_CREATE,
+ user_id=current_user_id,
+ target_user_id=user.id,
+ details={'username': username, 'role': role}
+ )
+ db.session.commit()
+
+ return jsonify({
+ 'message': 'User created successfully',
+ 'user': user.to_dict()
+ }), 201
+
+
+@admin_bp.route('/users/<int:user_id>', methods=['GET'])
+@admin_required
+def get_user(user_id):
+ """Get a specific user."""
+ user = User.query.get(user_id)
+ if not user:
+ return jsonify({'error': 'User not found'}), 404
+
+ return jsonify({'user': user.to_dict()}), 200
+
+
+@admin_bp.route('/users/<int:user_id>', methods=['PUT'])
+@admin_required
+def update_user(user_id):
+ """Update a user."""
+ data = request.get_json()
+ current_user_id = get_jwt_identity()
+
+ user = User.query.get(user_id)
+ if not user:
+ return jsonify({'error': 'User not found'}), 404
+
+ changes = {}
+
+ # Update email
+ if 'email' in data and data['email'] != user.email:
+ existing = User.query.filter_by(email=data['email']).first()
+ if existing and existing.id != user.id:
+ return jsonify({'error': 'Email already registered'}), 409
+ changes['email'] = {'old': user.email, 'new': data['email']}
+ user.email = data['email']
+
+ # Update username
+ if 'username' in data and data['username'] != user.username:
+ existing = User.query.filter_by(username=data['username']).first()
+ if existing and existing.id != user.id:
+ return jsonify({'error': 'Username already taken'}), 409
+ changes['username'] = {'old': user.username, 'new': data['username']}
+ user.username = data['username']
+
+ # Update role
+ if 'role' in data and data['role'] != user.role:
+ if data['role'] not in User.VALID_ROLES:
+ return jsonify({'error': f'Invalid role. Must be one of: {", ".join(User.VALID_ROLES)}'}), 400
+
+ # Prevent demoting the last admin
+ if user.role == User.ROLE_ADMIN and data['role'] != User.ROLE_ADMIN:
+ admin_count = User.query.filter_by(role=User.ROLE_ADMIN).count()
+ if admin_count <= 1:
+ return jsonify({'error': 'Cannot demote the last admin'}), 400
+
+ changes['role'] = {'old': user.role, 'new': data['role']}
+ user.role = data['role']
+
+ # Update password
+ if 'password' in data and data['password']:
+ if len(data['password']) < 8:
+ return jsonify({'error': 'Password must be at least 8 characters'}), 400
+ user.set_password(data['password'])
+ changes['password'] = 'changed'
+
+ # Update active status
+ if 'is_active' in data and data['is_active'] != user.is_active:
+ # Prevent deactivating self
+ if user.id == current_user_id and not data['is_active']:
+ return jsonify({'error': 'Cannot deactivate your own account'}), 400
+
+ changes['is_active'] = {'old': user.is_active, 'new': data['is_active']}
+ user.is_active = data['is_active']
+
+ # Log enable/disable separately
+ action = AuditLog.ACTION_USER_ENABLE if data['is_active'] else AuditLog.ACTION_USER_DISABLE
+ AuditService.log_user_action(
+ action=action,
+ user_id=current_user_id,
+ target_user_id=user.id,
+ details={'username': user.username}
+ )
+
+ db.session.commit()
+
+ # Log the update
+ if changes:
+ AuditService.log_user_action(
+ action=AuditLog.ACTION_USER_UPDATE,
+ user_id=current_user_id,
+ target_user_id=user.id,
+ details={'changes': changes}
+ )
+ db.session.commit()
+
+ return jsonify({
+ 'message': 'User updated successfully',
+ 'user': user.to_dict()
+ }), 200
+
+
+@admin_bp.route('/users/<int:user_id>', methods=['DELETE'])
+@admin_required
+def delete_user(user_id):
+ """Delete a user."""
+ current_user_id = get_jwt_identity()
+
+ user = User.query.get(user_id)
+ if not user:
+ return jsonify({'error': 'User not found'}), 404
+
+ # Prevent self-deletion
+ if user.id == current_user_id:
+ return jsonify({'error': 'Cannot delete your own account'}), 400
+
+ # Prevent deleting the last admin
+ if user.role == User.ROLE_ADMIN:
+ admin_count = User.query.filter_by(role=User.ROLE_ADMIN).count()
+ if admin_count <= 1:
+ return jsonify({'error': 'Cannot delete the last admin'}), 400
+
+ username = user.username
+ user_id_deleted = user.id
+
+ db.session.delete(user)
+ db.session.commit()
+
+ # Log the action
+ AuditService.log_user_action(
+ action=AuditLog.ACTION_USER_DELETE,
+ user_id=current_user_id,
+ target_user_id=user_id_deleted,
+ details={'username': username}
+ )
+ db.session.commit()
+
+ return jsonify({'message': 'User deleted successfully'}), 200
+
+
+# ============================================
+# Audit Log Endpoints
+# ============================================
+
+@admin_bp.route('/audit-logs', methods=['GET'])
+@admin_required
+def get_audit_logs():
+ """Get audit logs with pagination and filtering."""
+ page = request.args.get('page', 1, type=int)
+ per_page = request.args.get('per_page', 50, type=int)
+ action = request.args.get('action')
+ user_id = request.args.get('user_id', type=int)
+ target_type = request.args.get('target_type')
+
+ # Limit per_page to reasonable values
+ per_page = min(per_page, 100)
+
+ pagination = AuditService.get_logs(
+ page=page,
+ per_page=per_page,
+ action=action,
+ user_id=user_id,
+ target_type=target_type
+ )
+
+ return jsonify({
+ 'logs': [log.to_dict() for log in pagination.items],
+ 'pagination': {
+ 'page': pagination.page,
+ 'per_page': pagination.per_page,
+ 'total': pagination.total,
+ 'pages': pagination.pages,
+ 'has_next': pagination.has_next,
+ 'has_prev': pagination.has_prev
+ }
+ }), 200
+
+
+@admin_bp.route('/audit-logs/actions', methods=['GET'])
+@admin_required
+def get_audit_log_actions():
+ """Get list of unique action types in audit logs."""
+ actions = db.session.query(AuditLog.action).distinct().all()
+ return jsonify({
+ 'actions': [a[0] for a in actions]
+ }), 200
+
+
+# ============================================
+# System Settings Endpoints
+# ============================================
+
+@admin_bp.route('/settings', methods=['GET'])
+@admin_required
+def get_settings():
+ """Get all system settings."""
+ settings = SettingsService.get_all_with_metadata()
+ return jsonify({'settings': settings}), 200
+
+
+@admin_bp.route('/settings', methods=['PUT'])
+@admin_required
+def update_settings():
+ """Update system settings."""
+ data = request.get_json()
+ current_user_id = get_jwt_identity()
+
+ if not data:
+ return jsonify({'error': 'No data provided'}), 400
+
+ updated = []
+ for key, value in data.items():
+ old_value = SettingsService.get(key)
+ SettingsService.set(key, value, user_id=current_user_id)
+ updated.append(key)
+
+ # Log the change
+ AuditService.log_settings_change(
+ user_id=current_user_id,
+ key=key,
+ old_value=old_value,
+ new_value=value
+ )
+
+ db.session.commit()
+
+ return jsonify({
+ 'message': 'Settings updated successfully',
+ 'updated': updated
+ }), 200
+
+
+@admin_bp.route('/settings/<key>', methods=['GET'])
+@admin_required
+def get_setting(key):
+ """Get a specific setting."""
+ value = SettingsService.get(key)
+ if value is None:
+ return jsonify({'error': 'Setting not found'}), 404
+ return jsonify({'key': key, 'value': value}), 200
+
+
+@admin_bp.route('/settings/<key>', methods=['PUT'])
+@admin_required
+def update_setting(key):
+ """Update a specific setting."""
+ data = request.get_json()
+ current_user_id = get_jwt_identity()
+
+ if 'value' not in data:
+ return jsonify({'error': 'No value provided'}), 400
+
+ old_value = SettingsService.get(key)
+ SettingsService.set(key, data['value'], user_id=current_user_id)
+
+ # Log the change
+ AuditService.log_settings_change(
+ user_id=current_user_id,
+ key=key,
+ old_value=old_value,
+ new_value=data['value']
+ )
+ db.session.commit()
+
+ return jsonify({
+ 'message': 'Setting updated successfully',
+ 'key': key,
+ 'value': data['value']
+ }), 200
+
+
+# ============================================
+# Admin Statistics Endpoints
+# ============================================
+
+@admin_bp.route('/stats', methods=['GET'])
+@admin_required
+def get_admin_stats():
+ """Get admin statistics."""
+ user_count = User.query.count()
+ active_users = User.query.filter_by(is_active=True).count()
+ admin_count = User.query.filter_by(role=User.ROLE_ADMIN).count()
+ developer_count = User.query.filter_by(role=User.ROLE_DEVELOPER).count()
+ viewer_count = User.query.filter_by(role=User.ROLE_VIEWER).count()
+
+ # Recent logins
+ recent_logins = AuditLog.query.filter_by(
+ action=AuditLog.ACTION_LOGIN
+ ).order_by(AuditLog.created_at.desc()).limit(10).all()
+
+ return jsonify({
+ 'users': {
+ 'total': user_count,
+ 'active': active_users,
+ 'by_role': {
+ 'admin': admin_count,
+ 'developer': developer_count,
+ 'viewer': viewer_count
+ }
+ },
+ 'recent_logins': [log.to_dict() for log in recent_logins]
+ }), 200
diff --git a/backend/app/api/auth.py b/backend/app/api/auth.py
index 14c338ae..72291799 100644
--- a/backend/app/api/auth.py
+++ b/backend/app/api/auth.py
@@ -8,11 +8,25 @@ from flask_jwt_extended import (
get_jwt
)
from app import db, limiter
-from app.models import User
+from app.models import User, AuditLog
+from app.services.settings_service import SettingsService
+from app.services.audit_service import AuditService
auth_bp = Blueprint('auth', __name__)
+@auth_bp.route('/setup-status', methods=['GET'])
+def get_setup_status():
+ """Check if initial setup is needed and if registration is enabled."""
+ needs_setup = SettingsService.needs_setup()
+ registration_enabled = SettingsService.is_registration_enabled()
+
+ return jsonify({
+ 'needs_setup': needs_setup,
+ 'registration_enabled': registration_enabled
+ }), 200
+
+
@auth_bp.route('/register', methods=['POST'])
@limiter.limit("3 per minute")
def register():
@@ -21,6 +35,11 @@ def register():
if not data:
return jsonify({'error': 'No data provided'}), 400
+ # Check if registration is allowed
+ is_first_user = User.query.count() == 0
+ if not is_first_user and not SettingsService.is_registration_enabled():
+ return jsonify({'error': 'Registration is disabled'}), 403
+
email = data.get('email')
username = data.get('username')
password = data.get('password')
@@ -37,19 +56,29 @@ def register():
if len(password) < 8:
return jsonify({'error': 'Password must be at least 8 characters'}), 400
- # First user becomes admin
- is_first_user = User.query.count() == 0
-
user = User(
email=email,
username=username,
- role='admin' if is_first_user else 'user'
+ role=User.ROLE_ADMIN if is_first_user else User.ROLE_DEVELOPER
)
user.set_password(password)
db.session.add(user)
db.session.commit()
+ # Mark setup as complete if this is the first user
+ if is_first_user:
+ SettingsService.complete_setup(user_id=user.id)
+
+ # Log the user creation
+ AuditService.log_user_action(
+ action=AuditLog.ACTION_USER_CREATE,
+ user_id=user.id,
+ target_user_id=user.id,
+ details={'username': username, 'role': user.role, 'self_registration': True}
+ )
+ db.session.commit()
+
access_token = create_access_token(identity=user.id)
refresh_token = create_refresh_token(identity=user.id)
@@ -57,7 +86,8 @@ def register():
'message': 'User registered successfully',
'user': user.to_dict(),
'access_token': access_token,
- 'refresh_token': refresh_token
+ 'refresh_token': refresh_token,
+ 'is_first_user': is_first_user
}), 201
@@ -88,10 +118,13 @@ def login():
# Record failed login attempt
if user:
user.record_failed_login()
+ AuditService.log_login(user.id, success=False, details={'reason': 'invalid_password'})
db.session.commit()
return jsonify({'error': 'Invalid email or password'}), 401
if not user.is_active:
+ AuditService.log_login(user.id, success=False, details={'reason': 'account_deactivated'})
+ db.session.commit()
return jsonify({'error': 'Account is deactivated'}), 403
# Check if 2FA is enabled
@@ -112,6 +145,11 @@ def login():
# No 2FA - proceed with normal login
user.reset_failed_login()
+ user.last_login_at = datetime.utcnow()
+ db.session.commit()
+
+ # Log successful login
+ AuditService.log_login(user.id, success=True)
db.session.commit()
access_token = create_access_token(identity=user.id)
diff --git a/backend/app/middleware/rbac.py b/backend/app/middleware/rbac.py
new file mode 100644
index 00000000..deb2bf63
--- /dev/null
+++ b/backend/app/middleware/rbac.py
@@ -0,0 +1,108 @@
+"""Role-Based Access Control middleware and decorators."""
+from functools import wraps
+from flask import jsonify
+from flask_jwt_extended import jwt_required, get_jwt_identity
+from app.models import User
+
+
+def get_current_user():
+ """Get the current authenticated user."""
+ user_id = get_jwt_identity()
+ if user_id:
+ return User.query.get(user_id)
+ return None
+
+
+def require_role(*allowed_roles):
+ """
+ Decorator that requires the user to have one of the specified roles.
+
+ Usage:
+ @require_role('admin', 'developer')
+ def my_endpoint():
+ ...
+ """
+ def decorator(fn):
+ @wraps(fn)
+ @jwt_required()
+ def wrapper(*args, **kwargs):
+ user = get_current_user()
+ if not user:
+ return jsonify({'error': 'User not found'}), 404
+ if not user.is_active:
+ return jsonify({'error': 'Account is deactivated'}), 403
+ if user.role not in allowed_roles:
+ return jsonify({'error': 'Insufficient permissions'}), 403
+ return fn(*args, **kwargs)
+ return wrapper
+ return decorator
+
+
+def admin_required(fn):
+ """
+ Decorator that requires admin role.
+
+ Usage:
+ @admin_required
+ def admin_only_endpoint():
+ ...
+ """
+ @wraps(fn)
+ @jwt_required()
+ def wrapper(*args, **kwargs):
+ user = get_current_user()
+ if not user:
+ return jsonify({'error': 'User not found'}), 404
+ if not user.is_active:
+ return jsonify({'error': 'Account is deactivated'}), 403
+ if not user.is_admin:
+ return jsonify({'error': 'Admin access required'}), 403
+ return fn(*args, **kwargs)
+ return wrapper
+
+
+def developer_required(fn):
+ """
+ Decorator that requires developer role or higher (admin or developer).
+
+ Usage:
+ @developer_required
+ def developer_endpoint():
+ ...
+ """
+ @wraps(fn)
+ @jwt_required()
+ def wrapper(*args, **kwargs):
+ user = get_current_user()
+ if not user:
+ return jsonify({'error': 'User not found'}), 404
+ if not user.is_active:
+ return jsonify({'error': 'Account is deactivated'}), 403
+ if not user.is_developer:
+ return jsonify({'error': 'Developer access required'}), 403
+ return fn(*args, **kwargs)
+ return wrapper
+
+
+def viewer_required(fn):
+ """
+ Decorator that requires viewer role or higher (any valid role).
+ Essentially just requires authentication and active account.
+
+ Usage:
+ @viewer_required
+ def viewer_endpoint():
+ ...
+ """
+ @wraps(fn)
+ @jwt_required()
+ def wrapper(*args, **kwargs):
+ user = get_current_user()
+ if not user:
+ return jsonify({'error': 'User not found'}), 404
+ if not user.is_active:
+ return jsonify({'error': 'Account is deactivated'}), 403
+ if not user.is_viewer:
+ return jsonify({'error': 'Access denied'}), 403
+ return fn(*args, **kwargs)
+ return wrapper
diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py
index 8095630d..b07a795b 100644
--- a/backend/app/models/__init__.py
+++ b/backend/app/models/__init__.py
@@ -4,5 +4,10 @@ from app.models.domain import Domain
from app.models.env_variable import EnvironmentVariable, EnvironmentVariableHistory
from app.models.notification_preferences import NotificationPreferences
from app.models.deployment import Deployment, DeploymentDiff
+from app.models.system_settings import SystemSettings
+from app.models.audit_log import AuditLog
-__all__ = ['User', 'Application', 'Domain', 'EnvironmentVariable', 'EnvironmentVariableHistory', 'NotificationPreferences', 'Deployment', 'DeploymentDiff']
+__all__ = [
+ 'User', 'Application', 'Domain', 'EnvironmentVariable', 'EnvironmentVariableHistory',
+ 'NotificationPreferences', 'Deployment', 'DeploymentDiff', 'SystemSettings', 'AuditLog'
+]
diff --git a/backend/app/models/audit_log.py b/backend/app/models/audit_log.py
new file mode 100644
index 00000000..b6dc0ab9
--- /dev/null
+++ b/backend/app/models/audit_log.py
@@ -0,0 +1,90 @@
+from datetime import datetime
+from app import db
+import json
+
+
+class AuditLog(db.Model):
+ """Audit log for tracking user actions."""
+ __tablename__ = 'audit_logs'
+
+ id = db.Column(db.Integer, primary_key=True)
+ action = db.Column(db.String(100), nullable=False, index=True)
+ user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=True)
+ target_type = db.Column(db.String(50), nullable=True) # user, app, setting, etc.
+ target_id = db.Column(db.Integer, nullable=True)
+ details = db.Column(db.Text, nullable=True) # JSON string
+ ip_address = db.Column(db.String(45), nullable=True) # IPv6 compatible
+ user_agent = db.Column(db.String(500), nullable=True)
+ created_at = db.Column(db.DateTime, default=datetime.utcnow, index=True)
+
+ # Relationship to user
+ user = db.relationship('User', foreign_keys=[user_id])
+
+ # Common action types
+ ACTION_LOGIN = 'user.login'
+ ACTION_LOGIN_FAILED = 'user.login_failed'
+ ACTION_LOGOUT = 'user.logout'
+ ACTION_USER_CREATE = 'user.create'
+ ACTION_USER_UPDATE = 'user.update'
+ ACTION_USER_DELETE = 'user.delete'
+ ACTION_USER_DISABLE = 'user.disable'
+ ACTION_USER_ENABLE = 'user.enable'
+ ACTION_SETTINGS_UPDATE = 'settings.update'
+ ACTION_APP_CREATE = 'app.create'
+ ACTION_APP_UPDATE = 'app.update'
+ ACTION_APP_DELETE = 'app.delete'
+ ACTION_APP_START = 'app.start'
+ ACTION_APP_STOP = 'app.stop'
+ ACTION_APP_RESTART = 'app.restart'
+ ACTION_DEPLOY = 'app.deploy'
+ ACTION_BACKUP_CREATE = 'backup.create'
+ ACTION_BACKUP_RESTORE = 'backup.restore'
+
+ def get_details(self):
+ """Return parsed details JSON."""
+ if self.details:
+ try:
+ return json.loads(self.details)
+ except (json.JSONDecodeError, TypeError):
+ return {}
+ return {}
+
+ def set_details(self, details_dict):
+ """Set details from a dictionary."""
+ if details_dict:
+ self.details = json.dumps(details_dict)
+ else:
+ self.details = None
+
+ def to_dict(self):
+ return {
+ 'id': self.id,
+ 'action': self.action,
+ 'user_id': self.user_id,
+ 'username': self.user.username if self.user else None,
+ 'target_type': self.target_type,
+ 'target_id': self.target_id,
+ 'details': self.get_details(),
+ 'ip_address': self.ip_address,
+ 'user_agent': self.user_agent,
+ 'created_at': self.created_at.isoformat() if self.created_at else None
+ }
+
+ @staticmethod
+ def log(action, user_id=None, target_type=None, target_id=None,
+ details=None, ip_address=None, user_agent=None):
+ """Create an audit log entry."""
+ log_entry = AuditLog(
+ action=action,
+ user_id=user_id,
+ target_type=target_type,
+ target_id=target_id,
+ ip_address=ip_address,
+ user_agent=user_agent
+ )
+ log_entry.set_details(details)
+ db.session.add(log_entry)
+ return log_entry
+
+ def __repr__(self):
+ return f'<AuditLog {self.action} by user {self.user_id}>'
diff --git a/backend/app/models/system_settings.py b/backend/app/models/system_settings.py
new file mode 100644
index 00000000..04ee92cb
--- /dev/null
+++ b/backend/app/models/system_settings.py
@@ -0,0 +1,81 @@
+from datetime import datetime
+from app import db
+
+
+class SystemSettings(db.Model):
+ """Key-value store for system-wide settings."""
+ __tablename__ = 'system_settings'
+
+ id = db.Column(db.Integer, primary_key=True)
+ key = db.Column(db.String(100), unique=True, nullable=False, index=True)
+ value = db.Column(db.Text, nullable=True)
+ value_type = db.Column(db.String(20), default='string') # string, boolean, integer, json
+ description = db.Column(db.String(500), nullable=True)
+ updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
+ updated_by = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=True)
+
+ # Relationship to user who last updated
+ updated_by_user = db.relationship('User', foreign_keys=[updated_by])
+
+ def get_typed_value(self):
+ """Return the value converted to its appropriate type."""
+ if self.value is None:
+ return None
+ if self.value_type == 'boolean':
+ return self.value.lower() in ('true', '1', 'yes')
+ if self.value_type == 'integer':
+ return int(self.value)
+ if self.value_type == 'json':
+ import json
+ return json.loads(self.value)
+ return self.value
+
+ def set_typed_value(self, value):
+ """Set the value, converting from its type to string storage."""
+ if value is None:
+ self.value = None
+ elif self.value_type == 'boolean':
+ self.value = 'true' if value else 'false'
+ elif self.value_type == 'integer':
+ self.value = str(int(value))
+ elif self.value_type == 'json':
+ import json
+ self.value = json.dumps(value)
+ else:
+ self.value = str(value)
+
+ def to_dict(self):
+ return {
+ 'id': self.id,
+ 'key': self.key,
+ 'value': self.get_typed_value(),
+ 'value_type': self.value_type,
+ 'description': self.description,
+ 'updated_at': self.updated_at.isoformat() if self.updated_at else None,
+ 'updated_by': self.updated_by
+ }
+
+ @staticmethod
+ def get(key, default=None):
+ """Get a setting value by key."""
+ setting = SystemSettings.query.filter_by(key=key).first()
+ if setting:
+ return setting.get_typed_value()
+ return default
+
+ @staticmethod
+ def set(key, value, value_type='string', description=None, user_id=None):
+ """Set a setting value by key."""
+ setting = SystemSettings.query.filter_by(key=key).first()
+ if not setting:
+ setting = SystemSettings(key=key, value_type=value_type, description=description)
+ db.session.add(setting)
+ setting.set_typed_value(value)
+ if description is not None:
+ setting.description = description
+ if user_id is not None:
+ setting.updated_by = user_id
+ return setting
+
+ def __repr__(self):
+ return f'<SystemSettings {self.key}={self.value}>'
diff --git a/backend/app/models/user.py b/backend/app/models/user.py
index 6fd096df..e5762a94 100644
--- a/backend/app/models/user.py
+++ b/backend/app/models/user.py
@@ -7,14 +7,22 @@ import json
class User(db.Model):
__tablename__ = 'users'
+ # Role constants
+ ROLE_ADMIN = 'admin'
+ ROLE_DEVELOPER = 'developer'
+ ROLE_VIEWER = 'viewer'
+ VALID_ROLES = [ROLE_ADMIN, ROLE_DEVELOPER, ROLE_VIEWER]
+
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(120), unique=True, nullable=False, index=True)
username = db.Column(db.String(80), unique=True, nullable=False, index=True)
password_hash = db.Column(db.String(256), nullable=False)
- role = db.Column(db.String(20), default='user') # 'admin' or 'user'
+ role = db.Column(db.String(20), default='developer') # 'admin', 'developer', 'viewer'
is_active = db.Column(db.Boolean, default=True)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
+ last_login_at = db.Column(db.DateTime, nullable=True)
+ created_by = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=True)
# Account lockout fields
failed_login_count = db.Column(db.Integer, default=0)
@@ -63,6 +71,25 @@ class User(db.Model):
def check_password(self, password):
return check_password_hash(self.password_hash, password)
+ @property
+ def is_admin(self):
+ """Check if user has admin role."""
+ return self.role == self.ROLE_ADMIN
+
+ @property
+ def is_developer(self):
+ """Check if user has developer role or higher."""
+ return self.role in [self.ROLE_ADMIN, self.ROLE_DEVELOPER]
+
+ @property
+ def is_viewer(self):
+ """Check if user has viewer role or higher (all roles)."""
+ return self.role in self.VALID_ROLES
+
+ def has_role(self, *roles):
+ """Check if user has any of the specified roles."""
+ return self.role in roles
+
def to_dict(self):
return {
'id': self.id,
@@ -72,7 +99,9 @@ class User(db.Model):
'is_active': self.is_active,
'totp_enabled': self.totp_enabled,
'created_at': self.created_at.isoformat(),
- 'updated_at': self.updated_at.isoformat()
+ 'updated_at': self.updated_at.isoformat(),
+ 'last_login_at': self.last_login_at.isoformat() if self.last_login_at else None,
+ 'created_by': self.created_by
}
def get_backup_codes(self):
diff --git a/backend/app/services/audit_service.py b/backend/app/services/audit_service.py
new file mode 100644
index 00000000..e0ee93d6
--- /dev/null
+++ b/backend/app/services/audit_service.py
@@ -0,0 +1,154 @@
+"""Service for audit logging operations."""
+from flask import request
+from app import db
+from app.models import AuditLog
+
+
+class AuditService:
+ """Service for creating and querying audit logs."""
+
+ @staticmethod
+ def get_request_info():
+ """Extract IP address and user agent from the current request."""
+ ip_address = request.remote_addr
+ # Handle proxy headers
+ if request.headers.get('X-Forwarded-For'):
+ ip_address = request.headers.get('X-Forwarded-For').split(',')[0].strip()
+ elif request.headers.get('X-Real-IP'):
+ ip_address = request.headers.get('X-Real-IP')
+
+ user_agent = request.headers.get('User-Agent', '')[:500]
+ return ip_address, user_agent
+
+ @staticmethod
+ def log(action, user_id=None, target_type=None, target_id=None, details=None):
+ """
+ Create an audit log entry with request context.
+
+ Args:
+ action: The action being logged (use AuditLog.ACTION_* constants)
+ user_id: ID of the user performing the action
+ target_type: Type of the target (e.g., 'user', 'app', 'setting')
+ target_id: ID of the target entity
+ details: Dictionary with additional details
+
+ Returns:
+ The created AuditLog entry
+ """
+ ip_address, user_agent = AuditService.get_request_info()
+
+ log_entry = AuditLog.log(
+ action=action,
+ user_id=user_id,
+ target_type=target_type,
+ target_id=target_id,
+ details=details,
+ ip_address=ip_address,
+ user_agent=user_agent
+ )
+ return log_entry
+
+ @staticmethod
+ def log_login(user_id, success=True, details=None):
+ """Log a login attempt."""
+ action = AuditLog.ACTION_LOGIN if success else AuditLog.ACTION_LOGIN_FAILED
+ return AuditService.log(
+ action=action,
+ user_id=user_id,
+ target_type='user',
+ target_id=user_id,
+ details=details
+ )
+
+ @staticmethod
+ def log_user_action(action, user_id, target_user_id, details=None):
+ """Log a user management action."""
+ return AuditService.log(
+ action=action,
+ user_id=user_id,
+ target_type='user',
+ target_id=target_user_id,
+ details=details
+ )
+
+ @staticmethod
+ def log_settings_change(user_id, key, old_value, new_value):
+ """Log a settings change."""
+ return AuditService.log(
+ action=AuditLog.ACTION_SETTINGS_UPDATE,
+ user_id=user_id,
+ target_type='setting',
+ details={'key': key, 'old_value': old_value, 'new_value': new_value}
+ )
+
+ @staticmethod
+ def log_app_action(action, user_id, app_id, app_name=None, details=None):
+ """Log an application action."""
+ log_details = details or {}
+ if app_name:
+ log_details['app_name'] = app_name
+ return AuditService.log(
+ action=action,
+ user_id=user_id,
+ target_type='app',
+ target_id=app_id,
+ details=log_details
+ )
+
+ @staticmethod
+ def get_logs(page=1, per_page=50, action=None, user_id=None,
+ target_type=None, start_date=None, end_date=None):
+ """
+ Query audit logs with filtering and pagination.
+
+ Args:
+ page: Page number (1-indexed)
+ per_page: Number of results per page
+ action: Filter by action type
+ user_id: Filter by user who performed action
+ target_type: Filter by target type
+ start_date: Filter logs after this date
+ end_date: Filter logs before this date
+
+ Returns:
+ Pagination object with logs
+ """
+ query = AuditLog.query.order_by(AuditLog.created_at.desc())
+
+ if action:
+ query = query.filter(AuditLog.action == action)
+ if user_id:
+ query = query.filter(AuditLog.user_id == user_id)
+ if target_type:
+ query = query.filter(AuditLog.target_type == target_type)
+ if start_date:
+ query = query.filter(AuditLog.created_at >= start_date)
+ if end_date:
+ query = query.filter(AuditLog.created_at <= end_date)
+
+ return query.paginate(page=page, per_page=per_page, error_out=False)
+
+ @staticmethod
+ def get_recent_logs(limit=100):
+ """Get the most recent audit logs."""
+ return AuditLog.query.order_by(
+ AuditLog.created_at.desc()
+ ).limit(limit).all()
+
+ @staticmethod
+ def get_user_activity(user_id, limit=50):
+ """Get recent activity for a specific user."""
+ return AuditLog.query.filter_by(
+ user_id=user_id
+ ).order_by(
+ AuditLog.created_at.desc()
+ ).limit(limit).all()
+
+ @staticmethod
+ def cleanup_old_logs(days=90):
+ """Delete audit logs older than specified days."""
+ from datetime import datetime, timedelta
+ cutoff = datetime.utcnow() - timedelta(days=days)
+ deleted = AuditLog.query.filter(AuditLog.created_at < cutoff).delete()
+ db.session.commit()
+ return deleted
diff --git a/backend/app/services/settings_service.py b/backend/app/services/settings_service.py
new file mode 100644
index 00000000..fdfb82b7
--- /dev/null
+++ b/backend/app/services/settings_service.py
@@ -0,0 +1,136 @@
+"""Service for system settings operations."""
+from app import db
+from app.models import SystemSettings, User
+
+
+class SettingsService:
+ """Service for managing system settings."""
+
+ # Default settings with their types and descriptions
+ DEFAULT_SETTINGS = {
+ 'setup_completed': {
+ 'value': False,
+ 'type': 'boolean',
+ 'description': 'Whether initial setup has been completed'
+ },
+ 'registration_enabled': {
+ 'value': False,
+ 'type': 'boolean',
+ 'description': 'Allow public user registration'
+ },
+ 'instance_name': {
+ 'value': 'ServerKit',
+ 'type': 'string',
+ 'description': 'Name of this ServerKit instance'
+ },
+ 'audit_log_retention_days': {
+ 'value': 90,
+ 'type': 'integer',
+ 'description': 'Number of days to retain audit logs'
+ }
+ }
+
+ @staticmethod
+ def get(key, default=None):
+ """Get a setting value by key."""
+ return SystemSettings.get(key, default)
+
+ @staticmethod
+ def set(key, value, user_id=None):
+ """Set a setting value by key."""
+ # Get the expected type from defaults
+ default_config = SettingsService.DEFAULT_SETTINGS.get(key, {})
+ value_type = default_config.get('type', 'string')
+ description = default_config.get('description')
+
+ setting = SystemSettings.set(
+ key=key,
+ value=value,
+ value_type=value_type,
+ description=description,
+ user_id=user_id
+ )
+ db.session.commit()
+ return setting
+
+ @staticmethod
+ def get_all():
+ """Get all settings as a dictionary."""
+ settings = SystemSettings.query.all()
+ result = {}
+ for setting in settings:
+ result[setting.key] = setting.get_typed_value()
+ return result
+
+ @staticmethod
+ def get_all_with_metadata():
+ """Get all settings with full metadata."""
+ settings = SystemSettings.query.all()
+ return [setting.to_dict() for setting in settings]
+
+ @staticmethod
+ def initialize_defaults():
+ """Initialize default settings if they don't exist."""
+ for key, config in SettingsService.DEFAULT_SETTINGS.items():
+ existing = SystemSettings.query.filter_by(key=key).first()
+ if not existing:
+ SystemSettings.set(
+ key=key,
+ value=config['value'],
+ value_type=config['type'],
+ description=config['description']
+ )
+ db.session.commit()
+
+ @staticmethod
+ def needs_setup():
+ """Check if initial setup is required."""
+ # If no users exist, setup is needed
+ user_count = User.query.count()
+ if user_count == 0:
+ return True
+
+ # Check setup_completed setting
+ setup_completed = SettingsService.get('setup_completed', False)
+ return not setup_completed
+
+ @staticmethod
+ def complete_setup(user_id=None):
+ """Mark the initial setup as completed."""
+ SettingsService.set('setup_completed', True, user_id=user_id)
+
+ @staticmethod
+ def is_registration_enabled():
+ """Check if public registration is enabled."""
+ # If no users exist, always allow registration (for first user)
+ user_count = User.query.count()
+ if user_count == 0:
+ return True
+ return SettingsService.get('registration_enabled', False)
+
+ @staticmethod
+ def set_registration_enabled(enabled, user_id=None):
+ """Enable or disable public registration."""
+ SettingsService.set('registration_enabled', enabled, user_id=user_id)
+
+ @staticmethod
+ def migrate_legacy_roles():
+ """Migrate users with 'user' role to 'developer' role."""
+ users_to_migrate = User.query.filter_by(role='user').all()
+ count = 0
+ for user in users_to_migrate:
+ user.role = User.ROLE_DEVELOPER
+ count += 1
+ if count > 0:
+ db.session.commit()
+ return count
+
+ @staticmethod
+ def ensure_admin_exists():
+ """
+ Check if at least one admin exists.
+ If users exist but no admins, something is wrong.
+ """
+ admin_count = User.query.filter_by(role=User.ROLE_ADMIN).count()
+ user_count = User.query.count()
+ return admin_count > 0 or user_count == 0
diff --git a/frontend/dist/index.html b/frontend/dist/index.html
index 3c74aea7..15412e89 100644
--- a/frontend/dist/index.html
+++ b/frontend/dist/index.html
@@ -6,8 +6,8 @@
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>React Dashboard Template</title>
- <script type="module" crossorigin src="/assets/index-ClQee1fk.js"></script>
- <link rel="stylesheet" crossorigin href="/assets/index-DytIiSKP.css">
+ <script type="module" crossorigin src="/assets/index-D2kW3a5a.js"></script>
+ <link rel="stylesheet" crossorigin href="/assets/index-B1Vn4ZuG.css">
</head>
<body>
diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx
index 4c8d6090..fb978a05 100644
--- a/frontend/src/App.jsx
+++ b/frontend/src/App.jsx
@@ -7,6 +7,7 @@ import DashboardLayout from './layouts/DashboardLayout';
import Dashboard from './pages/Dashboard';
import Login from './pages/Login';
import Register from './pages/Register';
+import Setup from './pages/Setup';
import Applications from './pages/Applications';
import ApplicationDetail from './pages/ApplicationDetail';
import Docker from './pages/Docker';
@@ -25,38 +26,72 @@ import Security from './pages/Security';
import Templates from './pages/Templates';
function PrivateRoute({ children }) {
- const { isAuthenticated, loading } = useAuth();
+ const { isAuthenticated, loading, needsSetup } = useAuth();
if (loading) {
return <div className="loading">Loading...</div>;
}
+ // If setup is needed, redirect to setup
+ if (needsSetup) {
+ return <Navigate to="/setup" />;
+ }
+
return isAuthenticated ? children : <Navigate to="/login" />;
}
function PublicRoute({ children }) {
- const { isAuthenticated, loading } = useAuth();
+ const { isAuthenticated, loading, needsSetup } = useAuth();
if (loading) {
return <div className="loading">Loading...</div>;
}
+ // If setup is needed, redirect to setup
+ if (needsSetup) {
+ return <Navigate to="/setup" />;
+ }
+
return isAuthenticated ? <Navigate to="/" /> : children;
}
+function SetupRoute({ children }) {
+ const { loading, needsSetup, isAuthenticated } = useAuth();
+
+ if (loading) {
+ return <div className="loading">Loading...</div>;
+ }
+
+ // If setup is not needed, redirect appropriately
+ if (!needsSetup) {
+ return isAuthenticated ? <Navigate to="/" /> : <Navigate to="/login" />;
+ }
+
+ return children;
+}
+
function AppRoutes() {
+ const { registrationEnabled } = useAuth();
+
return (
<Routes>
+ <Route path="/setup" element={
+ <SetupRoute>
+ <Setup />
+ </SetupRoute>
+ } />
<Route path="/login" element={
<PublicRoute>
<Login />
</PublicRoute>
} />
- <Route path="/register" element={
- <PublicRoute>
- <Register />
- </PublicRoute>
- } />
+ {registrationEnabled && (
+ <Route path="/register" element={
+ <PublicRoute>
+ <Register />
+ </PublicRoute>
+ } />
+ )}
<Route path="/" element={
<PrivateRoute>
<DashboardLayout />
diff --git a/frontend/src/components/Sidebar.jsx b/frontend/src/components/Sidebar.jsx
index 6d77eda1..dd2e4d62 100644
--- a/frontend/src/components/Sidebar.jsx
+++ b/frontend/src/components/Sidebar.jsx
@@ -16,148 +16,150 @@ const Sidebar = () => {
ServerKit
</div>
- <div className="menu-label">Overview</div>
- <nav className="nav">
- <NavLink to="/" className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`} end>
- <svg viewBox="0 0 24 24">
- <rect x="3" y="3" width="7" height="7"/>
- <rect x="14" y="3" width="7" height="7"/>
- <rect x="14" y="14" width="7" height="7"/>
- <rect x="3" y="14" width="7" height="7"/>
- </svg>
- Dashboard
- </NavLink>
- </nav>
+ <div className="sidebar-nav-container">
+ <div className="menu-label">Overview</div>
+ <nav className="nav">
+ <NavLink to="/" className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`} end>
+ <svg viewBox="0 0 24 24">
+ <rect x="3" y="3" width="7" height="7"/>
+ <rect x="14" y="3" width="7" height="7"/>
+ <rect x="14" y="14" width="7" height="7"/>
+ <rect x="3" y="14" width="7" height="7"/>
+ </svg>
+ Dashboard
+ </NavLink>
+ </nav>
- <div className="menu-label">Infrastructure</div>
- <nav className="nav">
- <NavLink to="/domains" className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}>
- <svg viewBox="0 0 24 24">
- <circle cx="12" cy="12" r="10"/>
- <line x1="2" y1="12" x2="22" y2="12"/>
- <path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/>
- </svg>
- Domains & Sites
- </NavLink>
- <NavLink to="/apps" className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}>
- <svg viewBox="0 0 24 24">
- <path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/>
- <polyline points="3.27 6.96 12 12.01 20.73 6.96"/>
- <line x1="12" y1="22.08" x2="12" y2="12"/>
- </svg>
- Applications
- </NavLink>
- <NavLink to="/templates" className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}>
- <svg viewBox="0 0 24 24">
- <rect x="3" y="3" width="7" height="9"/>
- <rect x="14" y="3" width="7" height="5"/>
- <rect x="14" y="12" width="7" height="9"/>
- <rect x="3" y="16" width="7" height="5"/>
- </svg>
- Templates
- </NavLink>
- <NavLink to="/databases" className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}>
- <svg viewBox="0 0 24 24">
- <ellipse cx="12" cy="5" rx="9" ry="3"/>
- <path d="M21 12c0 1.66-4 3-9 3s-9-1.34-9-3"/>
- <path d="M3 5v14c0 1.66 4 3 9 3s9-1.34 9-3V5"/>
- </svg>
- Databases
- </NavLink>
- <NavLink to="/ssl" className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}>
- <svg viewBox="0 0 24 24">
- <rect x="3" y="11" width="18" height="11" rx="2" ry="2"/>
- <path d="M7 11V7a5 5 0 0 1 10 0v4"/>
- </svg>
- SSL Certificates
- </NavLink>
- <NavLink to="/docker" className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}>
- <svg viewBox="0 0 24 24">
- <rect x="2" y="7" width="6" height="6" rx="1"/>
- <rect x="9" y="7" width="6" height="6" rx="1"/>
- <rect x="16" y="7" width="6" height="6" rx="1"/>
- <rect x="2" y="14" width="6" height="6" rx="1"/>
- <rect x="9" y="14" width="6" height="6" rx="1"/>
- </svg>
- Docker
- </NavLink>
- <NavLink to="/php" className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}>
- <svg viewBox="0 0 24 24">
- <ellipse cx="12" cy="12" rx="10" ry="6"/>
- <text x="12" y="15" textAnchor="middle" fontSize="8" fill="currentColor" stroke="none">php</text>
- </svg>
- PHP
- </NavLink>
- <NavLink to="/firewall" className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}>
- <svg viewBox="0 0 24 24">
- <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
- </svg>
- Firewall
- </NavLink>
- </nav>
+ <div className="menu-label">Infrastructure</div>
+ <nav className="nav">
+ <NavLink to="/domains" className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}>
+ <svg viewBox="0 0 24 24">
+ <circle cx="12" cy="12" r="10"/>
+ <line x1="2" y1="12" x2="22" y2="12"/>
+ <path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/>
+ </svg>
+ Domains & Sites
+ </NavLink>
+ <NavLink to="/apps" className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}>
+ <svg viewBox="0 0 24 24">
+ <path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/>
+ <polyline points="3.27 6.96 12 12.01 20.73 6.96"/>
+ <line x1="12" y1="22.08" x2="12" y2="12"/>
+ </svg>
+ Applications
+ </NavLink>
+ <NavLink to="/templates" className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}>
+ <svg viewBox="0 0 24 24">
+ <rect x="3" y="3" width="7" height="9"/>
+ <rect x="14" y="3" width="7" height="5"/>
+ <rect x="14" y="12" width="7" height="9"/>
+ <rect x="3" y="16" width="7" height="5"/>
+ </svg>
+ Templates
+ </NavLink>
+ <NavLink to="/databases" className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}>
+ <svg viewBox="0 0 24 24">
+ <ellipse cx="12" cy="5" rx="9" ry="3"/>
+ <path d="M21 12c0 1.66-4 3-9 3s-9-1.34-9-3"/>
+ <path d="M3 5v14c0 1.66 4 3 9 3s9-1.34 9-3V5"/>
+ </svg>
+ Databases
+ </NavLink>
+ <NavLink to="/ssl" className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}>
+ <svg viewBox="0 0 24 24">
+ <rect x="3" y="11" width="18" height="11" rx="2" ry="2"/>
+ <path d="M7 11V7a5 5 0 0 1 10 0v4"/>
+ </svg>
+ SSL Certificates
+ </NavLink>
+ <NavLink to="/docker" className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}>
+ <svg viewBox="0 0 24 24">
+ <rect x="2" y="7" width="6" height="6" rx="1"/>
+ <rect x="9" y="7" width="6" height="6" rx="1"/>
+ <rect x="16" y="7" width="6" height="6" rx="1"/>
+ <rect x="2" y="14" width="6" height="6" rx="1"/>
+ <rect x="9" y="14" width="6" height="6" rx="1"/>
+ </svg>
+ Docker
+ </NavLink>
+ <NavLink to="/php" className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}>
+ <svg viewBox="0 0 24 24">
+ <ellipse cx="12" cy="12" rx="10" ry="6"/>
+ <text x="12" y="15" textAnchor="middle" fontSize="8" fill="currentColor" stroke="none">php</text>
+ </svg>
+ PHP
+ </NavLink>
+ <NavLink to="/firewall" className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}>
+ <svg viewBox="0 0 24 24">
+ <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
+ </svg>
+ Firewall
+ </NavLink>
+ </nav>
- <div className="menu-label">Operations</div>
- <nav className="nav">
- <NavLink to="/files" className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}>
- <svg viewBox="0 0 24 24">
- <path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/>
- </svg>
- File Manager
- </NavLink>
- <NavLink to="/ftp" className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}>
- <svg viewBox="0 0 24 24">
- <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
- <polyline points="17 8 12 3 7 8"/>
- <line x1="12" y1="3" x2="12" y2="15"/>
- </svg>
- FTP Server
- </NavLink>
- <NavLink to="/monitoring" className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}>
- <svg viewBox="0 0 24 24">
- <path d="M22 12h-4l-3 9L9 3l-3 9H2"/>
- </svg>
- Monitoring
- </NavLink>
- <NavLink to="/backups" className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}>
- <svg viewBox="0 0 24 24">
- <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
- <polyline points="7 10 12 15 17 10"/>
- <line x1="12" y1="15" x2="12" y2="3"/>
- </svg>
- Backups
- </NavLink>
- <NavLink to="/cron" className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}>
- <svg viewBox="0 0 24 24">
- <circle cx="12" cy="12" r="10"/>
- <polyline points="12 6 12 12 16 14"/>
- </svg>
- Cron Jobs
- </NavLink>
- <NavLink to="/security" className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}>
- <svg viewBox="0 0 24 24">
- <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
- <path d="M12 8v4m0 4h.01"/>
- </svg>
- Security
- </NavLink>
- </nav>
+ <div className="menu-label">Operations</div>
+ <nav className="nav">
+ <NavLink to="/files" className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}>
+ <svg viewBox="0 0 24 24">
+ <path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/>
+ </svg>
+ File Manager
+ </NavLink>
+ <NavLink to="/ftp" className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}>
+ <svg viewBox="0 0 24 24">
+ <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
+ <polyline points="17 8 12 3 7 8"/>
+ <line x1="12" y1="3" x2="12" y2="15"/>
+ </svg>
+ FTP Server
+ </NavLink>
+ <NavLink to="/monitoring" className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}>
+ <svg viewBox="0 0 24 24">
+ <path d="M22 12h-4l-3 9L9 3l-3 9H2"/>
+ </svg>
+ Monitoring
+ </NavLink>
+ <NavLink to="/backups" className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}>
+ <svg viewBox="0 0 24 24">
+ <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
+ <polyline points="7 10 12 15 17 10"/>
+ <line x1="12" y1="15" x2="12" y2="3"/>
+ </svg>
+ Backups
+ </NavLink>
+ <NavLink to="/cron" className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}>
+ <svg viewBox="0 0 24 24">
+ <circle cx="12" cy="12" r="10"/>
+ <polyline points="12 6 12 12 16 14"/>
+ </svg>
+ Cron Jobs
+ </NavLink>
+ <NavLink to="/security" className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}>
+ <svg viewBox="0 0 24 24">
+ <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
+ <path d="M12 8v4m0 4h.01"/>
+ </svg>
+ Security
+ </NavLink>
+ </nav>
- <div className="menu-label">System</div>
- <nav className="nav">
- <NavLink to="/terminal" className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}>
- <svg viewBox="0 0 24 24">
- <path d="M4 17l6-6-6-6M12 19h8"/>
- </svg>
- Terminal / Logs
- </NavLink>
- <NavLink to="/settings" className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}>
- <svg viewBox="0 0 24 24">
- <circle cx="12" cy="12" r="3"/>
- <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"/>
- </svg>
- Settings
- </NavLink>
- </nav>
+ <div className="menu-label">System</div>
+ <nav className="nav">
+ <NavLink to="/terminal" className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}>
+ <svg viewBox="0 0 24 24">
+ <path d="M4 17l6-6-6-6M12 19h8"/>
+ </svg>
+ Terminal / Logs
+ </NavLink>
+ <NavLink to="/settings" className={({ isActive }) => `nav-item ${isActive ? 'active' : ''}`}>
+ <svg viewBox="0 0 24 24">
+ <circle cx="12" cy="12" r="3"/>
+ <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"/>
+ </svg>
+ Settings
+ </NavLink>
+ </nav>
+ </div>
<div className="user-profile">
<div className="avatar">
diff --git a/frontend/src/components/settings/AuditLogTab.jsx b/frontend/src/components/settings/AuditLogTab.jsx
new file mode 100644
index 00000000..d8b2aedf
--- /dev/null
+++ b/frontend/src/components/settings/AuditLogTab.jsx
@@ -0,0 +1,248 @@
+import React, { useState, useEffect } from 'react';
+import api from '../../services/api';
+
+const AuditLogTab = () => {
+ const [logs, setLogs] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState('');
+ const [pagination, setPagination] = useState({
+ page: 1,
+ perPage: 50,
+ total: 0,
+ pages: 1
+ });
+ const [filters, setFilters] = useState({
+ action: '',
+ user_id: ''
+ });
+ const [actions, setActions] = useState([]);
+
+ useEffect(() => {
+ loadLogs();
+ loadActions();
+ }, [pagination.page, filters]);
+
+ async function loadLogs() {
+ try {
+ setLoading(true);
+ const params = {
+ page: pagination.page,
+ per_page: pagination.perPage
+ };
+ if (filters.action) params.action = filters.action;
+ if (filters.user_id) params.user_id = filters.user_id;
+
+ const data = await api.getAuditLogs(params);
+ setLogs(data.logs);
+ setPagination(prev => ({
+ ...prev,
+ total: data.pagination.total,
+ pages: data.pagination.pages
+ }));
+ setError('');
+ } catch (err) {
+ setError(err.message || 'Failed to load audit logs');
+ } finally {
+ setLoading(false);
+ }
+ }
+
+ async function loadActions() {
+ try {
+ const data = await api.getAuditLogActions();
+ setActions(data.actions);
+ } catch (err) {
+ console.error('Failed to load action types:', err);
+ }
+ }
+
+ function handleFilterChange(e) {
+ const { name, value } = e.target;
+ setFilters(prev => ({ ...prev, [name]: value }));
+ setPagination(prev => ({ ...prev, page: 1 }));
+ }
+
+ function handlePageChange(newPage) {
+ setPagination(prev => ({ ...prev, page: newPage }));
+ }
+
+ function formatDate(dateString) {
+ if (!dateString) return '';
+ return new Date(dateString).toLocaleString('en-US', {
+ year: 'numeric',
+ month: 'short',
+ day: 'numeric',
+ hour: '2-digit',
+ minute: '2-digit',
+ second: '2-digit'
+ });
+ }
+
+ function getActionIcon(action) {
+ if (action.includes('login')) {
+ return (
+ <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" fill="none" strokeWidth="2">
+ <path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"/>
+ <polyline points="10 17 15 12 10 7"/>
+ <line x1="15" y1="12" x2="3" y2="12"/>
+ </svg>
+ );
+ }
+ if (action.includes('user')) {
+ return (
+ <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" fill="none" strokeWidth="2">
+ <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/>
+ <circle cx="12" cy="7" r="4"/>
+ </svg>
+ );
+ }
+ if (action.includes('app') || action.includes('deploy')) {
+ return (
+ <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" fill="none" strokeWidth="2">
+ <rect x="3" y="3" width="18" height="18" rx="2" ry="2"/>
+ <line x1="3" y1="9" x2="21" y2="9"/>
+ <line x1="9" y1="21" x2="9" y2="9"/>
+ </svg>
+ );
+ }
+ if (action.includes('setting')) {
+ return (
+ <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" fill="none" strokeWidth="2">
+ <circle cx="12" cy="12" r="3"/>
+ <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"/>
+ </svg>
+ );
+ }
+ return (
+ <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" fill="none" strokeWidth="2">
+ <circle cx="12" cy="12" r="10"/>
+ <line x1="12" y1="8" x2="12" y2="12"/>
+ <line x1="12" y1="16" x2="12.01" y2="16"/>
+ </svg>
+ );
+ }
+
+ function getActionClass(action) {
+ if (action.includes('failed') || action.includes('delete')) return 'action-danger';
+ if (action.includes('create') || action.includes('enable')) return 'action-success';
+ if (action.includes('update') || action.includes('disable')) return 'action-warning';
+ return 'action-info';
+ }
+
+ function formatActionName(action) {
+ return action.replace(/\./g, ' ').replace(/_/g, ' ');
+ }
+
+ function renderDetails(details) {
+ if (!details || Object.keys(details).length === 0) return null;
+
+ return (
+ <div className="log-details">
+ {Object.entries(details).map(([key, value]) => (
+ <span key={key} className="detail-item">
+ <span className="detail-key">{key}:</span>
+ <span className="detail-value">
+ {typeof value === 'object' ? JSON.stringify(value) : String(value)}
+ </span>
+ </span>
+ ))}
+ </div>
+ );
+ }
+
+ return (
+ <div className="audit-log-tab">
+ <div className="tab-header">
+ <div className="tab-header-content">
+ <h3>Audit Log</h3>
+ <p>Track user actions and system events</p>
+ </div>
+ </div>
+
+ <div className="filters-bar">
+ <div className="filter-group">
+ <label>Action Type</label>
+ <select name="action" value={filters.action} onChange={handleFilterChange}>
+ <option value="">All Actions</option>
+ {actions.map(action => (
+ <option key={action} value={action}>{formatActionName(action)}</option>
+ ))}
+ </select>
+ </div>
+ <button className="btn btn-ghost" onClick={() => {
+ setFilters({ action: '', user_id: '' });
+ setPagination(prev => ({ ...prev, page: 1 }));
+ }}>
+ Clear Filters
+ </button>
+ </div>
+
+ {error && <div className="error-message">{error}</div>}
+
+ {loading ? (
+ <div className="loading-state">Loading audit logs...</div>
+ ) : (
+ <>
+ <div className="audit-log-list">
+ {logs.length === 0 ? (
+ <div className="empty-state">No audit logs found</div>
+ ) : (
+ logs.map(log => (
+ <div key={log.id} className={`log-entry ${getActionClass(log.action)}`}>
+ <div className="log-icon">
+ {getActionIcon(log.action)}
+ </div>
+ <div className="log-content">
+ <div className="log-header">
+ <span className="log-action">{formatActionName(log.action)}</span>
+ <span className="log-user">
+ by {log.username || 'System'}
+ </span>
+ {log.target_type && (
+ <span className="log-target">
+ on {log.target_type} {log.target_id ? `#${log.target_id}` : ''}
+ </span>
+ )}
+ </div>
+ {renderDetails(log.details)}
+ <div className="log-meta">
+ <span className="log-time">{formatDate(log.created_at)}</span>
+ {log.ip_address && (
+ <span className="log-ip">IP: {log.ip_address}</span>
+ )}
+ </div>
+ </div>
+ </div>
+ ))
+ )}
+ </div>
+
+ {pagination.pages > 1 && (
+ <div className="pagination">
+ <button
+ className="btn btn-sm btn-ghost"
+ disabled={pagination.page <= 1}
+ onClick={() => handlePageChange(pagination.page - 1)}
+ >
+ Previous
+ </button>
+ <span className="pagination-info">
+ Page {pagination.page} of {pagination.pages}
+ ({pagination.total} total)
+ </span>
+ <button
+ className="btn btn-sm btn-ghost"
+ disabled={pagination.page >= pagination.pages}
+ onClick={() => handlePageChange(pagination.page + 1)}
+ >
+ Next
+ </button>
+ </div>
+ )}
+ </>
+ )}
+ </div>
+ );
+};
+
+export default AuditLogTab;
diff --git a/frontend/src/components/settings/UserModal.jsx b/frontend/src/components/settings/UserModal.jsx
new file mode 100644
index 00000000..b4435d87
--- /dev/null
+++ b/frontend/src/components/settings/UserModal.jsx
@@ -0,0 +1,227 @@
+import React, { useState, useEffect } from 'react';
+import { useAuth } from '../../contexts/AuthContext';
+
+const UserModal = ({ user, onSave, onClose }) => {
+ const [formData, setFormData] = useState({
+ email: '',
+ username: '',
+ password: '',
+ confirmPassword: '',
+ role: 'developer',
+ is_active: true
+ });
+ const [error, setError] = useState('');
+ const [loading, setLoading] = useState(false);
+ const { user: currentUser } = useAuth();
+
+ const isEditing = !!user;
+ const isSelf = user?.id === currentUser?.id;
+
+ useEffect(() => {
+ if (user) {
+ setFormData({
+ email: user.email || '',
+ username: user.username || '',
+ password: '',
+ confirmPassword: '',
+ role: user.role || 'developer',
+ is_active: user.is_active !== false
+ });
+ }
+ }, [user]);
+
+ function handleChange(e) {
+ const { name, value, type, checked } = e.target;
+ setFormData(prev => ({
+ ...prev,
+ [name]: type === 'checkbox' ? checked : value
+ }));
+ }
+
+ async function handleSubmit(e) {
+ e.preventDefault();
+ setError('');
+
+ // Validation
+ if (!formData.email || !formData.username) {
+ setError('Email and username are required');
+ return;
+ }
+
+ if (!isEditing && !formData.password) {
+ setError('Password is required for new users');
+ return;
+ }
+
+ if (formData.password && formData.password.length < 8) {
+ setError('Password must be at least 8 characters');
+ return;
+ }
+
+ if (formData.password && formData.password !== formData.confirmPassword) {
+ setError('Passwords do not match');
+ return;
+ }
+
+ setLoading(true);
+
+ try {
+ const userData = {
+ email: formData.email,
+ username: formData.username,
+ role: formData.role,
+ is_active: formData.is_active
+ };
+
+ // Only include password if it's been set
+ if (formData.password) {
+ userData.password = formData.password;
+ }
+
+ await onSave(userData);
+ } catch (err) {
+ setError(err.message || 'Failed to save user');
+ } finally {
+ setLoading(false);
+ }
+ }
+
+ return (
+ <div className="modal-overlay">
+ <div className="modal modal-md">
+ <div className="modal-header">
+ <h3>{isEditing ? 'Edit User' : 'Add New User'}</h3>
+ <button className="modal-close" onClick={onClose}>
+ <svg viewBox="0 0 24 24" width="20" height="20" stroke="currentColor" fill="none" strokeWidth="2">
+ <line x1="18" y1="6" x2="6" y2="18"/>
+ <line x1="6" y1="6" x2="18" y2="18"/>
+ </svg>
+ </button>
+ </div>
+
+ <form onSubmit={handleSubmit}>
+ <div className="modal-body">
+ {error && <div className="error-message">{error}</div>}
+
+ <div className="form-group">
+ <label htmlFor="email">Email</label>
+ <input
+ type="email"
+ id="email"
+ name="email"
+ value={formData.email}
+ onChange={handleChange}
+ placeholder="[email protected]"
+ required
+ />
+ </div>
+
+ <div className="form-group">
+ <label htmlFor="username">Username</label>
+ <input
+ type="text"
+ id="username"
+ name="username"
+ value={formData.username}
+ onChange={handleChange}
+ placeholder="Enter username"
+ required
+ />
+ </div>
+
+ <div className="form-row">
+ <div className="form-group">
+ <label htmlFor="password">
+ {isEditing ? 'New Password (leave blank to keep current)' : 'Password'}
+ </label>
+ <input
+ type="password"
+ id="password"
+ name="password"
+ value={formData.password}
+ onChange={handleChange}
+ placeholder={isEditing ? 'Leave blank to keep current' : 'At least 8 characters'}
+ required={!isEditing}
+ />
+ </div>
+
+ <div className="form-group">
+ <label htmlFor="confirmPassword">Confirm Password</label>
+ <input
+ type="password"
+ id="confirmPassword"
+ name="confirmPassword"
+ value={formData.confirmPassword}
+ onChange={handleChange}
+ placeholder="Confirm password"
+ required={!!formData.password}
+ />
+ </div>
+ </div>
+
+ <div className="form-group">
+ <label htmlFor="role">Role</label>
+ <select
+ id="role"
+ name="role"
+ value={formData.role}
+ onChange={handleChange}
+ disabled={isSelf}
+ >
+ <option value="admin">Admin - Full access</option>
+ <option value="developer">Developer - Manage apps and deployments</option>
+ <option value="viewer">Viewer - Read-only access</option>
+ </select>
+ {isSelf && (
+ <span className="form-help">You cannot change your own role</span>
+ )}
+ </div>
+
+ <div className="form-group">
+ <label className="checkbox-label">
+ <input
+ type="checkbox"
+ name="is_active"
+ checked={formData.is_active}
+ onChange={handleChange}
+ disabled={isSelf}
+ />
+ <span className="checkbox-text">Account is active</span>
+ </label>
+ {isSelf && (
+ <span className="form-help">You cannot deactivate your own account</span>
+ )}
+ </div>
+
+ <div className="role-descriptions">
+ <h4>Role Permissions</h4>
+ <div className="role-item">
+ <span className="role-name">Admin</span>
+ <span className="role-desc">Full system access including user management and settings</span>
+ </div>
+ <div className="role-item">
+ <span className="role-name">Developer</span>
+ <span className="role-desc">Manage applications, deployments, databases, and domains</span>
+ </div>
+ <div className="role-item">
+ <span className="role-name">Viewer</span>
+ <span className="role-desc">Read-only access to dashboards and logs</span>
+ </div>
+ </div>
+ </div>
+
+ <div className="modal-footer">
+ <button type="button" className="btn btn-ghost" onClick={onClose}>
+ Cancel
+ </button>
+ <button type="submit" className="btn btn-primary" disabled={loading}>
+ {loading ? 'Saving...' : (isEditing ? 'Save Changes' : 'Create User')}
+ </button>
+ </div>
+ </form>
+ </div>
+ </div>
+ );
+};
+
+export default UserModal;
diff --git a/frontend/src/components/settings/UsersTab.jsx b/frontend/src/components/settings/UsersTab.jsx
new file mode 100644
index 00000000..0ddf7bb3
--- /dev/null
+++ b/frontend/src/components/settings/UsersTab.jsx
@@ -0,0 +1,259 @@
+import React, { useState, useEffect } from 'react';
+import api from '../../services/api';
+import { useAuth } from '../../contexts/AuthContext';
+import UserModal from './UserModal';
+
+const UsersTab = () => {
+ const [users, setUsers] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState('');
+ const [showModal, setShowModal] = useState(false);
+ const [editingUser, setEditingUser] = useState(null);
+ const [deleteConfirm, setDeleteConfirm] = useState(null);
+ const { user: currentUser } = useAuth();
+
+ useEffect(() => {
+ loadUsers();
+ }, []);
+
+ async function loadUsers() {
+ try {
+ setLoading(true);
+ const data = await api.getUsers();
+ setUsers(data.users);
+ setError('');
+ } catch (err) {
+ setError(err.message || 'Failed to load users');
+ } finally {
+ setLoading(false);
+ }
+ }
+
+ function handleAddUser() {
+ setEditingUser(null);
+ setShowModal(true);
+ }
+
+ function handleEditUser(user) {
+ setEditingUser(user);
+ setShowModal(true);
+ }
+
+ function handleCloseModal() {
+ setShowModal(false);
+ setEditingUser(null);
+ }
+
+ async function handleSaveUser(userData) {
+ try {
+ if (editingUser) {
+ await api.updateUser(editingUser.id, userData);
+ } else {
+ await api.createUser(userData);
+ }
+ await loadUsers();
+ handleCloseModal();
+ } catch (err) {
+ throw err;
+ }
+ }
+
+ async function handleDeleteUser(user) {
+ try {
+ await api.deleteUser(user.id);
+ setDeleteConfirm(null);
+ await loadUsers();
+ } catch (err) {
+ setError(err.message || 'Failed to delete user');
+ }
+ }
+
+ async function handleToggleActive(user) {
+ try {
+ await api.updateUser(user.id, { is_active: !user.is_active });
+ await loadUsers();
+ } catch (err) {
+ setError(err.message || 'Failed to update user status');
+ }
+ }
+
+ function getRoleBadgeClass(role) {
+ switch (role) {
+ case 'admin':
+ return 'badge-danger';
+ case 'developer':
+ return 'badge-primary';
+ case 'viewer':
+ return 'badge-secondary';
+ default:
+ return 'badge-secondary';
+ }
+ }
+
+ function formatDate(dateString) {
+ if (!dateString) return 'Never';
+ return new Date(dateString).toLocaleDateString('en-US', {
+ year: 'numeric',
+ month: 'short',
+ day: 'numeric',
+ hour: '2-digit',
+ minute: '2-digit'
+ });
+ }
+
+ if (loading) {
+ return (
+ <div className="users-tab">
+ <div className="loading-state">Loading users...</div>
+ </div>
+ );
+ }
+
+ return (
+ <div className="users-tab">
+ <div className="tab-header">
+ <div className="tab-header-content">
+ <h3>User Management</h3>
+ <p>Manage user accounts and permissions</p>
+ </div>
+ <button className="btn btn-primary" onClick={handleAddUser}>
+ <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" fill="none" strokeWidth="2">
+ <line x1="12" y1="5" x2="12" y2="19"/>
+ <line x1="5" y1="12" x2="19" y2="12"/>
+ </svg>
+ Add User
+ </button>
+ </div>
+
+ {error && <div className="error-message">{error}</div>}
+
+ <div className="users-table-container">
+ <table className="users-table">
+ <thead>
+ <tr>
+ <th>User</th>
+ <th>Role</th>
+ <th>Status</th>
+ <th>Last Login</th>
+ <th>Created</th>
+ <th>Actions</th>
+ </tr>
+ </thead>
+ <tbody>
+ {users.map(user => (
+ <tr key={user.id} className={!user.is_active ? 'inactive' : ''}>
+ <td className="user-info">
+ <div className="user-avatar">
+ {user.username.charAt(0).toUpperCase()}
+ </div>
+ <div className="user-details">
+ <span className="username">
+ {user.username}
+ {user.id === currentUser?.id && (
+ <span className="you-badge">You</span>
+ )}
+ </span>
+ <span className="email">{user.email}</span>
+ </div>
+ </td>
+ <td>
+ <span className={`badge ${getRoleBadgeClass(user.role)}`}>
+ {user.role}
+ </span>
+ </td>
+ <td>
+ <span className={`status-badge ${user.is_active ? 'active' : 'inactive'}`}>
+ {user.is_active ? 'Active' : 'Disabled'}
+ </span>
+ </td>
+ <td className="date-cell">{formatDate(user.last_login_at)}</td>
+ <td className="date-cell">{formatDate(user.created_at)}</td>
+ <td className="actions-cell">
+ <button
+ className="btn btn-sm btn-ghost"
+ onClick={() => handleEditUser(user)}
+ title="Edit user"
+ >
+ <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" fill="none" strokeWidth="2">
+ <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/>
+ <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/>
+ </svg>
+ </button>
+ {user.id !== currentUser?.id && (
+ <>
+ <button
+ className={`btn btn-sm btn-ghost ${user.is_active ? 'text-warning' : 'text-success'}`}
+ onClick={() => handleToggleActive(user)}
+ title={user.is_active ? 'Disable user' : 'Enable user'}
+ >
+ {user.is_active ? (
+ <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" fill="none" strokeWidth="2">
+ <path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"/>
+ <line x1="1" y1="1" x2="23" y2="23"/>
+ </svg>
+ ) : (
+ <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" fill="none" strokeWidth="2">
+ <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/>
+ <circle cx="12" cy="12" r="3"/>
+ </svg>
+ )}
+ </button>
+ <button
+ className="btn btn-sm btn-ghost text-danger"
+ onClick={() => setDeleteConfirm(user)}
+ title="Delete user"
+ >
+ <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" fill="none" strokeWidth="2">
+ <polyline points="3 6 5 6 21 6"/>
+ <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>
+ </svg>
+ </button>
+ </>
+ )}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+
+ {showModal && (
+ <UserModal
+ user={editingUser}
+ onSave={handleSaveUser}
+ onClose={handleCloseModal}
+ />
+ )}
+
+ {deleteConfirm && (
+ <div className="modal-overlay">
+ <div className="modal modal-sm">
+ <div className="modal-header">
+ <h3>Delete User</h3>
+ <button className="modal-close" onClick={() => setDeleteConfirm(null)}>
+ <svg viewBox="0 0 24 24" width="20" height="20" stroke="currentColor" fill="none" strokeWidth="2">
+ <line x1="18" y1="6" x2="6" y2="18"/>
+ <line x1="6" y1="6" x2="18" y2="18"/>
+ </svg>
+ </button>
+ </div>
+ <div className="modal-body">
+ <p>Are you sure you want to delete <strong>{deleteConfirm.username}</strong>?</p>
+ <p className="text-muted">This action cannot be undone.</p>
+ </div>
+ <div className="modal-footer">
+ <button className="btn btn-ghost" onClick={() => setDeleteConfirm(null)}>
+ Cancel
+ </button>
+ <button className="btn btn-danger" onClick={() => handleDeleteUser(deleteConfirm)}>
+ Delete User
+ </button>
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+};
+
+export default UsersTab;
diff --git a/frontend/src/contexts/AuthContext.jsx b/frontend/src/contexts/AuthContext.jsx
index 38726a08..3e47b5f4 100644
--- a/frontend/src/contexts/AuthContext.jsx
+++ b/frontend/src/contexts/AuthContext.jsx
@@ -6,11 +6,38 @@ const AuthContext = createContext(null);
export function AuthProvider({ children }) {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
+ const [setupStatus, setSetupStatus] = useState({
+ needsSetup: false,
+ registrationEnabled: false,
+ checked: false
+ });
useEffect(() => {
- checkAuth();
+ checkSetupStatus();
}, []);
+ async function checkSetupStatus() {
+ try {
+ const status = await api.getSetupStatus();
+ setSetupStatus({
+ needsSetup: status.needs_setup,
+ registrationEnabled: status.registration_enabled,
+ checked: true
+ });
+
+ // If setup is complete, check authentication
+ if (!status.needs_setup) {
+ await checkAuth();
+ } else {
+ setLoading(false);
+ }
+ } catch (error) {
+ console.error('Setup status check failed:', error);
+ // Fallback to checking auth directly
+ await checkAuth();
+ }
+ }
+
async function checkAuth() {
const token = localStorage.getItem('access_token');
if (token) {
@@ -25,6 +52,19 @@ export function AuthProvider({ children }) {
setLoading(false);
}
+ async function refreshSetupStatus() {
+ try {
+ const status = await api.getSetupStatus();
+ setSetupStatus({
+ needsSetup: status.needs_setup,
+ registrationEnabled: status.registration_enabled,
+ checked: true
+ });
+ } catch (error) {
+ console.error('Failed to refresh setup status:', error);
+ }
+ }
+
async function login(email, password) {
const data = await api.login(email, password);
setUser(data.user);
@@ -62,8 +102,14 @@ export function AuthProvider({ children }) {
logout,
updateUser,
refreshUser,
+ refreshSetupStatus,
isAuthenticated: !!user,
isAdmin: user?.role === 'admin',
+ isDeveloper: user?.role === 'admin' || user?.role === 'developer',
+ isViewer: !!user?.role,
+ setupStatus,
+ needsSetup: setupStatus.needsSetup,
+ registrationEnabled: setupStatus.registrationEnabled,
};
return (
diff --git a/frontend/src/pages/Settings.jsx b/frontend/src/pages/Settings.jsx
index d9412ab3..01241d5f 100644
--- a/frontend/src/pages/Settings.jsx
+++ b/frontend/src/pages/Settings.jsx
@@ -1,9 +1,12 @@
import React, { useState, useEffect } from 'react';
import { useAuth } from '../contexts/AuthContext';
import api from '../services/api';
+import UsersTab from '../components/settings/UsersTab';
+import AuditLogTab from '../components/settings/AuditLogTab';
const Settings = () => {
const [activeTab, setActiveTab] = useState('profile');
+ const { isAdmin } = useAuth();
return (
<div className="page settings-page">
@@ -74,6 +77,36 @@ const Settings = () => {
</svg>
System Info
</button>
+ {isAdmin && (
+ <>
+ <div className="settings-nav-divider">Admin</div>
+ <button
+ className={`settings-nav-item ${activeTab === 'users' ? 'active' : ''}`}
+ onClick={() => setActiveTab('users')}
+ >
+ <svg viewBox="0 0 24 24" width="18" height="18">
+ <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/>
+ <circle cx="9" cy="7" r="4"/>
+ <path d="M23 21v-2a4 4 0 0 0-3-3.87"/>
+ <path d="M16 3.13a4 4 0 0 1 0 7.75"/>
+ </svg>
+ Users
+ </button>
+ <button
+ className={`settings-nav-item ${activeTab === 'audit' ? 'active' : ''}`}
+ onClick={() => setActiveTab('audit')}
+ >
+ <svg viewBox="0 0 24 24" width="18" height="18">
+ <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
+ <polyline points="14 2 14 8 20 8"/>
+ <line x1="16" y1="13" x2="8" y2="13"/>
+ <line x1="16" y1="17" x2="8" y2="17"/>
+ <polyline points="10 9 9 9 8 9"/>
+ </svg>
+ Audit Log
+ </button>
+ </>
+ )}
<button
className={`settings-nav-item ${activeTab === 'about' ? 'active' : ''}`}
onClick={() => setActiveTab('about')}
@@ -93,6 +126,8 @@ const Settings = () => {
{activeTab === 'appearance' && <AppearanceSettings />}
{activeTab === 'notifications' && <NotificationSettings />}
{activeTab === 'system' && <SystemInfo />}
+ {activeTab === 'users' && isAdmin && <UsersTab />}
+ {activeTab === 'audit' && isAdmin && <AuditLogTab />}
{activeTab === 'about' && <AboutSection />}
</div>
</div>
diff --git a/frontend/src/pages/Setup.jsx b/frontend/src/pages/Setup.jsx
new file mode 100644
index 00000000..6a59b8c9
--- /dev/null
+++ b/frontend/src/pages/Setup.jsx
@@ -0,0 +1,134 @@
+import React, { useState } from 'react';
+import { useNavigate } from 'react-router-dom';
+import { useAuth } from '../contexts/AuthContext';
+
+const Setup = () => {
+ const [email, setEmail] = useState('');
+ const [username, setUsername] = useState('');
+ const [password, setPassword] = useState('');
+ const [confirmPassword, setConfirmPassword] = useState('');
+ const [error, setError] = useState('');
+ const [loading, setLoading] = useState(false);
+ const { register } = useAuth();
+ const navigate = useNavigate();
+
+ async function handleSubmit(e) {
+ e.preventDefault();
+ setError('');
+
+ if (password !== confirmPassword) {
+ setError('Passwords do not match');
+ return;
+ }
+
+ if (password.length < 8) {
+ setError('Password must be at least 8 characters');
+ return;
+ }
+
+ setLoading(true);
+
+ try {
+ await register(email, username, password);
+ // User is now logged in, redirect to home
+ navigate('/');
+ } catch (err) {
+ setError(err.message || 'Failed to create admin account');
+ } finally {
+ setLoading(false);
+ }
+ }
+
+ return (
+ <div className="auth-container">
+ <div className="auth-card setup-card">
+ <div className="auth-header">
+ <div className="brand-logo">
+ <svg viewBox="0 0 24 24" width="32" height="32" stroke="currentColor" fill="none" strokeWidth="2">
+ <path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5"/>
+ </svg>
+ </div>
+ <h1>Welcome to ServerKit</h1>
+ <p>Let's set up your admin account</p>
+ </div>
+
+ <div className="setup-info">
+ <div className="setup-info-icon">
+ <svg viewBox="0 0 24 24" width="20" height="20" stroke="currentColor" fill="none" strokeWidth="2">
+ <circle cx="12" cy="12" r="10"/>
+ <line x1="12" y1="16" x2="12" y2="12"/>
+ <line x1="12" y1="8" x2="12.01" y2="8"/>
+ </svg>
+ </div>
+ <p>This is your first time using ServerKit. Create an administrator account to get started. This account will have full access to manage your server.</p>
+ </div>
+
+ {error && <div className="error-message">{error}</div>}
+
+ <form onSubmit={handleSubmit}>
+ <div className="form-group">
+ <label htmlFor="email">Admin Email</label>
+ <input
+ type="email"
+ id="email"
+ value={email}
+ onChange={(e) => setEmail(e.target.value)}
+ placeholder="[email protected]"
+ required
+ autoFocus
+ />
+ </div>
+
+ <div className="form-group">
+ <label htmlFor="username">Username</label>
+ <input
+ type="text"
+ id="username"
+ value={username}
+ onChange={(e) => setUsername(e.target.value)}
+ placeholder="Choose a username"
+ required
+ />
+ </div>
+
+ <div className="form-group">
+ <label htmlFor="password">Password</label>
+ <input
+ type="password"
+ id="password"
+ value={password}
+ onChange={(e) => setPassword(e.target.value)}
+ placeholder="At least 8 characters"
+ required
+ />
+ </div>
+
+ <div className="form-group">
+ <label htmlFor="confirmPassword">Confirm Password</label>
+ <input
+ type="password"
+ id="confirmPassword"
+ value={confirmPassword}
+ onChange={(e) => setConfirmPassword(e.target.value)}
+ placeholder="Confirm your password"
+ required
+ />
+ </div>
+
+ <button type="submit" className="btn btn-primary btn-full" disabled={loading}>
+ {loading ? 'Creating account...' : 'Create Admin Account'}
+ </button>
+ </form>
+
+ <div className="setup-footer">
+ <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" fill="none" strokeWidth="2">
+ <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
+ </svg>
+ <span>Your data is stored securely on this server</span>
+ </div>
+ </div>
+ </div>
+ );
+};
+
+export default Setup;
diff --git a/frontend/src/services/api.js b/frontend/src/services/api.js
index 975fe9f1..8f08acca 100644
--- a/frontend/src/services/api.js
+++ b/frontend/src/services/api.js
@@ -93,6 +93,10 @@ class ApiService {
}
// Auth endpoints
+ async getSetupStatus() {
+ return this.request('/auth/setup-status');
+ }
+
async login(email, password) {
const data = await this.request('/auth/login', {
method: 'POST',
@@ -126,6 +130,84 @@ class ApiService {
});
}
+ // ========================================
+ // Admin - User Management endpoints
+ // ========================================
+ async getUsers() {
+ return this.request('/admin/users');
+ }
+
+ async getUser(userId) {
+ return this.request(`/admin/users/${userId}`);
+ }
+
+ async createUser(userData) {
+ return this.request('/admin/users', {
+ method: 'POST',
+ body: userData
+ });
+ }
+
+ async updateUser(userId, userData) {
+ return this.request(`/admin/users/${userId}`, {
+ method: 'PUT',
+ body: userData
+ });
+ }
+
+ async deleteUser(userId) {
+ return this.request(`/admin/users/${userId}`, {
+ method: 'DELETE'
+ });
+ }
+
+ // ========================================
+ // Admin - Audit Log endpoints
+ // ========================================
+ async getAuditLogs(params = {}) {
+ const searchParams = new URLSearchParams();
+ if (params.page) searchParams.append('page', params.page);
+ if (params.per_page) searchParams.append('per_page', params.per_page);
+ if (params.action) searchParams.append('action', params.action);
+ if (params.user_id) searchParams.append('user_id', params.user_id);
+ if (params.target_type) searchParams.append('target_type', params.target_type);
+ const query = searchParams.toString();
+ return this.request(`/admin/audit-logs${query ? '?' + query : ''}`);
+ }
+
+ async getAuditLogActions() {
+ return this.request('/admin/audit-logs/actions');
+ }
+
+ // ========================================
+ // Admin - System Settings endpoints
+ // ========================================
+ async getSystemSettings() {
+ return this.request('/admin/settings');
+ }
+
+ async updateSystemSettings(settings) {
+ return this.request('/admin/settings', {
+ method: 'PUT',
+ body: settings
+ });
+ }
+
+ async getSystemSetting(key) {
+ return this.request(`/admin/settings/${key}`);
+ }
+
+ async updateSystemSetting(key, value) {
+ return this.request(`/admin/settings/${key}`, {
+ method: 'PUT',
+ body: { value }
+ });
+ }
+
+ async getAdminStats() {
+ return this.request('/admin/stats');
+ }
+
// Apps endpoints
async getApps() {
return this.request('/apps');
diff --git a/frontend/src/styles/components/_users.less b/frontend/src/styles/components/_users.less
new file mode 100644
index 00000000..12150650
--- /dev/null
+++ b/frontend/src/styles/components/_users.less
@@ -0,0 +1,486 @@
+// ============================================
+// USER MANAGEMENT STYLES
+// ============================================
+
+// --------------------------------------------
+// Setup Page
+// --------------------------------------------
+.setup-card {
+ max-width: 480px;
+}
+
+.setup-info {
+ display: flex;
+ gap: @space-4;
+ padding: @space-4;
+ background: fade(@accent-primary, 10%);
+ border-radius: @radius-md;
+ margin-bottom: @space-6;
+
+ .setup-info-icon {
+ flex-shrink: 0;
+ color: @accent-primary;
+ }
+
+ p {
+ margin: 0;
+ font-size: @font-size-sm;
+ color: @text-secondary;
+ line-height: 1.5;
+ }
+}
+
+.setup-footer {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: @space-2;
+ margin-top: @space-6;
+ padding-top: @space-6;
+ border-top: 1px solid @border-default;
+ color: @text-tertiary;
+ font-size: @font-size-sm;
+
+ svg {
+ color: @success;
+ }
+}
+
+// --------------------------------------------
+// Users Tab
+// --------------------------------------------
+.users-tab {
+ .tab-header {
+ display: flex;
+ justify-content: space-between;
+ align-items: flex-start;
+ margin-bottom: @space-6;
+
+ .tab-header-content {
+ h3 {
+ margin: 0 0 @space-1 0;
+ font-size: @font-size-lg;
+ font-weight: 600;
+ }
+
+ p {
+ margin: 0;
+ color: @text-secondary;
+ font-size: @font-size-sm;
+ }
+ }
+ }
+}
+
+.users-table-container {
+ overflow-x: auto;
+ border: 1px solid @border-default;
+ border-radius: @radius-md;
+}
+
+.users-table {
+ width: 100%;
+ border-collapse: collapse;
+
+ th, td {
+ padding: @space-4;
+ text-align: left;
+ border-bottom: 1px solid @border-default;
+ }
+
+ th {
+ background: @bg-hover;
+ font-weight: 500;
+ font-size: @font-size-sm;
+ color: @text-secondary;
+ text-transform: uppercase;
+ letter-spacing: 0.05em;
+ }
+
+ tr:last-child td {
+ border-bottom: none;
+ }
+
+ tr:hover td {
+ background: @bg-card;
+ }
+
+ tr.inactive {
+ opacity: 0.6;
+
+ td {
+ background: fade(@warning, 5%);
+ }
+ }
+
+ .user-info {
+ display: flex;
+ align-items: center;
+ gap: @space-4;
+ }
+
+ .user-avatar {
+ width: 40px;
+ height: 40px;
+ border-radius: 50%;
+ background: @accent-primary;
+ color: #fff;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ font-weight: 600;
+ font-size: @font-size-md;
+ flex-shrink: 0;
+ }
+
+ .user-details {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+
+ .username {
+ font-weight: 500;
+ display: flex;
+ align-items: center;
+ gap: @space-2;
+ }
+
+ .email {
+ font-size: @font-size-sm;
+ color: @text-secondary;
+ }
+ }
+
+ .you-badge {
+ font-size: @font-size-xs;
+ padding: 2px 6px;
+ background: @accent-primary;
+ color: #fff;
+ border-radius: @radius-sm;
+ font-weight: 500;
+ }
+
+ .status-badge {
+ display: inline-flex;
+ align-items: center;
+ padding: 4px 10px;
+ border-radius: @radius-full;
+ font-size: @font-size-xs;
+ font-weight: 500;
+
+ &.active {
+ background: fade(@success, 15%);
+ color: @success;
+ }
+
+ &.inactive {
+ background: fade(@warning, 15%);
+ color: @warning;
+ }
+ }
+
+ .date-cell {
+ font-size: @font-size-sm;
+ color: @text-secondary;
+ white-space: nowrap;
+ }
+
+ .actions-cell {
+ display: flex;
+ gap: @space-1;
+ }
+}
+
+// --------------------------------------------
+// User Modal Styles
+// --------------------------------------------
+.form-row {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: @space-4;
+
+ @media (max-width: 600px) {
+ grid-template-columns: 1fr;
+ }
+}
+
+.checkbox-label {
+ display: flex;
+ align-items: center;
+ gap: @space-2;
+ cursor: pointer;
+
+ input[type="checkbox"] {
+ width: 18px;
+ height: 18px;
+ cursor: pointer;
+ }
+
+ .checkbox-text {
+ font-weight: 400;
+ }
+}
+
+.form-help {
+ display: block;
+ margin-top: @space-1;
+ font-size: @font-size-xs;
+ color: @text-tertiary;
+}
+
+.role-descriptions {
+ margin-top: @space-6;
+ padding: @space-4;
+ background: @bg-hover;
+ border-radius: @radius-md;
+
+ h4 {
+ margin: 0 0 @space-4 0;
+ font-size: @font-size-sm;
+ font-weight: 600;
+ color: @text-secondary;
+ }
+
+ .role-item {
+ display: flex;
+ gap: @space-2;
+ padding: @space-2 0;
+
+ &:not(:last-child) {
+ border-bottom: 1px solid @border-default;
+ }
+
+ .role-name {
+ font-weight: 500;
+ min-width: 80px;
+ font-size: @font-size-sm;
+ }
+
+ .role-desc {
+ font-size: @font-size-sm;
+ color: @text-secondary;
+ }
+ }
+}
+
+// --------------------------------------------
+// Audit Log Tab
+// --------------------------------------------
+.audit-log-tab {
+ .tab-header {
+ margin-bottom: @space-6;
+
+ h3 {
+ margin: 0 0 @space-1 0;
+ font-size: @font-size-lg;
+ font-weight: 600;
+ }
+
+ p {
+ margin: 0;
+ color: @text-secondary;
+ font-size: @font-size-sm;
+ }
+ }
+}
+
+.filters-bar {
+ display: flex;
+ gap: @space-4;
+ align-items: flex-end;
+ margin-bottom: @space-6;
+ padding: @space-4;
+ background: @bg-hover;
+ border-radius: @radius-md;
+
+ .filter-group {
+ display: flex;
+ flex-direction: column;
+ gap: @space-1;
+
+ label {
+ font-size: @font-size-sm;
+ font-weight: 500;
+ color: @text-secondary;
+ }
+
+ select {
+ min-width: 180px;
+ }
+ }
+}
+
+.audit-log-list {
+ display: flex;
+ flex-direction: column;
+ gap: @space-2;
+}
+
+.log-entry {
+ display: flex;
+ gap: @space-4;
+ padding: @space-4;
+ background: @bg-card;
+ border-radius: @radius-md;
+ border-left: 3px solid transparent;
+
+ &.action-success {
+ border-left-color: @success;
+ }
+
+ &.action-warning {
+ border-left-color: @warning;
+ }
+
+ &.action-danger {
+ border-left-color: @danger;
+ }
+
+ &.action-info {
+ border-left-color: @accent-primary;
+ }
+
+ .log-icon {
+ flex-shrink: 0;
+ width: 32px;
+ height: 32px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ background: @bg-hover;
+ border-radius: @radius-sm;
+ color: @text-secondary;
+ }
+
+ .log-content {
+ flex: 1;
+ min-width: 0;
+ }
+
+ .log-header {
+ display: flex;
+ flex-wrap: wrap;
+ gap: @space-2;
+ align-items: center;
+ margin-bottom: @space-1;
+
+ .log-action {
+ font-weight: 500;
+ text-transform: capitalize;
+ }
+
+ .log-user {
+ color: @text-secondary;
+ font-size: @font-size-sm;
+ }
+
+ .log-target {
+ color: @text-tertiary;
+ font-size: @font-size-sm;
+ }
+ }
+
+ .log-details {
+ display: flex;
+ flex-wrap: wrap;
+ gap: @space-2;
+ margin-bottom: @space-2;
+
+ .detail-item {
+ display: inline-flex;
+ gap: @space-1;
+ padding: 2px @space-2;
+ background: @bg-hover;
+ border-radius: @radius-sm;
+ font-size: @font-size-xs;
+
+ .detail-key {
+ color: @text-tertiary;
+ }
+
+ .detail-value {
+ color: @text-secondary;
+ max-width: 200px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ }
+ }
+
+ .log-meta {
+ display: flex;
+ gap: @space-4;
+ font-size: @font-size-xs;
+ color: @text-tertiary;
+
+ .log-ip {
+ font-family: @font-mono;
+ }
+ }
+}
+
+.pagination {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: @space-4;
+ margin-top: @space-6;
+ padding-top: @space-6;
+ border-top: 1px solid @border-default;
+
+ .pagination-info {
+ font-size: @font-size-sm;
+ color: @text-secondary;
+ }
+}
+
+// --------------------------------------------
+// Settings Nav Divider
+// --------------------------------------------
+.settings-nav-divider {
+ padding: @space-2 @space-4;
+ margin-top: @space-4;
+ font-size: @font-size-xs;
+ font-weight: 600;
+ color: @text-tertiary;
+ text-transform: uppercase;
+ letter-spacing: 0.1em;
+}
+
+// --------------------------------------------
+// Loading & Empty States
+// --------------------------------------------
+.loading-state,
+.empty-state {
+ padding: @space-10;
+ text-align: center;
+ color: @text-secondary;
+}
+
+// --------------------------------------------
+// Button Variants
+// --------------------------------------------
+.btn.text-warning {
+ color: @warning;
+
+ &:hover {
+ background: fade(@warning, 10%);
+ }
+}
+
+.btn.text-success {
+ color: @success;
+
+ &:hover {
+ background: fade(@success, 10%);
+ }
+}
+
+.btn.text-danger {
+ color: @danger;
+
+ &:hover {
+ background: fade(@danger, 10%);
+ }
+}
diff --git a/frontend/src/styles/layout/_sidebar.less b/frontend/src/styles/layout/_sidebar.less
index 7e431311..fb28756e 100644
--- a/frontend/src/styles/layout/_sidebar.less
+++ b/frontend/src/styles/layout/_sidebar.less
@@ -26,6 +26,7 @@
.flex-start();
gap: @space-3;
border-bottom: 1px solid @border-subtle;
+ flex-shrink: 0;
}
.brand-logo {
@@ -35,6 +36,31 @@
color: white;
}
+// Scrollable nav container
+.sidebar-nav-container {
+ flex: 1;
+ overflow-y: auto;
+ overflow-x: hidden;
+
+ // Custom scrollbar
+ &::-webkit-scrollbar {
+ width: 4px;
+ }
+
+ &::-webkit-scrollbar-track {
+ background: transparent;
+ }
+
+ &::-webkit-scrollbar-thumb {
+ background: @border-active;
+ border-radius: @radius-full;
+ }
+
+ &::-webkit-scrollbar-thumb:hover {
+ background: @text-tertiary;
+ }
+}
+
// Menu labels
.menu-label {
padding: @space-6 @space-8 @space-2;
@@ -85,7 +111,7 @@
// User profile at bottom
.user-profile {
- margin-top: auto;
+ flex-shrink: 0;
padding: @space-5;
border-top: 1px solid @border-subtle;
.flex-start();
diff --git a/frontend/src/styles/main.less b/frontend/src/styles/main.less
index abd58f9e..60276607 100644
--- a/frontend/src/styles/main.less
+++ b/frontend/src/styles/main.less
@@ -46,6 +46,7 @@
@import 'components/_query-runner';
@import 'components/_deploy';
@import 'components/_build';
+@import 'components/_users';
// --------------------------------------------
// 5. PAGE-SPECIFIC STYLES
diff --git a/frontend/src/styles/pages/_settings.less b/frontend/src/styles/pages/_settings.less
index eab38040..c41f3900 100644
--- a/frontend/src/styles/pages/_settings.less
+++ b/frontend/src/styles/pages/_settings.less
@@ -37,12 +37,29 @@
gap: @space-1;
position: sticky;
top: @space-6;
- height: fit-content;
+ max-height: calc(100vh - @space-12);
+ overflow-y: auto;
+
+ // Custom scrollbar for nav
+ &::-webkit-scrollbar {
+ width: 4px;
+ }
+
+ &::-webkit-scrollbar-track {
+ background: transparent;
+ }
+
+ &::-webkit-scrollbar-thumb {
+ background: @border-active;
+ border-radius: @radius-full;
+ }
@media (max-width: @breakpoint-lg) {
flex-direction: row;
flex-wrap: wrap;
position: static;
+ max-height: none;
+ overflow-y: visible;
background: @bg-card;
padding: @space-2;
border-radius: @radius-lg;