Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

client-socket-nodejs

Package Overview
Dependencies
Maintainers
1
Versions
18
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

client-socket-nodejs

Client socket in nodejs for proxy authenticateion of resource server

  • 2.0.7
  • latest
  • npm
  • Socket score

Version published
Maintainers
1
Created
Source

1. Install

npm i client-socket-nodejs cng-node-js-utils

2. Create key pair for this client before do anything follow:

// import 
const { ClientDeviceInfo } = require("client-socket-nodejs").socket;

let appName = "TEST";

let deviceKey = {
    // copy in this area for keyPair will been created for save
}

/**
 * define app key by app_app name:
 */
let clientDeviceInfo = new ClientDeviceInfo(appName, deviceKey);
clientDeviceInfo.getClientInfo()
    .then(deviceInfo => {
        console.log('deviceInfo: ', deviceInfo);
        console.log('Key pair created:', clientDeviceInfo.getKeyPair())
    })
    .catch(err => {
        console.log('Error for create key: ', err);
    });

3. Register user in socket user follow:

const { ClientSocket, ClientDeviceInfo } = require("client-socket-nodejs").socket;

let appName = "TEST";   // appName for resource server

let deviceKey = {
    // copy key pair in step 2 in here
    id: 'public_key',
    key: 'private_key',
    created_time: 'create_time format ISO yyyy-mm-dd hh:mi:ss'
}
/**
 * define app key by app_app name:
 */
let clientDeviceInfo = new ClientDeviceInfo(appName, deviceKey);


// Pass for user
let pass = 'passForUser';
let expired = 365;
let isDebug = true;

// define link for connect
let socketLink = {
    url: "http://localhost:9225"
    , path: "/socket"
    , timeout: 10000
}

// define user for reqister
let loginUser = {
    username: 'phoneNumberOrEmail',  // 'phone or email
    user_type: 'emal', // 'phone' | 'email' | 'ldap'
}

// define user info for reqister
let userInfo = {
    nickname: "NickName Demo"
    , fullname: "The name of this app for description"
    , address: "Address for this server"
    , phone: "Phone number"
    , email: "Email of this user"
    , avatar: 'Link of avatar'
    , background: 'Link of background'
}

// define one socketClient follow:
let clientSocket = new ClientSocket(clientDeviceInfo, loginUser, userInfo, pass, expired, isDebug);
// init connection to server for register user
clientSocket.init(socketLink.url, socketLink.path, socketLink.timeout)

// Waiting for token response from server:
const { waiting } = require("cng-node-js-utils")
waiting(20000, { hasData: () => clientSocket.getToken() })
    .then(msg => {
        // View token valid and copy to token for save step 4:
        console.log("***>Current TOKEN connected: ", clientSocket.getToken());
    })

4. Login by user for token if token expire

const { ClientSocket, ClientDeviceInfo } = require("client-socket-nodejs").socket;

let appName = "TEST";   // appName for resource server

let deviceKey = {
    // copy key pair in step 2 in here
    id: 'public_key',
    key: 'private_key',
    created_time: 'create_time format ISO yyyy-mm-dd hh:mi:ss'
}
/**
 * define app key by app_app name:
 */
let clientDeviceInfo = new ClientDeviceInfo(appName, deviceKey);

// Pass for user
let pass = 'passForUser';
let expired = 365;
let isDebug = true;

// define link for connect
let socketLink = {
    url: "http://localhost:9225"
    , path: "/socket"
    , timeout: 10000
}

// define user for reqister
let loginUser = {
    username: 'phoneNumberOrEmail',  // 'phone or email
    user_type: 'emal', // 'phone' | 'email' | 'ldap'
}

// define user info for reqister
let userInfo; // no need to define;

// define one socketClient follow:
let clientSocket = new ClientSocket(clientDeviceInfo, loginUser, userInfo, pass, expired, isDebug);
// init connection to server for register user
clientSocket.init(socketLink.url, socketLink.path, socketLink.timeout)

// Waiting for token response from server:
const { waiting } = require("cng-node-js-utils")
waiting(20000, { hasData: () => clientSocket.getToken() })
    .then(msg => {
        // View token valid and copy to token for save step 4:
        console.log("***>Current TOKEN connected: ", clientSocket.getToken());
    })

5. Init socket connection with token


// define class for socket
const { ClientSocket, ClientDeviceInfo } = require("../socket");

let appName = "TEST";   // appName for token register in step 3:

let deviceKey = {
    // copy key pair in step 2 in here
    id: 'public_key',
    key: 'private_key',
    created_time: 'create_time format ISO yyyy-mm-dd hh:mi:ss'
}

let token = "copy Token in step 3 in here";

/**
 * define app key by app_app name:
 */
let clientDeviceInfo = new ClientDeviceInfo(appName, deviceKey, token);


// define one socketClient follow:
let clientSocket = new ClientSocket(clientDeviceInfo, loginUser, userInfo, pass, expired, isDebug);
// init connection to server for register user
clientSocket.init(socketLink.url, socketLink.path, socketLink.timeout)

// Waiting for token response from server:
const { waiting } = require("cng-node-js-utils")
waiting(20000, { hasData: () => clientSocket.getToken() })
    .then(msg => {
        // View token valid and copy to token for save step 4:
        console.log("***>Current TOKEN connected: ", clientSocket.getToken());
    })

6. Make proxy authentication server socket

npm i client-socket-nodejs
  • 6.1 create key pair for this server

  • 6.2 register new user (ask admin socket server)

  • 6.3 login and get token with expired date

  • 6.4 copy keyPair and token follow file config socketVerify

  • 6.5 create handler for verify token in ./handler/client-socket/socket-verify.js or any for secret token and private_key for this server:

/**
 * Hàm này giao tiếp khởi tạo client Handler giao tiếp máy chủ socket để verify token và get user từ socket server
 * Điều kiện là máy này đã thiết lập được kênh liên lạc với máy chủ socket rồi
 * Được cấp token có hiệu lực rồi
 */

// test thử kênh liên lạc với máy chủ sau khi đã đăng ký được token
const { ClientSocket, ClientDeviceInfo, ClientHandler } = require("client-socket-nodejs");

let appName = "TEST";  // tên này phải trùng với tên khi cấp token đó
// PHẦN ĐƯỢC TẠO bởi client:
// sử dụng test/create-key-pair.js để tạo key trước, sau đó copy khóa đó vào dưới đây
let deviceKey = {
    id: 'MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAMYLyjaOwTyajv1GMlBVim70bw4DUERzHhqobvN+2As8j7qGTNNl7FoZjCRMeVJcvLSerpCT+RWA695bmLv91RcCAwEAAQ==',
    key: 'MIIBOwIBAAJBAMYLyjaOwTyajv1GMlBVim70bw4DUERzHhqobvN+2As8j7qGTNNl7FoZjCRMeVJcvLSerpCT+RWA695bmLv91RcCAwEAAQJAA80yIn33A5zL5dy1Fomt0Jdskk5J+iZji4t0JcRnjT+hsKroIjwVNS9z58MXmwI1u/s3WljkAGTLvOjepMlPYQIhAPDeu1YxUS7QAg0VtaCwm1R6sxs4Fub+pcbvYrOf+s8fAiEA0nxvOfZI8wE0/CoP2j1D5sNKinsImVt52HpyrWvK0wkCIQDKWzSjWtdLLrEqcPyfvP8h39ssmNiUw4ZeNKqFIXfCHQIgfyr03DUDL+XbyDn1Z+o52vLEV1QsBtNwkyyvmj0UxlkCIQCC43kV/Jc6FegQd/IZFE4YnGaqSii+y2/gz2O6xpGnjQ==',
    created_time: '2020-09-12 09:02:09'
}
// PHẦN ĐƯỢC TẠO bởi server socket:
// token cho máy chủ cuongdq:
let token = "eyJ1c2VybmFtZSI6IjA5MDM1MDAxMjUiLCJkZXZpY2VfaWQiOjE1LCJpYXQiOjE1OTk4ODM4NDY2OTQsImV4cCI6MTYzMTQxOTg0NjY5NH0=.WlJGaDdDYkhFOWczZXdXdVdvOUsrV2NjV2U5bVBtTlRtKzI2WGw0Vi9leDZzWjkwcmVEOGlsMHNUazlFTXVxTC9DTFk0b3BSWHdtOVJ4V2t2a1ZoUHc9PQ==";

// nếu ta cấp token và deviceKey thì thông tin user có thể bỏ qua
let clientDeviceInfo = new ClientDeviceInfo(appName, deviceKey, token);

let socketLink = {
    url: "http://localhost:9225"
    , path: "/socket"
    , timeout: 10000
}

// byPASS for check
let byPass = true;  // for false if advance user to get user info from socket server
let clientSocket = new ClientSocket(clientDeviceInfo);
clientSocket.init(socketLink.url, socketLink.path, socketLink.timeout)

const clientHandler = new ClientHandler(clientSocket, socketLink.url, socketLink.path, byPass)
module.exports = {
    verifyToken: clientHandler.verifyToken,
    getResource: clientHandler.getResource
}
  • 6.6 in any routes for verify token by socket proxy
    // processor for getToken + post json_data + post form_data
    const { postHandler } = require("cng-node-js-utils")
    // processor for verify token,  return: req.user if success or req.error if fail
    const socketVerify = require("../../handlers/client-socket/socket-verify")

7. Javascript package for login form:

# install key
npm i client-socket-nodejs@latest
# create new KEYPAIRs for your app
node ./client-socket-nodejs/test/create-key-pair.js 
// import lib
const { ClientInputInterface } = require("client-node-js");

// copy keypairs when you create here:
const deviceKey = {
    // copy keyPair here
}

// Define your app name
const APP_NAME = "WEB-DEMO";
// Define device class with appname and keypair
let clientDeviceInfo = new ClientDeviceInfo(APP_NAME, deviceKey);

// define link to server (ask your admin socket Server for link)
const socketLink = {
    url: "http://localhost:9225"
    , path: "/socket"
    , timeout: 10000
}

// ask for admin socket server for user init no pass in server database

// Define client 
let client = new ClientInputInterface(APP_NAME, deviceKey, socketLink);

const { waiting } = require("cng-node-js-utils");

// if token saved
let myToken =
  "yourtoken.yoursign";

// login BY Token 
 client
    .loginByToken(myToken)
    .then((data) => {
      console.log("data", data);
    })
    .catch((err) => {
      console.log("err", err);
    });


// login by USER form

// const loginForm = {
//   username: "yourEmail@email", // 'phone or email
//   user_type: "email", // 'phone' | 'email' | 'ldap'
//   password: "xxxx",
//   expired: 365,
// };

// client
//   .loginByUser(
//     loginForm.username,
//     loginForm.user_type,
//     loginForm.password,
//     loginForm.expired
//   )
//   .then((data) => {
//     console.log("LoginData", data);
//   })

Login IN WEB default index.html

<html>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<!-- <script src="https://cuongdq.no-ip.info/socket/api/js/www.client.socket.login.js"></script> -->
<script src="./www.client.socket.login.js"></script>
<script>

// app demo
  const APP_NAME = "WEB-DEMO-CUONGDQ";
  // Key demo
  const deviceKey = {
    created_time: "2020-09-17 22:25:09",
    id: "MFswDQYJKoZIhvcNAQEBBQADSgAwRwJAea/IOT6QMv/kw1W8aYzlIG/twyKmjYggL94DbduYC8t7QmZ0JCpK43ugArxzVmXnAU6oe0wiuH57yS4cKLntUQIDAQAB",
    key: "MIIBOQIBAAJAea/IOT6QMv/kw1W8aYzlIG/twyKmjYggL94DbduYC8t7QmZ0JCpK43ugArxzVmXnAU6oe0wiuH57yS4cKLntUQIDAQABAkA/81ucif6qbsVAyuwL5Jn95BTmOm2hb+rKfTj8IS3U9EjAMs4ppC79uIMGL8zAQiftY2DOs/QFPgBlHRYBGGlhAiEA6Ar9ZB/Jk/jRvsXfrlbNog95AQrXSsv7ydvsUh9sqrUCIQCGQAVXdSzYBeLaodpatYrrLMRRwOc6iH6rTaYypN3trQIhALhfKxEoNLnPRZEIln9m10MCekn6vC/hPnIYvYBPGb/VAiAHzXbCA4RstcLelCOdvAlr67kpSz3lMAO0rxmmveBMLQIgQx8NQrTVAWvHghZEqEmy/1IAKaziMf4FQQgPt0UGAcc="
  };

  // socket server link
  const socketLink = {
    url: "http://localhost:9225",
    path: "/socket",
    timeout: 10000,
  };

  // key pair auto:
  // let clientDeviceInfo = new clientSocketLogin.ClientDeviceInfo();
  // clientDeviceInfo.getClientInfo()
  //   .then(deviceInfo => {
  //     // console.log('deviceInfo: ', deviceInfo);
  //     console.log('KeyPair:', clientDeviceInfo.getKeyPair())
  //   })
  //   .catch(err => {
  //     console.log('Error: ', err);
  //   });

  let client = new clientSocketLogin.ClientInputInterface(APP_NAME, deviceKey, socketLink);

  // check device ready (socket communicated with server)
  client.getDeviceId()
    .then(deviceId => {
      console.log('The device ready: ', deviceId);
    })

  // token saved
  let myToken =
    "xeyJ1c2VybmFtZSI6ImN1b25nLmRxIiwiZGV2aWNlX2lkIjozMSwiaWF0IjoxNjAwMzM3NzU4MzI1LCJleHAiOjE2MzE4NzM3NTgzMjV9.QVFFL2FJR1dRamV5Zm9Ba1I0RGNGT0RtUVBYdlBBUUxMNjkxY2hkYVc2d1pIT0krSFI5ekRZS29Ma3VXT3o2SzNxTFdycVFodkRoMDgvSXhPclB3WHc9PQ==";

// if login by token is
  // client
  //   .loginByToken(myToken)
  //   .then((tokenData) => {
  //     if (tokenData.userInfo) {
  //       console.log("Login OK tokenData", tokenData);
  //     } else {
  //       console.log("Token invalid");
  //     }
  //   })

  const loginForm = {
    username: "0123456789", // 'phone or email
    user_type: "phone", // 'phone' | 'email' | 'ldap'
    password: "12345",
    expired: 1,
  };

// if login by user is
  client
    .loginByUser(
      loginForm.username,
      loginForm.user_type,
      loginForm.password,
      loginForm.expired
    )
    .then((tokenData) => {
      if (tokenData.userInfo) {
        console.log("Login OK tokenData", tokenData);
      } else {
        console.log("Login Fail by user");
      }
    })

</script>

<body>
  This is your page for login form
</body>

</html>

proxy token vefify:

// define your config in  
const socketConfig = require("../../cfg/resource-server-socket-cfg");
// include the module
const { VerifyToken } = require("client-socket-nodejs");
// init proxy server connection:
let verifyToken = new VerifyToken(socketConfig);
// verify client token by command:
// token have info of: {username, device_id, iat, exp}
// verifyToken.verify(clientToken,clientDevicename)

FAQs

Package last updated on 31 Dec 2020

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc