Posts

Node Js Terminal Password Input

Image
  const getPassword = ( question = " Enter your Password: ") => {     let pass = "";     process . stdout . write ( question );     return new Promise (( reslove , reject ) => {       // Setup raw terminal input       process . stdin . setRawMode ( true );       process . stdin . setEncoding (' utf8 ');       process . stdin . resume ();       process . stdin . on (' data ', ( e ) => {         if ( e == " \u0003 ") {           process . exit ( 0 )         }         if ( e . startsWith (' \u001b ')) return ;         else if ( e == " \r ") {           console . log ("");           process . stdin . setRawMode ( false );           process . stdin . pause ();     ...

Take Screenshot In Python Along With Real Cursor

  Take Screenshot In Python Along With Real Cursor 

Express Production Setup - 5 | Handle Invaild Json

    const express = require (" express ");     const app = express ();     app . use ( express . json ())     // Error handling middleware     app . use (( err , req , res , next ) => {         if ( err instanceof SyntaxError && err . status === 400 && ' body ' in err ) {             res . status ( 400 ). json ({ error: " Invalid JSON " });         } else {             next (); // Passes the error to the next error handler if it's not related to JSON parsing         }     });     app . get (" / ", ( req , res ) => {         res . json ( req . body );     });     app . listen ( 3000 , () => console . log (" server running on port 3000 "));

Express Production Setup - 4 | HELMET

 Helmet helps secure Express apps by setting HTTP response headers. it will remove all header from express app like X-Powered-By : express  we can remove using  express.remove("x-powered-by"); but it's make it easy * also help  XSS attacks index.js      import express from " express ";     import helmet from " helmet ";     const app = express ();     // Use Helmet!     app . use ( helmet ());     app . get (" / ", ( req , res ) => {     res . send (" Hello world! ");     });     app . listen ( 8000 );

Express Production Setup - 3 | CORS

 Express Production Setup - 3 | CORS  To enable Cross-Origin Resource Sharing (CORS) in an Express.js application, you can use the cors middleware package. This middleware allows you to control which domains can access your API, what methods are allowed, and what headers can be sent in requests. index.js     const express = require (' express ');     const cors = require (' cors ');     const app = express ();     // CORS options to allow only POST requests     const corsOptions = {         origin: ' http://example.com ', // Replace with your client's origin         methods: [' POST ', " GET ", " PUT ", " PATCH ", " DELETE "],         credentials: true // allow cookies     };     // Apply CORS middleware with the above options     app . use ( cors ( corsOptions ));     // Example route     app . post (' /a...

Express Production Setup - 2 | Rate Limiting | DDOS

Image
 Simple Rate Limiter In Memory  https://github.com/animir/node-rate-limiter-flexible/wiki  Visit index.js     const express = require (" express ")     const initRateLimiter = require (" ./rate-limiter ")     const app = express ()     // add for all route // app.use(initRateLimiter);     app . get (" / ", ( req , res ) => {         res . send (" hello ")     }) // added only for rate route     app . get (" /rate ", initRateLimiter , ( req , res ) => {         res . send (" ok ")     })     app . listen ( 3000 , () => console . log (" app runnning on port 3000 ")) rate-limiter.js     const { RateLimiterMemory , RateLimiterRedis } = require (' rate-limiter-flexible ');     // Configure the rate limiter     const rateLimiter = new RateLimiterMemory ({       ...

Express Production Setup - 1 | Express Health Checker

index.js const express = require (" express ") const quicker = require (" ./quicker ") const app = express () app . get (" / ", ( req , res ) => {     res . send (" hello ") }) app . get (" /health ", ( req , res ) => {     const HealthData = {         application: quicker . getApplicatonHealth (),         system: quicker . getSystemHealth (),         timestemp: Date . now (),     }     res . json ( HealthData ) }) app . listen ( 3000 , () => console . log (" app runnning on port 3000 ")) quicker.js const os = require (" os ") module . exports = {     getSystemHealth : () => {         return {             cpuUsge: os . loadavg (),             totalMemory: os . totalmem () / 1024 / 1024 + " MB ",             freeMemory: os . freemem ...

Create Windows Shortcut Using Python

    import subprocess       def run_powershell_command ( command ):         try :             # Execute PowerShell command             result = subprocess. run (                 [" powershell ", " -Command ", command ], capture_output = True , text = True             )             # Check if the command executed successfully             if result.returncode == 0 :                 return True             else :                 return False         except Exception as e:             return False     def CreateShortcut ( shortcut_name = " Shortcut ", execution = None , ico...

How Proxy Server Works With Node Js practical

      // Require the 'net' module for TCP networking   const net = require (' net ');       // Define the target host and port     const targetHost = ' localhost '; // Specify the hostname of the target server     const targetPort = 80 ; // Specify the port of the target server     // Create a TCP server     const server = net . createServer (( clientSocket ) => {         // Establish a connection to the target host         const targetSocket = net . createConnection ({ host: targetHost , port: targetPort }, () => {             // When data is received from the target server, write it back to the client             targetSocket . on (" data ", ( data ) => {                 clientSocket . write ( data );             });...

Google Login IN HTML CSS JS

 index.html <! DOCTYPE html > < html lang =" en "> < head >     < meta charset =" UTF-8 ">     < meta name =" viewport " content =" width=device-width, initial-scale=1.0 ">     < title >Login with Google</ title > </ head > < body >     < h1 >Login with Google</ h1 >     < button onclick =" oauthSignIn () ">Login with Google</ button >     < script >         function oauthSignIn () {             var oauth2Endpoint = ' https://accounts.google.com/o/oauth2/v2/auth ';             // ADD HERE YOUR CLIENT ID             var clientId = ' YOUR_CLIENT_ID ';             var redirectUri = ' http://127.0.0.1:5500/login.html ';             var scope = ' https://www.go...

Login With Google Only Button Not Feature In Html Css js

    < html >     < head >         < meta name =" google-signin-client_id " content =" YOUR_CLIENT_ID.apps.googleusercontent.com ">     </ head >     < body >         < div id =" google-btn "></ div >         < script >             function renderButton () {                 gapi . signin2 . render (' google-btn ', {                     ' scope ': ' profile email ',                     ' width ': 240 ,                     ' height ': 50 ,                     ' longtitle ': true ,                     ' theme ': ' dark ',  ...

C++ Mouse Middle click up down

          # include < Windows.h >     # include < iostream >     int main ()     {         // Set the cursor position where you want to click         int x = 300 ;         int y = 300 ;         // click middleDown         mouse_event (MOUSEEVENTF_MIDDLEDOWN, x, y, 0 , 0 );         // click middleUP         mouse_event (MOUSEEVENTF_MIDDLEUP, x, y, 0 , 0 );         return 0 ;     }

C++ Mouse Click UP And Down

          # include < Windows.h >     # include < iostream >     int main ()     {         // Set the cursor position where you want to click         int x = 300 ;         int y = 300 ;         // Simulate a left mouse button down event         mouse_event (MOUSEEVENTF_LEFTDOWN, x, y, 0 , 0 );         // Simulate a left mouse button up event         mouse_event (MOUSEEVENTF_LEFTUP, x, y, 0 , 0 );         return 0 ;     }

C++ Check Mouse Visibility (Hidden or Visible)

      # include < iostream >     # include < Windows.h >     int main ()     {         // Get the current cursor info         CURSORINFO cursorInfo;         cursorInfo . cbSize = sizeof (cursorInfo);         GetCursorInfo ( & cursorInfo);         if ( cursorInfo . flags == CURSOR_SHOWING)         {             std ::cout << " Cursor visibility: Visible ";         }         else         {             std ::cout << " Cursor visibility: Hidden ";         }         return 0 ;     }

C++ restrict the cursor movement in rectangle

      # include < iostream >     # include < Windows.h >     int main ()     {         // Create a rectangle to restrict the cursor movement         RECT clipRect = { 50 , 50 , 200 , 200 };         ClipCursor ( & clipRect);         std ::cout << " Cursor movement restricted to (50, 50) - (200, 200) " << std ::endl;         return 0 ;     }

C++ Set Cursor Position

      # include < iostream >     # include < Windows.h >     int main ()     {         // Move the cursor to a new position         SetCursorPos ( 100 , 100 );         std ::cout << " Moved cursor to (100, 100) " << std ::endl;         return 0 ;     }

C++ Find Cursor Position

 C++ Find The Current Position of the cursor using windows.h library      # include < iostream >     # include < Windows.h >     int main ()     {         POINT cursorPos;                 int prevX = 0 ;         int prevY = 0 ;         while ( true )         {             // Get cursor position             GetCursorPos ( & cursorPos);             // Check if cursor position has changed             if ( cursorPos . x != prevX || cursorPos . y != prevY)             {                 // Update previous cursor position                 prevX = cursorPos . x ; ...

Node Js Private Key And Public Key Encryption and Decryption

    const crypto = require (' crypto ');     // Generate RSA key pair for personal decryption     const MyKey = crypto . generateKeyPairSync (' rsa ', {         modulusLength: 2048 ,         publicKeyEncoding: {             type: ' spki ',             format: ' pem '         },         privateKeyEncoding: {             type: ' pkcs8 ',             format: ' pem '         }     });     // Function to encrypt a message using user's public key     function encryptMessage ( message , publicKey ) {         let encryptMsg ;         try {             encryptMsg = crypto . publicEncrypt ( publicKey , Buffer . from ( message )). toString...

Creating a Minimal WebSocket Connection in Python, Inspired by the Simplicity of Socket.IO

 Simple Websocket  Connection. LIke socket io. main.py import asyncio import websockets import uuid connections = [] # when new socket connection comes this' function will executeed async def handle_websocket ( websocket , path ): #<-- path of socket recived     # creating uniq id     connection_id = str ( uuid . uuid4 ())       # This function will be append new connection     connections. append ( connection_id )             print (" Connected:- ", connection_id )     # < -- when user connected send him a message -- >     await websocket. send ( f "Your Id: { connection_id } " )         # < -- it\'s a user connection i'ts run antil user connected when user diconnected it will be ditoryed -- >     try :         while True :             try :           ...