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.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
Add server time and timezone management features
Juan Denis46b6d5e7ad71
diff --git a/backend/app/api/system.py b/backend/app/api/system.pyindex 728a8946..d78b3045 100644--- a/backend/app/api/system.py+++ b/backend/app/api/system.py@@ -187,6 +187,49 @@ def health_check():}), 200+@system_bp.route('/time', methods=['GET'])+@jwt_required()+def get_server_time():+ """Get current server time and timezone."""+ return jsonify(SystemService.get_server_time()), 200+++@system_bp.route('/timezones', methods=['GET'])+@jwt_required()+def get_timezones():+ """Get list of available timezones."""+ current_user_id = get_jwt_identity()+ user = User.query.get(current_user_id)++ if user.role != 'admin':+ return jsonify({'error': 'Admin access required'}), 403++ timezones = SystemService.get_available_timezones()+ return jsonify({'timezones': timezones}), 200+++@system_bp.route('/timezone', methods=['PUT'])+@jwt_required()+def set_timezone():+ """Set server timezone (admin only)."""+ current_user_id = get_jwt_identity()+ user = User.query.get(current_user_id)++ if user.role != 'admin':+ return jsonify({'error': 'Admin access required'}), 403++ data = request.get_json()+ if not data or 'timezone' not in data:+ return jsonify({'error': 'Timezone is required'}), 400++ result = SystemService.set_timezone(data['timezone'])++ if result['success']:+ return jsonify(result), 200+ else:+ return jsonify(result), 400++@system_bp.route('/processes', methods=['GET'])@jwt_required()def get_processes():diff --git a/backend/app/services/system_service.py b/backend/app/services/system_service.pyindex 86b0021f..d0308104 100644--- a/backend/app/services/system_service.py+++ b/backend/app/services/system_service.py@@ -191,6 +191,134 @@ class SystemService:return ' '.join(parts) if parts else '0m'+ @classmethod+ def get_server_time(cls):+ """Get current server time and timezone info."""+ import time as time_module++ now = datetime.now()+ utc_now = datetime.utcnow()++ # Get timezone name+ tz_name = time_module.tzname[time_module.daylight] if time_module.daylight else time_module.tzname[0]++ # Try to get more detailed timezone info on Linux+ timezone_file = '/etc/timezone'+ timezone_id = None+ if os.path.exists(timezone_file):+ try:+ with open(timezone_file, 'r') as f:+ timezone_id = f.read().strip()+ except Exception:+ pass++ # Fallback: try timedatectl on systemd systems+ if not timezone_id:+ try:+ result = subprocess.run(+ ['timedatectl', 'show', '--property=Timezone', '--value'],+ capture_output=True, text=True, timeout=5+ )+ if result.returncode == 0:+ timezone_id = result.stdout.strip()+ except Exception:+ pass++ # Calculate UTC offset+ utc_offset_seconds = (now - utc_now).total_seconds()+ utc_offset_hours = int(utc_offset_seconds // 3600)+ utc_offset_minutes = int((abs(utc_offset_seconds) % 3600) // 60)+ utc_offset_str = f"UTC{'+' if utc_offset_hours >= 0 else ''}{utc_offset_hours:+d}:{utc_offset_minutes:02d}"++ return {+ 'current_time': now.isoformat(),+ 'current_time_formatted': now.strftime('%Y-%m-%d %H:%M:%S'),+ 'utc_time': utc_now.isoformat(),+ 'timezone_name': tz_name,+ 'timezone_id': timezone_id or tz_name,+ 'utc_offset': utc_offset_str,+ 'utc_offset_seconds': int(utc_offset_seconds)+ }++ @classmethod+ def get_available_timezones(cls):+ """Get list of available timezones."""+ try:+ # Use timedatectl to list timezones on systemd systems+ result = subprocess.run(+ ['timedatectl', 'list-timezones'],+ capture_output=True, text=True, timeout=10+ )+ if result.returncode == 0:+ return result.stdout.strip().split('\n')+ except Exception:+ pass++ # Fallback: return common timezones+ return [+ 'UTC',+ 'America/New_York',+ 'America/Chicago',+ 'America/Denver',+ 'America/Los_Angeles',+ 'America/Toronto',+ 'America/Vancouver',+ 'America/Mexico_City',+ 'America/Sao_Paulo',+ 'Europe/London',+ 'Europe/Paris',+ 'Europe/Berlin',+ 'Europe/Madrid',+ 'Europe/Rome',+ 'Europe/Amsterdam',+ 'Europe/Moscow',+ 'Asia/Tokyo',+ 'Asia/Shanghai',+ 'Asia/Hong_Kong',+ 'Asia/Singapore',+ 'Asia/Dubai',+ 'Asia/Kolkata',+ 'Australia/Sydney',+ 'Australia/Melbourne',+ 'Pacific/Auckland',+ ]++ @classmethod+ def set_timezone(cls, timezone_id):+ """Set server timezone (requires root/sudo)."""+ # Validate timezone exists+ available = cls.get_available_timezones()+ if timezone_id not in available:+ return {'success': False, 'error': f'Invalid timezone: {timezone_id}'}++ try:+ # Try timedatectl first (systemd)+ result = subprocess.run(+ ['sudo', 'timedatectl', 'set-timezone', timezone_id],+ capture_output=True, text=True, timeout=10+ )+ if result.returncode == 0:+ return {'success': True, 'message': f'Timezone set to {timezone_id}'}++ # Fallback: symlink method+ result = subprocess.run(+ ['sudo', 'ln', '-sf', f'/usr/share/zoneinfo/{timezone_id}', '/etc/localtime'],+ capture_output=True, text=True, timeout=10+ )+ if result.returncode == 0:+ # Also update /etc/timezone+ subprocess.run(+ ['sudo', 'bash', '-c', f'echo "{timezone_id}" > /etc/timezone'],+ capture_output=True, text=True, timeout=10+ )+ return {'success': True, 'message': f'Timezone set to {timezone_id}'}++ return {'success': False, 'error': result.stderr or 'Failed to set timezone'}+ except subprocess.TimeoutExpired:+ return {'success': False, 'error': 'Timeout while setting timezone'}+ except Exception as e:+ return {'success': False, 'error': str(e)}+@classmethoddef get_all_metrics(cls):"""Get all system metrics at once."""@@ -201,5 +329,6 @@ class SystemService:'network': cls.get_network_metrics(),'load_average': cls.get_load_average(),'system': cls.get_system_info(),+ 'time': cls.get_server_time(),'timestamp': datetime.utcnow().isoformat()}diff --git a/frontend/dist/index.html b/frontend/dist/index.htmlindex 38af6e4d..e5aa6ad1 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-IQpYnTvr.js"></script>- <link rel="stylesheet" crossorigin href="/assets/index-BFijD2gh.css">+ <script type="module" crossorigin src="/assets/index-BD3d9Dtf.js"></script>+ <link rel="stylesheet" crossorigin href="/assets/index-C0PTPb9w.css"></head><body>diff --git a/frontend/src/pages/Dashboard.jsx b/frontend/src/pages/Dashboard.jsxindex 7d70162e..e8034eba 100644--- a/frontend/src/pages/Dashboard.jsx+++ b/frontend/src/pages/Dashboard.jsx@@ -4,7 +4,7 @@ import {Cpu, MemoryStick, HardDrive, Server,Plus, RefreshCw, Activity, Layers,Database, Globe, Container, Code,- ArrowRight, Clock, CheckCircle+ ArrowRight, Clock, CheckCircle, MapPin} from 'lucide-react';import api from '../services/api';import { useMetrics } from '../hooks/useMetrics';@@ -17,12 +17,20 @@ const Dashboard = () => {const [services, setServices] = useState([]);const [dbStatus, setDbStatus] = useState(null);const [uptime, setUptime] = useState(null);+ const [serverTime, setServerTime] = useState(null);const [loading, setLoading] = useState(true);useEffect(() => {loadData();}, []);+ // Update server time display every second using metrics.time+ useEffect(() => {+ if (metrics?.time) {+ setServerTime(metrics.time);+ }+ }, [metrics]);+async function loadData() {try {const [appsData, servicesData, dbData, uptimeData] = await Promise.all([@@ -121,6 +129,18 @@ const Dashboard = () => {</div>)}</div>+ <div className="status-bar-center">+ {serverTime && (+ <div className="server-time-display">+ <Clock size={14} />+ <span className="time-value">{serverTime.current_time_formatted}</span>+ <span className="timezone-badge">+ <MapPin size={10} />+ {serverTime.timezone_id || serverTime.timezone_name}+ </span>+ </div>+ )}+ </div><div className="status-bar-right"><div className="status-bar-stat"><span className="stat-label">Apps</span>diff --git a/frontend/src/pages/Settings.jsx b/frontend/src/pages/Settings.jsxindex 9f59efbf..8f5951a3 100644--- a/frontend/src/pages/Settings.jsx+++ b/frontend/src/pages/Settings.jsx@@ -1505,10 +1505,15 @@ const SystemInfo = () => {const { isAdmin } = useAuth();const [metrics, setMetrics] = useState(null);const [loading, setLoading] = useState(true);+ const [timezones, setTimezones] = useState([]);+ const [selectedTimezone, setSelectedTimezone] = useState('');+ const [savingTimezone, setSavingTimezone] = useState(false);+ const [timezoneMessage, setTimezoneMessage] = useState(null);useEffect(() => {if (isAdmin) {loadMetrics();+ loadTimezones();}}, [isAdmin]);@@ -1516,6 +1521,9 @@ const SystemInfo = () => {try {const data = await api.getSystemMetrics();setMetrics(data);+ if (data?.time?.timezone_id) {+ setSelectedTimezone(data.time.timezone_id);+ }} catch (err) {console.error('Failed to load metrics:', err);} finally {@@ -1523,6 +1531,34 @@ const SystemInfo = () => {}}+ async function loadTimezones() {+ try {+ const data = await api.getTimezones();+ setTimezones(data.timezones || []);+ } catch (err) {+ console.error('Failed to load timezones:', err);+ }+ }++ async function handleTimezoneChange() {+ if (!selectedTimezone) return;++ setSavingTimezone(true);+ setTimezoneMessage(null);++ try {+ const result = await api.setTimezone(selectedTimezone);+ setTimezoneMessage({ type: 'success', text: result.message || 'Timezone updated' });+ // Refresh metrics to show new time+ loadMetrics();+ } catch (err) {+ setTimezoneMessage({ type: 'error', text: err.message || 'Failed to set timezone' });+ } finally {+ setSavingTimezone(false);+ setTimeout(() => setTimezoneMessage(null), 5000);+ }+ }+if (!isAdmin) {return (<div className="settings-section">@@ -1643,6 +1679,57 @@ const SystemInfo = () => {</div></div>)}++ {/* Server Time & Timezone */}+ <div className="settings-card">+ <h3>Server Time & Timezone</h3>+ {metrics?.time && (+ <div className="info-list" style={{ marginBottom: '1rem' }}>+ <div className="info-item">+ <span className="info-label">Current Time</span>+ <span className="info-value">{metrics.time.current_time_formatted}</span>+ </div>+ <div className="info-item">+ <span className="info-label">UTC Offset</span>+ <span className="info-value">{metrics.time.utc_offset}</span>+ </div>+ <div className="info-item">+ <span className="info-label">Current Timezone</span>+ <span className="info-value">{metrics.time.timezone_id || metrics.time.timezone_name}</span>+ </div>+ </div>+ )}+ <div className="form-group">+ <label>Change Timezone</label>+ <div className="timezone-selector">+ <select+ value={selectedTimezone}+ onChange={(e) => setSelectedTimezone(e.target.value)}+ className="form-control"+ >+ <option value="">Select timezone...</option>+ {timezones.map((tz) => (+ <option key={tz} value={tz}>{tz}</option>+ ))}+ </select>+ <button+ className="btn btn-primary"+ onClick={handleTimezoneChange}+ disabled={savingTimezone || !selectedTimezone || selectedTimezone === metrics?.time?.timezone_id}+ >+ {savingTimezone ? 'Saving...' : 'Apply'}+ </button>+ </div>+ {timezoneMessage && (+ <div className={`timezone-message ${timezoneMessage.type}`}>+ {timezoneMessage.text}+ </div>+ )}+ <span className="form-help">+ Changing timezone requires server restart to take full effect+ </span>+ </div>+ </div></div>);};diff --git a/frontend/src/services/api.js b/frontend/src/services/api.jsindex 1b895329..d293f28d 100644--- a/frontend/src/services/api.js+++ b/frontend/src/services/api.js@@ -340,6 +340,21 @@ class ApiService {return this.request('/system/metrics');}+ async getServerTime() {+ return this.request('/system/time');+ }++ async getTimezones() {+ return this.request('/system/timezones');+ }++ async setTimezone(timezone) {+ return this.request('/system/timezone', {+ method: 'PUT',+ body: { timezone }+ });+ }+async getVersion() {return this.request('/system/version');}diff --git a/frontend/src/styles/pages/_dashboard.less b/frontend/src/styles/pages/_dashboard.lessindex 71c65724..de51b53d 100644--- a/frontend/src/styles/pages/_dashboard.less+++ b/frontend/src/styles/pages/_dashboard.less@@ -54,6 +54,43 @@}}+.status-bar-center {+ display: flex;+ align-items: center;+ justify-content: center;+ flex: 1;+}++.server-time-display {+ display: flex;+ align-items: center;+ gap: @space-2;+ color: @text-secondary;+ font-size: @font-size-sm;++ svg {+ color: @text-tertiary;+ }++ .time-value {+ font-family: @font-mono;+ font-weight: @font-weight-medium;+ color: @text-primary;+ }++ .timezone-badge {+ display: flex;+ align-items: center;+ gap: 4px;+ font-size: @font-size-xs;+ color: @accent-primary;+ background: @accent-glow;+ padding: 2px 8px;+ border-radius: @radius-full;+ margin-left: @space-2;+ }+}+.status-bar-right {display: flex;align-items: center;diff --git a/frontend/src/styles/pages/_settings.less b/frontend/src/styles/pages/_settings.lessindex 46733e61..1417fae5 100644--- a/frontend/src/styles/pages/_settings.less+++ b/frontend/src/styles/pages/_settings.less@@ -551,6 +551,39 @@}}+// Timezone Selector+.timezone-selector {+ display: flex;+ gap: @space-3;+ align-items: center;++ select {+ flex: 1;+ max-width: 300px;+ }++ .btn {+ flex-shrink: 0;+ }+}++.timezone-message {+ margin-top: @space-2;+ padding: @space-2 @space-3;+ border-radius: @radius-md;+ font-size: @font-size-sm;++ &.success {+ background: fade(@success, 15%);+ color: @success;+ }++ &.error {+ background: fade(@danger, 15%);+ color: @danger;+ }+}+// About Section.about-card {background: @bg-card;