35512-vm/settings.php
2025-11-08 21:16:26 +00:00

242 lines
12 KiB
PHP

<?php
session_start();
require_once 'db/config.php';
require_once 'auth-check.php';
require_once 'auth-helpers.php';
// Only Super Admins can manage settings
$is_super_admin = ($_SESSION['user_role_id'] == 1);
if (!$is_super_admin) {
// Redirect non-super-admins or users who can't update permissions
if (!can($_SESSION['user_role_id'], 'permission', 'update')) {
header('Location: index.php?error=access_denied');
exit;
}
}
$success_message = '';
$error_message = '';
$pdo = db();
// Handle Google Settings form submission
if ($is_super_admin && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_google_settings'])) {
$google_client_id = $_POST['google_client_id'] ?? '';
$google_client_secret = $_POST['google_client_secret'] ?? '';
try {
$stmt = $pdo->prepare('UPDATE settings SET setting_value = ? WHERE setting_key = ?');
$stmt->execute([$google_client_id, 'google_client_id']);
$stmt->execute([$google_client_secret, 'google_client_secret']);
$success_message = 'Google settings updated successfully!';
} catch (PDOException $e) {
$error_message = 'Database error updating Google settings: ' . $e->getMessage();
}
}
// Handle Permissions form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_permissions'])) {
if (!can($_SESSION['user_role_id'], 'permission', 'update')) {
header('Location: index.php?error=access_denied');
exit;
}
try {
$pdo->beginTransaction();
$permissions = $_POST['permissions'] ?? [];
$stmt_roles = $pdo->query('SELECT id FROM roles');
$db_roles_ids = $stmt_roles->fetchAll(PDO::FETCH_COLUMN);
$delete_stmt = $pdo->prepare('DELETE FROM role_permissions WHERE role_id = ?');
$insert_stmt = $pdo->prepare('INSERT INTO role_permissions (role_id, resource, action, fields) VALUES (?, ?, ?, ?)');
foreach ($db_roles_ids as $role_id) {
$delete_stmt->execute([$role_id]);
if (isset($permissions[$role_id])) {
foreach (['asset', 'user', 'category', 'location', 'role', 'permission'] as $resource) {
foreach (['create', 'read', 'update', 'delete'] as $action) {
if (isset($permissions[$role_id][$resource][$action]['enabled']) && $permissions[$role_id][$resource][$action]['enabled'] == '1') {
$fields = (in_array($action, ['read', 'update', 'create'])) ? ($permissions[$role_id][$resource][$action]['fields'] ?? '*') : null;
if (empty($fields)) $fields = '*';
$insert_stmt->execute([$role_id, $resource, $action, $fields]);
}
}
}
}
}
$pdo->commit();
$success_message = 'Permissions updated successfully!';
} catch (PDOException $e) {
if ($pdo->inTransaction()) $pdo->rollBack();
$error_message = 'Database error: ' . $e->getMessage();
}
}
// Fetch data for display
$google_settings = [];
if ($is_super_admin) {
try {
$stmt = $pdo->query("SELECT setting_key, setting_value FROM settings WHERE setting_key IN ('google_client_id', 'google_client_secret')");
$google_settings_raw = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($google_settings_raw as $row) {
$google_settings[$row['setting_key']] = $row['setting_value'];
}
} catch (PDOException $e) {
$error_message = "Database error fetching Google settings: " . $e->getMessage();
}
}
try {
$roles_stmt = $pdo->query('SELECT * FROM roles ORDER BY name');
$roles = $roles_stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
$error_message = "Database error fetching roles: " . $e->getMessage();
$roles = [];
}
$resources = ['asset', 'user', 'category', 'location', 'role', 'permission'];
$actions = ['create', 'read', 'update', 'delete'];
function get_permissions() {
try {
$pdo_func = db();
$stmt = $pdo_func->query('SELECT * FROM role_permissions ORDER BY role_id, resource, action');
return $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
return ['error' => 'Database error: ' . $e->getMessage()];
}
}
$permissions_from_db = get_permissions();
$grouped_permissions = [];
if (!isset($permissions_from_db['error'])) {
foreach ($permissions_from_db as $p) {
$grouped_permissions[$p['role_id']][$p['resource']][$p['action']] = $p['fields'];
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Settings - IC-Inventory</title>
<meta name="description" content="Manage application settings, including Google OAuth and role permissions.">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="assets/css/custom.css?v=<?php echo time(); ?>">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<script src="https://unpkg.com/feather-icons"></script>
</head>
<body>
<div class="wrapper">
<?php require_once 'templates/sidebar.php'; ?>
<main id="content">
<div class="header">
<h1>Settings</h1>
</div>
<div class="surface p-4">
<?php if ($success_message): ?>
<div class="alert alert-success"><?php echo htmlspecialchars($success_message); ?></div>
<?php endif; ?>
<?php if ($error_message): ?>
<div class="alert alert-danger"><?php echo htmlspecialchars($error_message); ?></div>
<?php endif; ?>
<?php if ($is_super_admin): ?>
<div class="card mb-4">
<div class="card-header">
<h3>Google OAuth 2.0 Settings</h3>
</div>
<div class="card-body">
<p>These credentials are required for Google Login. You can get them from the <a href="https://console.cloud.google.com/apis/credentials" target="_blank">Google Cloud Console</a>.</p>
<p>The authorized redirect URI is: <code><?php echo htmlspecialchars(str_replace('settings.php', 'google-callback.php', (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'])); ?></code></p>
<form action="settings.php" method="post">
<div class="mb-3">
<label for="google_client_id" class="form-label">Client ID</label>
<input type="text" class="form-control" id="google_client_id" name="google_client_id" value="<?php echo htmlspecialchars($google_settings['google_client_id'] ?? ''); ?>">
</div>
<div class="mb-3">
<label for="google_client_secret" class="form-label">Client Secret</label>
<input type="password" class="form-control" id="google_client_secret" name="google_client_secret" value="<?php echo htmlspecialchars($google_settings['google_client_secret'] ?? ''); ?>">
</div>
<button type="submit" name="save_google_settings" class="btn btn-primary">Save Google Settings</button>
</form>
</div>
</div>
<?php endif; ?>
<?php if (can($_SESSION['user_role_id'], 'permission', 'update')): ?>
<div class="card">
<div class="card-header">
<h3>Role Permissions</h3>
</div>
<div class="card-body">
<form action="settings.php" method="post">
<div class="table-responsive">
<table class="table table-bordered permission-table">
<thead>
<tr>
<th>Role</th>
<th>Resource</th>
<th>Create</th>
<th>Read (Fields)</th>
<th>Update (Fields)</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<?php foreach ($roles as $role): ?>
<?php foreach ($resources as $resource_idx => $resource): ?>
<tr>
<?php if ($resource_idx === 0): ?>
<td rowspan="<?php echo count($resources); ?>" class="align-middle">
<strong><?php echo htmlspecialchars($role['name']); ?></strong>
<?php if ($role['id'] == 1): ?>
<span class="badge bg-primary">Super Admin</span>
<?php endif; ?>
</td>
<?php endif; ?>
<td class="align-middle"><?php echo ucfirst($resource); ?></td>
<?php foreach ($actions as $action):
$is_checked = isset($grouped_permissions[$role['id']][$resource]) && array_key_exists($action, $grouped_permissions[$role['id']][$resource]);
?>
<td class="align-middle">
<div class="form-check">
<input class="form-check-input" type="checkbox" name="permissions[<?php echo $role['id']; ?>][<?php echo $resource; ?>][<?php echo $action; ?>][enabled]" value="1" <?php echo $is_checked ? 'checked' : ''; ?>>
</div>
<?php if (in_array($action, ['read', 'update', 'create'])): ?>
<input type="text" class="form-control form-control-sm mt-1" name="permissions[<?php echo $role['id']; ?>][<?php echo $resource; ?>][<?php echo $action; ?>][fields]" placeholder="* for all" value="<?php echo htmlspecialchars($grouped_permissions[$role['id']][$resource][$action] ?? '*'); ?>">
<?php endif; ?>
</td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
<?php endforeach; ?>
</tbody>
</table>
</div>
<button type="submit" name="save_permissions" class="btn btn-primary">Save Permissions</button>
</form>
</div>
</div>
<?php endif; ?>
</div>
</main>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script src="assets/js/main.js?v=<?php echo time(); ?>"></script>
<script>
feather.replace();
</script>
</body>
</html>