]> PHS Git Server - phs-api.git/commitdiff
Cleaning up vpn controller and routes.
authorcharleswrayjr <charleswrayjr@gmail.com>
Tue, 16 Sep 2025 18:42:21 +0000 (13:42 -0500)
committercharleswrayjr <charleswrayjr@gmail.com>
Tue, 16 Sep 2025 18:42:21 +0000 (13:42 -0500)
src/controllers/vpn.controller.js
src/routes/vpn.routes.js

index 8b9117d9f823381eb975f0f67772242e333134ba..eaa0481af5830ed70d09ba0661b3144d853af10f 100644 (file)
@@ -1,9 +1,6 @@
 const { Client } = require( 'ssh2' );
 const fs = require( 'fs' );
 const net = require( 'net' );
-const util = require( 'util' );
-const exec = require( 'child_process' ).execSync;
-const execPromise = util.promisify(exec);
 
 /**
  *
@@ -147,7 +144,7 @@ module.exports = {
       next( error );
     } ).connect( sshConfig );
   },
-  getAvailableClients: async ( req, res, next ) => {
+  getAvailableClients:async ( req, res, next ) => {
     const conn = new Client();
     conn.on( 'ready', () => {
       const commands = [
@@ -211,7 +208,7 @@ module.exports = {
       next( error );
     } ).connect( sshConfig );
   },
-  getClients: async ( req, res, next ) => {
+  getClients:async ( req, res, next ) => {
     const conn = new Client();
     conn.on( 'ready', () => {
       const command = `cat /var/log/openvpn/openvpn-status.log`;
@@ -240,85 +237,85 @@ module.exports = {
       next( error );
     } ).connect( sshConfig );
   },
-  disconnect: async ( req, res, next ) => {
+  disconnect:async ( req, res, next ) => {
     const { clientName, duration } = req.body; // duration in minutes
     if (!clientName) {
-      return next(new createError(400, 'Client name required'));
+      return next( new createError( 400, 'Client name required' ) );
     }
 
     try {
       // Read from the OpenVPN status log to get the client's real IP
-      const statusContent = fs.readFileSync('/var/log/openvpn/openvpn-status.log', 'utf8');
+      const statusContent = fs.readFileSync( '/var/log/openvpn/openvpn-status.log', 'utf8' );
       let clientIp = null;
-      const clientLine = statusContent.split('\n').find(line =>
-        line.startsWith(`${clientName},`) && !line.startsWith('Virtual Address')
+      const clientLine = statusContent.split( '\n' ).find( line =>
+        line.startsWith( `${ clientName },` ) && !line.startsWith( 'Virtual Address' )
       );
       if (clientLine) {
-        const [, realAddress] = clientLine.split(',');
-        clientIp = realAddress.split(':')[0];
+        const [, realAddress] = clientLine.split( ',' );
+        clientIp = realAddress.split( ':' )[0];
       } else {
-        return next(new createError(404, `Client ${clientName} not connected`));
+        return next( new createError( 404, `Client ${ clientName } not connected` ) );
       }
 
       // Disconnect client via management interface
       const client = new net.Socket();
       let connectionAttempted = false;
-      client.on('connect', () => {
+      client.on( 'connect', () => {
         connectionAttempted = true;
-        client.write(`kill ${clientName}\n`);
-      });
+        client.write( `kill ${ clientName }\n` );
+      } );
 
-      client.on('data', async (data) => {
+      client.on( 'data', async ( data ) => {
         const response = data.toString();
-        if (!response.includes('ERROR:')) {
+        if (!response.includes( 'ERROR:' )) {
           if (duration && clientIp) {
             // Add iptables rule to block client IP for duration
             const conn = new Client();
-            conn.on('ready', () => {
+            conn.on( 'ready', () => {
               const commands = [
-                `sudo iptables -A INPUT -s ${clientIp} -p tcp --dport 1194 -j DROP`,
-                `sleep ${duration * 60} && sudo iptables -D INPUT -s ${clientIp} -p tcp --dport 1194 -j DROP &`,
+                `sudo iptables -A INPUT -s ${ clientIp } -p tcp --dport 1194 -j DROP`,
+                `sleep ${ duration * 60 } && sudo iptables -D INPUT -s ${ clientIp } -p tcp --dport 1194 -j DROP &`,
               ];
-              conn.exec(commands.join(' && '), (err, stream) => {
+              conn.exec( commands.join( ' && ' ), ( err, stream ) => {
                 if (err) {
                   conn.end();
                   client.destroy();
-                  return next(new createError(500, `IPTables command failed: ${err.message}`));
+                  return next( new createError( 500, `IPTables command failed: ${ err.message }` ) );
                 }
-                stream.on('close', (code) => {
+                stream.on( 'close', ( code ) => {
                   conn.end();
                   client.destroy();
                   if (code === 0) {
-                    res.json({ message: `Client ${clientName} disconnected for ${duration} minutes` });
+                    res.json( { message:`Client ${ clientName } disconnected for ${ duration } minutes` } );
                   } else {
-                    next(new createError(500, `IPTables command failed`));
+                    next( new createError( 500, `IPTables command failed` ) );
                   }
-                });
-              });
-            }).on('error', (err) => {
+                } );
+              } );
+            } ).on( 'error', ( err ) => {
               client.destroy();
-              next(new createError(500, `SSH connection failed: ${err.message}`));
-            }).connect(sshConfig);
+              next( new createError( 500, `SSH connection failed: ${ err.message }` ) );
+            } ).connect( sshConfig );
           } else {
             client.destroy();
-            res.json({ message: `Client ${clientName} disconnected` });
+            res.json( { message:`Client ${ clientName } disconnected` } );
           }
         } else {
           client.destroy();
-          next(new createError(500, `Failed to disconnect client: ${response}`));
+          next( new createError( 500, `Failed to disconnect client: ${ response }` ) );
         }
-      });
+      } );
 
-      client.on('error', (err) => {
+      client.on( 'error', ( err ) => {
         client.destroy();
-        next(new createError(500, `Management interface connection failed: ${err.message}`));
-      });
-      client.connect(7505, '192.168.1.62'); // Use host IP
+        next( new createError( 500, `Management interface connection failed: ${ err.message }` ) );
+      } );
+      client.connect( 7505, '192.168.1.62' ); // Use host IP
     } catch (error) {
-      next(new createError(500, `Failed to process disconnection: ${error.message}`));
+      next( new createError( 500, `Failed to process disconnection: ${ error.message }` ) );
     }
   },
-  getStatus: async ( req, res, next ) => {
+  getStatus:async ( req, res, next ) => {
     try {
       const conn = new Client();
       conn.on( 'ready', () => {
@@ -340,68 +337,68 @@ module.exports = {
             }
           } );
         } );
-      }).on('error', (err) => {
-        next(new createError(500, `SSH connection failed: ${err.message}`))
-      }).connect(sshConfig);
+      } ).on( 'error', ( err ) => {
+        next( new createError( 500, `SSH connection failed: ${ err.message }` ) );
+      } ).connect( sshConfig );
     } catch (error) {
-      return next(new createError(500, `Failed to check VPN status: ${error.message}`));
+      return next( new createError( 500, `Failed to check VPN status: ${ error.message }` ) );
     }
   },
-  stop: async ( req, res, next ) => {
+  stop:async ( req, res, next ) => {
     try {
       const conn = new Client();
       conn.on( 'ready', () => {
         const command = `sudo systemctl stop openvpn@server`;
-        conn.exec( command, ( err, stream ) => {
+        conn.exec( command, ( err ) => {
           if (err) {
             conn.end();
             return next( new createError( 500, `SSH command failed: ${ err.message }` ) );
           }
-          res.json({ message: 'VPN stopped successfully' });
+          res.json( { message:'VPN stopped successfully' } );
         } );
-      }).on('error', (err) => {
-        next(new createError(500, `SSH connection failed: ${err.message}`))
-      }).connect(sshConfig);
+      } ).on( 'error', ( err ) => {
+        next( new createError( 500, `SSH connection failed: ${ err.message }` ) );
+      } ).connect( sshConfig );
     } catch (error) {
-      return next(new createError(500, `Failed to stop VPN: ${error.message}`));
+      return next( new createError( 500, `Failed to stop VPN: ${ error.message }` ) );
     }
   },
-  start: async ( req, res, next ) => {
+  start:async ( req, res, next ) => {
     try {
       const conn = new Client();
       conn.on( 'ready', () => {
         const command = `sudo systemctl start openvpn@server`;
-        conn.exec( command, ( err, stream ) => {
+        conn.exec( command, ( err ) => {
           if (err) {
             conn.end();
             return next( new createError( 500, `SSH command failed: ${ err.message }` ) );
           }
-          res.json({ message: 'VPN started successfully' });
+          res.json( { message:'VPN started successfully' } );
         } );
-      }).on('error', (err) => {
-        next(new createError(500, `SSH connection failed: ${err.message}`))
-      }).connect(sshConfig);
+      } ).on( 'error', ( err ) => {
+        next( new createError( 500, `SSH connection failed: ${ err.message }` ) );
+      } ).connect( sshConfig );
     } catch (error) {
-      return next(new createError(500, `Failed to start VPN: ${error.message}`));
+      return next( new createError( 500, `Failed to start VPN: ${ error.message }` ) );
     }
   },
-  restart: async ( req, res, next ) => {
+  restart:async ( req, res, next ) => {
     try {
       const conn = new Client();
       conn.on( 'ready', () => {
         const command = `sudo systemctl restart openvpn@server`;
-        conn.exec( command, ( err, stream ) => {
+        conn.exec( command, ( err ) => {
           if (err) {
             conn.end();
             return next( new createError( 500, `SSH command failed: ${ err.message }` ) );
           }
-          res.json({ message: 'VPN restarted successfully' });
+          res.json( { message:'VPN restarted successfully' } );
         } );
-      }).on('error', (err) => {
-        next(new createError(500, `SSH connection failed: ${err.message}`))
-      }).connect(sshConfig);
+      } ).on( 'error', ( err ) => {
+        next( new createError( 500, `SSH connection failed: ${ err.message }` ) );
+      } ).connect( sshConfig );
     } catch (error) {
-      return next(new createError(500, `Failed to restart VPN: ${error.message}`));
+      return next( new createError( 500, `Failed to restart VPN: ${ error.message }` ) );
     }
   }
 };
\ No newline at end of file
index 9d0408aeccad92e311332c97d5f589069fbe547e..6817efda4f409af18f1c77df423920e20a3e8d37 100644 (file)
@@ -4,6 +4,7 @@ const { validate_auth } = require( '../middleware/routeHelpers' );
 const vpnController = require( '../controllers/vpn.controller' );
 
 module.exports = ( passport ) => {
+  router.use( validate_auth( passport ) );
 
   router.post( '/create-client', vpnController.createClient );
   router.put( '/revoke-client/', vpnController.revokeClient );