71 lines
2.5 KiB
JavaScript
71 lines
2.5 KiB
JavaScript
const express = require('express');
|
|
const fs = require('fs');
|
|
const db = require('../db/connection');
|
|
const { setuid } = require('process');
|
|
const router = express.Router();
|
|
|
|
|
|
router.use('/', (req, res) => {
|
|
const result = req.headers['x-username'];
|
|
|
|
console.log(req.headers['x-username']);
|
|
if (!result) {
|
|
return res.status(400).json({ error: "x-username header is required" });
|
|
}
|
|
const pre_username = JSON.parse(result);
|
|
const username = pre_username.token;
|
|
// Check if user exists and has permissions
|
|
console.log(username);
|
|
const query = 'SELECT perms FROM users WHERE username = ?';
|
|
db.query(query, [username], (err, results) => {
|
|
if (err) {
|
|
console.error('Database error:', err);
|
|
return res.status(500).json({ error: "Internal server error" });
|
|
}
|
|
|
|
if (results.length === 0) {
|
|
return res.status(401).json({ error: "Unauthorized" });
|
|
}
|
|
|
|
const perms = results[0].perms;
|
|
if (perms !== 'admin') {
|
|
return res.status(403).json({ error: "Insufficient permissions" });
|
|
}
|
|
|
|
// Handle config updates
|
|
if (req.method === 'POST') {
|
|
try {
|
|
const newConfig = req.body;
|
|
console.log(newConfig);
|
|
const existingConfig = JSON.parse(fs.readFileSync('config.json', 'utf8'));
|
|
const updatedConfig = { ...existingConfig, ...newConfig };
|
|
fs.writeFileSync('config.json', JSON.stringify(updatedConfig, null, 2));
|
|
res.json({ message: "Config updated successfully" });
|
|
} catch (error) {
|
|
console.error('Error writing config:', error);
|
|
res.status(500).json({ error: "Failed to update config" });
|
|
}
|
|
}
|
|
|
|
// Handle config reads
|
|
else if (req.method === 'GET') {
|
|
try {
|
|
const configData = fs.readFileSync('config.json', 'utf8');
|
|
if (!configData) {
|
|
return res.status(500).json({ error: "Config file is empty" });
|
|
}
|
|
const config = JSON.parse(configData);
|
|
res.json(config);
|
|
} catch (error) {
|
|
console.error('Error reading config:', error);
|
|
res.status(500).json({ error: "Failed to read config" });
|
|
}
|
|
}
|
|
|
|
else {
|
|
res.status(405).json({ error: "Method not allowed" });
|
|
}
|
|
});
|
|
});
|
|
|
|
module.exports = router; |