Skip to content

Commit

Permalink
fix: converted to class
Browse files Browse the repository at this point in the history
  • Loading branch information
frankpagan committed Dec 30, 2023
1 parent 5d33135 commit 45b7ea5
Showing 1 changed file with 161 additions and 161 deletions.
322 changes: 161 additions & 161 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,104 @@ const os = require('os');

const available = "/etc/nginx/sites-available/"
const enabled = "/etc/nginx/sites-enabled/"
class CoCreateNginx {
constructor() {
this.init()
}

init() {
exec('nginx -v', (error) => {
if (error) {
console.log('Nginx not found, installing...');
this.installNginx();
} else {
console.log('Nginx is already installed.');
}
});
}

async installNginx() {
try {
const platform = os.platform();

if (platform === 'linux') {
// For Debian/Ubuntu
await exec('sudo apt-get update && sudo apt-get install -y nginx');
await exec("sudo ufw allow 'Nginx Full'");
await exec('sudo chmod 777 /etc/nginx/sites-available');
await exec('sudo chmod 777 /etc/nginx/sites-enabled');
if (!fs.existsSync(`${enabled}main`)) {
// let main = `server {
// listen 80 default_server;
// listen [::]:80 default_server;


// server_name _;
// }`
let main = `server {
listen 80 default_server;
listen [::]:80 default_server;
async function createServer(hosts) {
const response = {}
if (!Array.isArray(hosts))
hosts = [hosts]
server_name _;
location / {
proxy_pass http://localhost:3000; # Forward traffic to your app on port 3000
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
}
}`

for (let host of hosts) {
const hostParts = host.split('.')
const domain = hostParts[0];
const tld = hostParts[1];
const server = `
fs.writeFileSync(`${available}main`, main)
await exec(`sudo ln -s ${available}main ${enabled}`);

if (fs.existsSync(`${enabled}default`))
fs.unlinkSync(`${enabled}default`)
if (fs.existsSync(`${available}default`))
fs.unlinkSync(`${available}default`)

let test = await exec(`sudo nginx -t`);
if (test.stderr.includes('test is successful')) {
await exec(`sudo systemctl reload nginx`);
console.log('main test passed reloading nginx')
response['main'] = true
} else {
console.log('main test failed')
response['main'] = false
}

}

} else if (platform === 'darwin') {
// TODO: For macOS
await exec('brew install nginx');
} else if (platform === 'win32') {
// TODO: For Windows, assuming Chocolatey is installed
await exec('choco install nginx');
} else {
console.log('Unsupported OS');
}

console.log('Nginx installed successfully');

} catch (error) {
console.error('Failed to Nginx:');
}
}

async createServer(hosts) {
const response = {}
if (!Array.isArray(hosts))
hosts = [hosts]

for (let host of hosts) {
const hostParts = host.split('.')
const domain = hostParts[0];
const tld = hostParts[1];
const server = `
server {
server_name ~^(?<sub>.+)\.${domain}\.${tld} ${host};
Expand Down Expand Up @@ -44,174 +131,87 @@ server {
`;

fs.writeFileSync(`${available}${host}`, server)
fs.writeFileSync(`${available}${host}`, server)

if (!fs.existsSync(`${enabled}${host}`))
await exec(`sudo ln -s ${available}${host} ${enabled}`);
if (!fs.existsSync(`${enabled}${host}`))
await exec(`sudo ln -s ${available}${host} ${enabled}`);

let test = await exec(`sudo nginx -t`);
if (test.stderr.includes('test is successful')) {
await exec(`sudo systemctl reload nginx`);
console.log(host, 'test passed reloading nginx')
response[host] = true
} else {
console.log(host, 'test failed')
response[host] = false
let test = await exec(`sudo nginx -t`);
if (test.stderr.includes('test is successful')) {
await exec(`sudo systemctl reload nginx`);
console.log(host, 'test passed reloading nginx')
response[host] = true
} else {
console.log(host, 'test failed')
response[host] = false
}
}
}

return response
}

async function deleteServer(hosts) {
const response = {}
if (!Array.isArray(hosts))
hosts = [hosts]
for (let host of hosts) {
if (fs.existsSync(`${enabled}${host}`))
fs.unlinkSync(`${enabled}${host}`)
if (fs.existsSync(`${available}${host}`))
fs.unlinkSync(`${available}${host}`)

response[host] = true
return response
}
return response
}

async function hasServer(hosts) {
if (!Array.isArray(hosts))
hosts = [hosts]
for (let host of hosts) {
const { stdout, stderr } = await exec(`grep -Ri 'server_name.*${host}' /etc/nginx/sites-enabled`)
if (stderr) {
console.error(`exec error: ${err}`);
return;
}
if (stdout) {
console.log(`Host found in the following configuration file(s):\n${stdout}`);
async deleteServer(hosts) {
const response = {}
if (!Array.isArray(hosts))
hosts = [hosts]
for (let host of hosts) {
if (fs.existsSync(`${enabled}${host}`))
fs.unlinkSync(`${enabled}${host}`)
if (fs.existsSync(`${available}${host}`))
fs.unlinkSync(`${available}${host}`)

} else {
console.log('Host not found in Nginx configurations.');
response[host] = true
}

if (stderr) console.error(`stderr: ${stderr}`);

}
}

async function installNginx() {
try {
const platform = os.platform();

if (platform === 'linux') {
// For Debian/Ubuntu
await exec('sudo apt-get update && sudo apt-get install -y nginx');
await exec("sudo ufw allow 'Nginx Full'");
await exec('sudo chmod 777 /etc/nginx/sites-available');
await exec('sudo chmod 777 /etc/nginx/sites-enabled');
if (!fs.existsSync(`${enabled}main`)) {
// let main = `server {
// listen 80 default_server;
// listen [::]:80 default_server;


// server_name _;
// }`
let main = `server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
location / {
proxy_pass http://localhost:3000; # Forward traffic to your app on port 3000
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
return response
}
}`

fs.writeFileSync(`${available}main`, main)
await exec(`sudo ln -s ${available}main ${enabled}`);

if (fs.existsSync(`${enabled}default`))
fs.unlinkSync(`${enabled}default`)
if (fs.existsSync(`${available}default`))
fs.unlinkSync(`${available}default`)

let test = await exec(`sudo nginx -t`);
if (test.stderr.includes('test is successful')) {
await exec(`sudo systemctl reload nginx`);
console.log('main test passed reloading nginx')
response['main'] = true
} else {
console.log('main test failed')
response['main'] = false
}

async hasServer(hosts) {
if (!Array.isArray(hosts))
hosts = [hosts]
for (let host of hosts) {
const { stdout, stderr } = await exec(`grep -Ri 'server_name.*${host}' /etc/nginx/sites-enabled`)
if (stderr) {
console.error(`exec error: ${err}`);
return;
}
if (stdout) {
console.log(`Host found in the following configuration file(s):\n${stdout}`);

} else if (platform === 'darwin') {
// TODO: For macOS
await exec('brew install nginx');
} else if (platform === 'win32') {
// TODO: For Windows, assuming Chocolatey is installed
await exec('choco install nginx');
} else {
console.log('Unsupported OS');
}
} else {
console.log('Host not found in Nginx configurations.');
}

console.log('Nginx installed successfully');
if (stderr) console.error(`stderr: ${stderr}`);

} catch (error) {
console.error('Failed to Nginx:');
}
}
}

function init() {
exec('nginx -v', (error) => {
if (error) {
console.log('Nginx not found, installing...');
installNginx();
} else {
console.log('Nginx is already installed.');
}
});
}
updateSudoers() {
const newRules = [
'appuser ALL=(ALL) NOPASSWD: /bin/ln -s /etc/nginx/sites-available/* /etc/nginx/sites-enabled/*',
'appuser ALL=(ALL) NOPASSWD: /usr/sbin/nginx -t',
'appuser ALL=(ALL) NOPASSWD: /bin/systemctl reload nginx',
// Include any specific command or script you've prepared for safely writing to sites-available
// 'appuser ALL=(ALL) NOPASSWD: /path/to/your/specific_command_or_script'
];

// Convert array of rules into a single string, each rule separated by a newline
const rulesStr = newRules.join("\\n");
const cmd = `echo '${rulesStr}' | sudo EDITOR='tee -a' visudo`;

exec(cmd, (error, stdout, stderr) => {
if (error) {
console.error(`Error: ${error}`);
return;
}
if (stderr) {
console.error(`Stderr: ${stderr}`);
return;
}
console.log(`Sudoers updated: ${stdout}`);
});
}

function updateSudoers() {
const newRules = [
'appuser ALL=(ALL) NOPASSWD: /bin/ln -s /etc/nginx/sites-available/* /etc/nginx/sites-enabled/*',
'appuser ALL=(ALL) NOPASSWD: /usr/sbin/nginx -t',
'appuser ALL=(ALL) NOPASSWD: /bin/systemctl reload nginx',
// Include any specific command or script you've prepared for safely writing to sites-available
// 'appuser ALL=(ALL) NOPASSWD: /path/to/your/specific_command_or_script'
];

// Convert array of rules into a single string, each rule separated by a newline
const rulesStr = newRules.join("\\n");
const cmd = `echo '${rulesStr}' | sudo EDITOR='tee -a' visudo`;

exec(cmd, (error, stdout, stderr) => {
if (error) {
console.error(`Error: ${error}`);
return;
}
if (stderr) {
console.error(`Stderr: ${stderr}`);
return;
}
console.log(`Sudoers updated: ${stdout}`);
});
}

init();

process.on('certificateCreated', (host) => {
createServer(host)
});

module.exports = { createServer, hasServer, deleteServer }
module.exports = CoCreateNginx

0 comments on commit 45b7ea5

Please sign in to comment.