req.user is unidentified in session (Node, express, session, passport) Ask Question

For some reason req.user is undefined, and after 4+ hours of trying to figure out why, I’m asking here. I even copy-pasted the server/index.js file of a friend’s server, changed the auth strategy so it worked for mine, and I get the same issue.

Everything else is working. It redirects to auth0, comes back to the correct place, either creates a new user in the DB or finds the user. In passport.serializeUser it has all the data I passed along. But when I hit the ‘/auth/me’ endpoint, req.user is undefined.

server/index.js

require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors')
const session = require("express-session");
const passport = require('passport');
const Auth0Strategy = require('passport-auth0');
const massive = require('massive');
const axios = require('axios');
const process = require("process");
const moment = require('moment');

const app = express();

//app.use(express.static(__dirname + './../build'));
app.use(bodyParser.json());
app.use(cors());

app.use(session({
    secret: process.env.SECRET, 
    cookie: { maxAge: 60000 },
    resave: false,
    saveUninitialized: true
   }));
app.use(passport.initialize());
app.use(passport.session()); 

// Use the session middleware
massive(process.env.CONNECTION_STRING)
.then( (db) => {
    console.log('Connected to Heroku')
    app.set('db', db);
}).catch(err=>console.log(err))
 


passport.use(new Auth0Strategy({
    domain: process.env.AUTH_DOMAIN,
    clientID: process.env.AUTH_CLIENT_ID,
    clientSecret: process.env.AUTH_CLIENT_SECRET,
    callbackURL: process.env.AUTH_CALLBACK
}, (accessToken, refreshToken, extraParams, profile, done) => {
    const db = app.get("db");
    const userData = profile._json;

    db.find_user([userData.identities[0].user_id]).then(user => {
    if (user[0]) {
        return done(null, user[0]);
    } else {
        db.create_user([
            userData.given_name,
            userData.family_name,
            userData.email,
            userData.identities[0].user_id
        ])
        .then(user => {
            return done(null, user);
        });
    }
    });
}))

passport.serializeUser( (user, done) => {
    //console.log('serializeuser', user)
    done(null, user);
}) 

passport.deserializeUser( (id, done) => {
    app.get("db").find_session_user([id])
        .then(user => {
        console.log(user);
        done(null, user[0]);
        });
})

app.get('/auth', passport.authenticate('auth0'));
app.get('/auth/callback', passport.authenticate('auth0', {
    successRedirect: process.env.SUCCESS_REDIRECT
}))

app.get('/auth/me', (req, res) => {
    console.log('auth/me endpoint hit')
    console.log(req.user)
    if(!req.user){
        return res.status(401).send('No user logged in.');
    }
    return res.status(200).send(req.user);
})

app.listen(process.env.PORT, () => console.log(`Listening on port: ${process.env.PORT}`));

Changes done to object from member function does not persist. Scope/ reference issue? Ask Question

I will try to keep this short and neat. I have two files, Main.js and Component1.js. I am trying to implement the module pattern but i am having troubles with getting changes to persist after being made in an event handler. I will explain the code as i go along, i am writing this in nodejs and this is the short version of each file:

Main.js

var component1 = require("Component1");
var components = { compA: component1(), compB: {} };

Component1.js

module.exports = function () {
    var count = 0;

    function listener(e) {     // Event handler of custom event.
        console.log(count);
        count++;
    }

    return { count: count }
}

Now, if i add the following line to Main.js

components.compA.randomString = "Hello";

and change listener() in Component1.js to

function listener(e) {     // Event handler of custom event.
    console.log(typeof randomString);
    console.log(count);
    count++;
}

i get the following print-out after issuing 1 custom event tied to the listener:

undefined
0

If i were to issue a second custom event the print-out would read:

undefined
1

but if i were to now console.log the compA.count in Main.js i would see that it was still zero.

I am guessing that this means that the listener either has access to a different scope, and therefore neither change “persisted” from the perspective of the other (count === 0 for Main.js, string undefined for the listener), or that compA and the listener referes to two different objects? I am arriving at this conclusion because if i now change Component1.js to

module.exports = function () {
    var count = 0;
    var _this;

    function listener(e) {     // Event handler of custom event.
        console.log(typeof _this.randomString);
        console.log(_this.count);
        _this.count++;
    }

    function init() {
        _this = this;
    }

    return { count : count, init: init }
}

and add the following line to the end of Main.js:

components.compA.init();

and issue 2 new custom events i get the following print-out:

string
0
string
1

and the correct count would persist to components.compA.count.

Can someone please explain this behaviour?

error connect ECONNREFUSED websocket Ask Question

Im trying to build p2p server in node.js using ws package but after running $HTTP_PORT=3002 P2P_PORT=5002 PEERS=ws://localhost:5004 npm run dev i get an error :

Listening on p2p port 5002
Listening on port 3002
events.js:165
      throw er; // Unhandled 'error' event
      ^

Error: connect ECONNREFUSED 127.0.0.1:5004
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1174:14)
Emitted 'error' event at:
    at WebSocket.finalize (/home/ris/Desktop/gj-chain/node_modules/ws/lib/websocket.js:190:41)
    at ClientRequest._req.on (/home/ris/Desktop/gj-chain/node_modules/ws/lib/websocket.js:639:10)
    at ClientRequest.emit (events.js:180:13)
    at Socket.socketErrorListener (_http_client.js:395:9)
    at Socket.emit (events.js:180:13)
    at emitErrorNT (internal/streams/destroy.js:64:8)
    at process._tickCallback (internal/process/next_tick.js:178:19)
[nodemon] app crashed - waiting for file changes before starting...

I tried reinstalling dependencies,change ports, kill processes on all ports(3002,5002,5004) but it didnt work. I believe there is some dependancy mess, im using ubuntu 16.04 node 9.11 / npm 5.6.0 version.

Undefined binding(s) while executing SELECT query Ask Question

I am using a Bookshelf refresh method to refresh a model but I am having a weird problem here. I have two tables device and subscription and they have one to one relationship. I have a method (lets call it foo) in which I am trying to refresh a subscription model. Now, I have two different scenarios when I am calling foo().

1

In this scenario, I call foo() with a subscription model which looks something like this

{ user_id: 10289,
  id: 1179,
  more columns...
}

and when I try to refresh this subscription model it works as expected and I don’t get any errors.

2

In this scenario, I fetch the device first along with subscription like so Device.forge().fetch({withRelated: ['subscription']}). Then I call foo() with subscription model which looks something like this

{ user_id: 10289,
  id: 1179,
  more columns...,
  device: {
     id: 17093,
     user_id: 10289,
     subscription_id: 1179,
     more columns...
  }
}

When I try to refresh a subscriotion model here I get an error

Undefined binding(s) detected when compiling SELECT query: select "subscriptions".* from "subscriptions" where "subscriptions"."id" = ? and "subscriptions"."id" = ? limit ?

For some reason, the generated query is expecting two subscription_id‘s in where clause and one of them is undefined.

My question is why does query has two subscription_id‘s in the second scenario? Why refresh works as expected when there is no device model present along with subscription model?

Any help clarifying this is much appreciated. Thank you.

Use of dot inside brackets is breaking the swig template Ask Question

Use of Dot inside curly brackets is breaking the rendering of swig template. I am not sure if its a bug.

I have the code like this some where in between html text for a article:

<pre>
    <code>
        <span>new Promise (function  (resolve, reject) {...}  );</span>
    </code>
</pre>

Using dots inside brackets {...} is breaking the rendering. Why? When I remove it was working fine but I had to track down the issue.

gulp-imagemin how to get the, compressed value, to a variable Ask Question

I have tried to get the compressed value of: original size, minified size and space savings to a variable. So far only plugins that I have found are showing this data only in console.

enter image description here

Is there any easy way to get the same data displayed in the console to a variable?

My code for gulp-imagemin:

    gulp.task("compress-images", () =>
    Promise.all([
      new Promise((resolve, reject) => {
        gulp
          .src("./uploads/*")
          .pipe(printSpaceSavings.init())
          .pipe(
            imagemin([
              imageminMozjpeg({ quality: 75 }),
              imagemin.svgo({
                plugins: [{ removeViewBox: true }, { cleanupIDs: false }]
              })
            ])
          )
          .pipe(
            tap(function(file) {
              file.contents = Buffer.from(
                yourFunction(file.contents.toString())
              );
              function yourFunction(input) {
                return input.toString(); // Possible to get this data to a variable?
              }
            })
          )
          .on("error", reject)
          .pipe(printSpaceSavings.print()) //consoleLog
          .pipe(gulp.dest("./compressed"))
          .on("end", resolve);
      })
    ])
  );

How to merge array of objects of different keys into one key from one array Ask Question

I am working in Node JS. I have one JSON array of object. There are different key in one JSON object such as A, B, C , D, E I have to merge array of objects from different keys into one key. I am providing my JSON object as follows.

{
    "out-for-delivery": [
        {
            "order_id": 1,
            "address": {
                "user_id": 1,
                "first_name": "Mark",
                "last_name": "Stevauh",
                "landmark": "Krti",
                "mobile": "123456789",
                "type": "work",
                "city_id": 4644,
                "postcode": 0,
                "address_type": "address",
                "locker_id": 0,
                "added_on": "2018-04-30T12:34:11.000Z",
                "updated_on": "2018-04-30T12:34:11.000Z",
                "address_1": "Gm is",
                "address_2": "Bc"
            },
            "status": "out-for-delivery"
        },
        {
            "order_id": 7,
            "address": {
                "user_id": 5,
                "first_name": "",
                "last_name": "",
                "landmark": "",
                "mobile": "123456789",
                "type": "other",
                "city_id": 34,
                "postcode": 0,
                "address_type": "locker",
                "locker_id": 2,
                "added_on": "2018-05-02T09:32:38.000Z",
                "updated_on": "2018-05-02T09:32:38.000Z",
                "address_1": "jhdasd ahdkjh asd",
                "address_2": "asfjksfdj asakjsf"
            },
            "status": "out-for-delivery"
        },
        {
            "order_id": 6,
            "address": {
                "user_id": 5,
                "first_name": "Shruti",
                "last_name": "Shinde",
                "landmark": "test",
                "mobile": "123456789",
                "type": "work",
                "city_id": 45,
                "postcode": 0,
                "address_type": "address",
                "locker_id": 0,
                "added_on": "2018-05-02T09:35:25.000Z",
                "updated_on": "2018-05-02T09:35:25.000Z",
                "address_1": "test",
                "address_2": "test"
            },
            "status": "out-for-delivery"
        }
    ],
    "retry-delivery": [
        {
            "order_id": 13,
            "address": null,
            "status": "retry-delivery"
        },
        {
            "order_id": 8,
            "address": {
                "user_id": 5,
                "first_name": "TEST",
                "last_name": "Shinde",
                "landmark": "test",
                "mobile": "9773071307",
                "type": "work",
                "city_id": 666,
                "postcode": 0,
                "address_type": "address",
                "locker_id": 0,
                "added_on": "2018-05-02T09:35:25.000Z",
                "updated_on": "2018-05-02T09:35:25.000Z",
                "address_1": "test",
                "address_2": "TEST"
            },
            "status": "retry-delivery"
        }
    ],
    "complete": [
        {
            "order_id": 2,
            "address": null,
            "status": "complete"
        }
    ],
    "cancelled": [
        {
            "order_id": 15,
            "address": null,
            "status": "cancelled"
        }
    ]
}

I want to merge array of objects from keys B , C into key D. So how can I achieve it. Thanks in advance. Really sorry I am doing little change in my question. I have only changed my keys which was previously A, B, C, D.