Support for multiple user types by Passport-local mongoose node.js

I wanted two types of users logging in (User, Client). How exactly can I create localStrategies, serialize and deserialize user for both types in my app.js
I have two separate schemas, both using the PassportLocalMongoose plugin.

I currently configuraing my passport like below,

var User = require('./models/User');
var Client= require('./models/Client');
passport.use(new LocalStrategy(User.authenticate(), Client.authenticate()));
passport.serializeUser(User.serializeUser(), Client.serializeUser());
passport.deserializeUser(User.deserializeUser(), Client.deserializeUser());

The problem lies when I try to register. Registering as a User works, but as a client shows “Unauthorized” error.
How can I fix this problem?

Cannot find module ‘…/models/user’ nodejs

I’ve got a problem with require.
I’ve got a users.js inside folder ‘router’. In users.js everything works great with

let User = require('../models/user');

But when users.js file getting bigger I wanted to part this file into a few files like login.js regiseter.js and so on. I created a folder ‘users’ inside ‘router’ and put there those files (login.js, register.js)

I changed my require to

let User = require('.../models/user');

Now I got an error:

Cannot find module ‘…/models/user’
enter image description here

Unable to debug the Nodejs application in Visual studio code

I have launch configuration for my Nodejs with ExpressJs application, the debugger mode starts and then immediately stops.. It doesn’t keep on listening.. any help is much appreciated.

{
    "name": "Launch via NPM",
    "type": "node",
    "request": "launch",
    "cwd": "${workspaceFolder}/index.js",
    "runtimeExecutable": "npm",
    "runtimeArgs": [
        "run-script", "debug"
    ],
    "port": 9229
}

Below is my server configuration

app.listen(PORT, HOST, () => {
  process.stdout.write(Server is listening on ${PORT} (${NODE_ENV})\n)
  log.info(Server is listening on ${PORT} (${NODE_ENV})\n)
})

Start commands in package.json

“devStart”: “nodemon –exec babel-node index.js”,

“start”: “per-env”,

“start:development”: “nodemon –exec babel-node index.js”,

AES-256-CTR Encryption in node JS and decryption in Java

I am trying to encode in nodejs and decryption for the same in nodejs works well. But when I try to do the decryption in Java using the same IV and secret, it doesn’t behave as expected.

Here is the code snippet:

Encryption in nodeJs:

var crypto = require('crypto'),
algorithm = 'aes-256-ctr',
_ = require('lodash');

var secret = 'd6F3231q7d19428743234@123nab@234';

function encrypt(text, secret) {
    var iv = crypto.randomBytes(16);
    console.log(iv);
    var cipher = crypto.createCipheriv(algorithm, new Buffer(secret), iv);
    var encrypted = cipher.update(text);

    encrypted = Buffer.concat([encrypted, cipher.final()]);

    return iv.toString('hex') + ':' + encrypted.toString('hex');
}
var encrypted = encrypt("8123497494", secret);
console.log(encrypted);

And the output is:

<Buffer 94 fa a4 f4 a1 3c bf f6 d7 90 18 3f 3b db 3f b9>
94faa4f4a13cbff6d790183f3bdb3fb9:fae8b07a135e084eb91e

Code Snippet for decryption in JAVA:

public class Test {

    public static void main(String[] args) throws Exception {
        String s = "94faa4f4a13cbff6d790183f3bdb3fb9:fae8b07a135e084eb91e";
        String seed = "d6F3231q7d19428743234@123nab@234";

        decrypt(s, seed);
    }

    private static void decrypt(String s, String seed)
            throws NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException, InvalidKeyException,
            InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
        String parts[] = s.split(":");
        String ivString = parts[0];
        String encodedString = parts[1];
        Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");

        byte[] secretBytes = seed.getBytes("UTF-8");

        IvParameterSpec ivSpec = new IvParameterSpec(hexStringToByteArray(ivString));

        /*Removed after the accepted answer
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] thedigest = md.digest(secretBytes);*/ 

        SecretKeySpec skey = new SecretKeySpec(thedigest, "AES");

        cipher.init(Cipher.DECRYPT_MODE, skey, ivSpec);
        byte[] output = cipher.doFinal(hexStringToByteArray(encodedString));

        System.out.println(new String(output));
    }
}

Output: ?s?8??

I am getting some junk value in the response. Tried a lot of options, but none of them seem to be working. Any lead/help is appreciated.

How to hide function implementation from caller in nodejs

I am exporting a js module via module.exports. The caller function requires this module and calls the exported functions.

Code looks something likes this:

file1.js

module.exports = {
 Info: showInfo
}

function showInfo(param1, callback) {
 callback(null, getInfo(param1))
}
let secretCode = 'xyz';

function getInfo(p1) {
 return EncodeInfo(param1, secretCode);
}

function EncodeInfo(p2, p3) {
 //some code
}

file2.js

var f1 = require('./file1');

f1.Info("some value");

Now the thing is that file2.js is provided by the customer at runtime and code gets deployed to the server. Server entry point functions call an entry function in file2.js. file2.js just has access to core node libraries, a logging functionality and request module.

I need to hide whats written inside file1.js. Customer can do something like this to see the code

console.log(f1.Info.toString());
//this will print following
/*
function showInfo(param1, callback){
    callback(null, getInfo(param1)) 
}
*/

This is ok, as getInfo() code is hidden. Also, other private functions and variables are hidden. Also to mention that customer cannot install any other node modules and only provides file2.js

Please note that I cannot control what he is writing in file2.js, neither I can scan before merging the file2.js with rest of the code.

Question 1:
The question is simply that is my assumption correct? Or is there any way where he can see the rest of the code implementation or any other details of imported(require) modules? Maybe through prototype?

Question 2:
Is there any way he can see the details of servers entry point function implementation. The customer does have access to process and hence process.env, but that is ok. I am more bothered about other file’s code.

How to structure a Node MongoDB project?

In my Node.js project with mongodb.js (note, not mongoose) I have the following structure:

  • index.js
    • sets up db connection (db.js)
    • sets up express server (api.js)
  • api.js
    • starts the server
    • defines routes and calls db (db.js)
  • database.js
    • starts db connection, db is defined as a global in the file
    • each db function uses the global db variable

Roughly like this:

// database.js
let db;

module.exports = {
    connect() {
       db = set value here;
    },
    findUser() {
      db.find(query);
    }
};

Now I’d like to restructure each db function to it’s own folder like database/user.js, but I’m not sure how to handle the global db var with separate files?

// database/users.js
module.exports = {
    findUser() {
        db.find(query); <-- how to pass the db connection
    }
};

I’d like to avoid having to pass the db as parameter to all functions. What’s the common way to structure this?

Connect node app to Openfire

I have my nodejs server and my Openfire server, I wanted to connect both and found out that there is a plugin for nodejs in Openfire. I have install it and placed my node project in /opt/openfire/nodejs.

I have not found any documentation of what steps should I follow next. I have installed xmpp.js library too but don’t know how should I connect it to the server through it. Neither do I know how to access or what is the url to my node app through openfire.

On the system settings in Openfire I have written the following properties so that in the Nodejs tab an entry appears

js.folder.server server.js

js.folder.server.path /opt/openfire/nodejs/folder

I am really new to this and haven’t found any help while searching

Error running Selenium automatically from Nightwatch.js with Firefox

I want to start Selenium Server automatically when I run a nightwatch.js test case. I changed the selenium settings on nightwatch.json to:

  "selenium" : {
    "start_process" : true,
    "server_path" : "./selenium/selenium391.jar",
    "log_path" : "C:/Projects/reports",
    "host" : "127.0.0.1",
    "port" : 4444,
    "cli_args" : {
      "webdriver.chrome.driver" : "./selenium/chromedriver.exe",
      "webdriver.ie.driver" : "./selenium/IEDriverServer.exe",
      "webdriver.firefox.profile" : "./selenium/geckodriver.exe"
    }
  },

This configuration works when I use Chrome as browser. However I got an error when I run it using Firefox:

ERROR Response 500 POST /wd/hub/session (312ms) { value:
   { message: 'Unable to create new service: GeckoDriverService\nBuild info: ver
sion: \'3.9.1\', revision: \'63f7b50\', time: \'2018-02-07T22:42:28.403Z\'\nSyst
em info: host: \'IBS-PC192\', ip: \'192.168.1.115\', os.name: \'Windows 7\', os.
arch: \'x86\', os.version: \'6.1\', java.version: \'1.8.0_112\'\nDriver info: dr
iver.version: unknown',
     error: 'session not created' },
  status: 33 }

If I run the Selenium Server manually, the nightwatch test works on Firefox. How do I resolve this?

nightwatch.json file: for Firefox

{
  "src_folders" : ["tests"],
  "output_folder" : "reports",
  "custom_commands_path" : "",
  "page_objects_path" : "",
  "custom_assertions_path" : "",
  "globals_path" : "C:/Projects/global/globals.js",
  "live_output" : false,
  "parallel_process_delay" : 10,
  "disable_colors": false,
  "test_workers" : false,

  "selenium" : {
    "start_process" : true,
    "server_path" : "./selenium/selenium391.jar",
    "log_path" : "C:/Projects/reports",
    "host" : "127.0.0.1",
    "port" : 4444,
    "cli_args" : {
      "webdriver.chrome.driver" : "./selenium/chromedriver.exe",
      "webdriver.ie.driver" : "./selenium/IEDriverServer.exe",
      "webdriver.firefox.profile" : "./selenium/geckodriver.exe"
    }
  },

  "test_settings" : {
    "default" : {
      "launch_url" : "http://localhost",
      "selenium_host" : "127.0.0.1",
      "selenium_port" : 4444,
      "silent" : true,
      "disable_colors": false,
      "screenshots" : {
        "enabled" : false,
        "path" : ""
      },
      "desiredCapabilities" : {
        "browserName" : "firefox",
        "javascriptEnabled" : true,
        "acceptSslCerts" : true
      }
    },

The content of selenium-debug.log

14:24:00.791 INFO - Selenium build info: version: '3.9.1', revision: '63f7b50'
14:24:00.791 INFO - Launching a standalone Selenium Server on port 4444
2018-02-16 14:24:00.853:INFO::main: Logging initialized @280ms to org.seleniumhq.jetty9.util.log.StdErrLog
2018-02-16 14:24:00.962:INFO:osjs.Server:main: jetty-9.4.7.v20170914, build timestamp: 2017-11-21T22:27:37+01:00, git hash: 82b8fb23f757335bb3329d540ce37a2a2615f0a8
2018-02-16 14:24:00.978:WARN:osjs.SecurityHandler:main: ServletContext@o.s.j.s.ServletContextHandler@5ed7a6{/,null,STARTING} has uncovered http methods for path: /
2018-02-16 14:24:00.978:INFO:osjsh.ContextHandler:main: Started o.s.j.s.ServletContextHandler@5ed7a6{/,null,AVAILABLE}
2018-02-16 14:24:01.352:INFO:osjs.AbstractConnector:main: Started ServerConnector@18f65a4{HTTP/1.1,[http/1.1]}{0.0.0.0:4444}
2018-02-16 14:24:01.352:INFO:osjs.Server:main: Started @782ms
14:24:01.352 INFO - Selenium Server is up and running on port 4444
2018-02-16 14:24:01.540:INFO:osjshC.ROOT:qtp17048053-10: org.openqa.selenium.remote.server.WebDriverServlet-132ec19: Initialising WebDriverServlet
14:24:01.618 INFO - Found handler: org.openqa.selenium.remote.server.commandhandler.BeginSession@1e1a802
14:24:01.618 INFO - /session: Executing POST on /session (handler: BeginSession)
14:24:01.680 INFO - Capabilities are: Capabilities {acceptSslCerts: true, browserName: firefox, javascriptEnabled: true, name: Google Wiki}
14:24:01.680 INFO - Capabilities {acceptSslCerts: true, browserName: firefox, javascriptEnabled: true, name: Google Wiki} matched class org.openqa.selenium.remote.server.ServicedSession$Factory (provider: org.openqa.selenium.firefox.GeckoDriverService)

How to iterate an array of objects and only get specific values

I have an array of below format

[{
    "_id" : "500",
    "loanRef" : "500",
    "createdTime" : "2018-02-15T17:20:47.156Z",
    "bdetails" : {
        "config" : {
            "chase" : [
                6,
                12
            ],
            "expiry" : 35
        }
    },
},
{
    "_id" : "500",
    "loanRef" : "500",
    "createdTime" : "2018-02-15T18:11:45.377Z",
    "bdetails" : {
        "config" : {
            "chase" : [
                6,
                12
            ],
            "expiry" : 35
        }
    },
}
}]

The above array size is around 200..

But I want this in this format

[{
    "_id" : "500",
    "loanRef" : "500",
    "createdTime" : "2018-02-15T17:20:47.156Z",
    "chase" : "[6,12]",
    "expiry" : 35           
},
{
    "_id" : "500",
    "loanRef" : "500",
    "createdTime" : "2018-02-15T18:11:45.377Z",
    "chase" : "[6,12]",
    "expiry" : 35
}]

Can someone help how we can form this with some js logic..Any help would save me with this.Thanks

how to grab all the positions of an array and insert individuality into the database

I have a post communication from an application that is in nodejs, it sends me some information that does not change and an array that contains 7 positions and I need to merge this information to insert into the database, I need to get the information that is fixed and one position the array and insert into the database until you read the 7 positions and thus finalize the insertion. But I do not know how I can do this, to insert information in the database I can do normal, I just do not know how to gather the fixed information and get an array position.

here is where I get the json information and insert

var rotina = req.body;
console.log(“processando uma requisição de rotina”);

  var connection = app.persistencia.connectionFactory();
  var pagamentoDao = new app.persistencia.PagamentoDao(connection);

  pagamentoDao.inserir(rotina, function(erro, resultado){

    if (erro){
      console.log('Erro ao gravar' + erro);
      res.status(400).send(erro);

    }else {
      rotina.id = resultado.insertId;
      console.log('Rotina Criada');
      res.status(400).send(rotina);
    }
  });

});