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}`));

How to set cookie value in JavaScript and get it in Rails controller Ask Question

Using Ruby on Rails 5.0.3 .

I want to set some value in cookie using JavaScript (when button clicked), and get it in Rails.

I know how to access session in Rails, which is session[:some_key] or cookies.

But I don’t know how to do in JavaScript. (it must be able to accessed from Rails session or cookies.)

How can I do it in JS?

Or any other ways to save some value in JS, and get it later in Rails ?

How to send a JavaScript object on the server side (ASP NET MVC)? Ask Question

Below is the relevant code (JS+jQuery on the client side):

function getuser(username, password) {
    var user = new Object();
    user.constructor();
    user.username = username;
    user.password = password;
    //....
    $("#a1").click(function () {
        var u = getuser($("#username").val(), $("#password").val());
        if (u == false) {
            alert("error");
        } else {
            //....
        }
    });
}

The question is how to send var u to a session on the server side?

Cross-domain session sharing in Rails 5 Ask Question

I have an app on example.com that has a Javascript widget users can place on their own website, user.com. It’s your typical embeddable JS script, <script type='text/javascript' src='example.com/widget.js?key=123456789'></script> deal and it works great.

However, I now want to serve information to users that depends on their session. I know I can’t have the browser share cookie data from user.com to example.com. I store example.coms session data with ActiveRecord and not a cookie. I was wondering if it’s possible to perhaps store the session_id from the ActiveRecord session in user.coms cookie? Or something, anything, that would let me keep a session for the client on user.com using the widget for example.com.

EDIT – To be clear, I don’t care about a session on user.com persisting so if the client then visits example.com directly the session remains.

How to protect a CKEditor file upload PHP script against unauthorized access? Ask Question

I’m using the following CKEditor file upload PHP script in a password-protected environment:

$accepted_origins = array( 'http://localhost', 'http://192.168.1.1', 'http://example.com', 'http://www.example.com' );
$upload_folder = '../uploads/';

if ( isset( $_FILES['upload'] ) ) {

    // Required: anonymous function reference number as explained above.
    $funcNum = $_GET['CKEditorFuncNum'] ;

    // Optional: instance name (might be used to load a specific configuration file or anything else).
    $CKEditor = $_GET['CKEditor'] ;

    // Optional: might be used to provide localized messages.
    $langCode = $_GET['langCode'] ;

    // Optional: compare it with the value of `ckCsrfToken` sent in a cookie to protect your server side uploader against CSRF.
    // Available since CKEditor 4.5.6.
    $token = $_POST['ckCsrfToken'] ;

    if ( isset( $_SERVER['HTTP_ORIGIN'] ) ) {
        // same-origin requests won't set an origin. If the origin is set, it must be valid.
        if ( in_array( $_SERVER['HTTP_ORIGIN'], $accepted_origins ) ) {
            header( 'Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN'] );
        } else {
            $error = 'Origin denied';
        }
    }

    // Sanitize input
    if ( preg_match( "/([^wsd-_~,;:[]().])|([.]{2,})/", $_FILES['upload']['name'] ) ) {
        $error = 'Invalid file name';
    }

    // Verify extension
    if ( !in_array( strtolower( pathinfo( $_FILES['upload']['name'], PATHINFO_EXTENSION ) ), array( 'gif', 'jpg', 'png', 'pdf' ) ) ) {
        $error = 'Invalid extension';
    }

    // Check if filename already exists
    $file_info = pathinfo( $_FILES['upload']['name'] );
    $i = 0;
    do {
        $target_filename = $file_info['filename'] . ( $i ? "_$i" : '' ) . '.' . $file_info['extension'];
        $i++;
        $target_file = $upload_folder . $target_filename;
    } while ( file_exists( $target_file ) );

    // Process file upload
    $tmp_file = $_FILES['upload']['tmp_name']; 
    move_uploaded_file( $tmp_file, $target_file );
    $protocol = ( $_SERVER['HTTPS'] && $_SERVER['HTTPS'] != 'off' ) ? 'https://' : 'http://';
    $url = 'uploads/' . basename( $target_file );

    echo "<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction($funcNum, '$url', '$error');</script>";

}

This script is called from a the JS file (config.js) through the config.filebrowserUploadUrl setting which is unaware of any PHP session.
My question is, is it possible to protect it against unauthorized access? If so, how?

Thanks in advance

Count total number of viewers on a page who are at a specific GPS location Ask Question

So, the basic premise is this.

I have a page being designed that gets a users permission to access their GPS location, displays their location on a map and then updates an info window on the map with their current location info and a message.

Currently the message is just a success or failure message letting them know if they are at the correct GPS coords within 50ft (or whatever value I set for that).

What I want to do is as follows.

Count the total number of viewers of this specific page who have arrived at the correct GPS location and when enough people get there, display a message to them.

So, I am assuming I will need to perform an action of some kind within the code that triggers when the person is within the xx ft radius of the specific location and then stores a session or something, then removes it if they move out of the radius, this would get updated every time their GPS location is checked and updated.

Next let’s say I need something to happen when X number of people are all at the correct location and viewing the page.

So, I will then need to be able to count the above and see if it is >= X etc.

Then, once X number of people have arrived at the specific location I will need something on the page to change to display a message to them all.

I am using a modified version of the code found here https://developers.google.com/maps/documentation/javascript/examples/map-geolocation

Modified to display the persons coords, accuracy and distanc from a specific location within the info window, instead of just the basic location found message they were using.

While waiting for enough people to arrive I would like that Info Window to display a message stating Y / X people have arrived, so people can see how many more are needed, then once X number of people arrive at said location I would like that info window to change to displaying a congratulations message and some other info.

Eventually I will be modifying this from a single static location and value of X to something I can have multiple of stored in a database and use for different locations, so different people can use it independantly of each other.

javascript – Cannot read property “cart” of undefined which is a session attribute Ask Question

var express = require('express');
var router = express.Router();
var Cart = require('../models/cart')

router.get('/', function(req, res, next) {
  var cart = new Cart(req.session.cart)
});

When I execute the above node.js program using “get” method,
the following error is triggered.

Cannot read property ‘cart’ of undefined

TypeError: Cannot read property ‘cart’ of undefined

I would like to simulate a shopping cart and use a session attribute to store the record when users try to add items into cart.

This program is to read a session attribute “cart”, no matter it is created or not, to return the active session’s cart record.

However, it seems the program cannot recognize this “cart” session attribute if I have not initialized it before.

How can I resolve this issue such that the program will not return error?

Flask Session Not Persisting (Postman works, Javascript doesn't) Ask Question

I’m developing a Flask server to communicate between some backend Python functionality and Javascript clients over the web. I’m attempting to utilize Flask’s session variable to store user specific data over the course of their time interacting with the app. I’ve removed most of the application specific code below but the core problem I’m experiencing remains.

Here is my the code for my (simplified) Flask app:

import json
import os
from flask import Flask, jsonify, request, session

app = Flask(__name__)
app.secret_key = 'my_secret_key'

@app.route('/', methods=['GET'])
def run():
  session['hello'] = 'world'
  return jsonify(session['hello'])

@app.route('/update', methods=['POST'])
def update():
  return jsonify(session['hello'])

if __name__ == '__main__':
  app.run(host='0.0.0.0')

Utilizing Postman, I can make a GET request to my server and receive the expected output of "world". I can then make a POST request with an arbitrary body and receive the same expected output of "world" (again using Postman).

When using Chrome, I can visit my server IP and see the expected output "world" on the page. I can also manually make a GET request using Javascript (in Chrome’s console) and receive the same response as expected. However, my problem arises when trying to send a POST request to the server using Javascript; the server shows a KeyError: 'hello' when trying to make this request.

Here is the Javascript I’m using to make the POST request:

var url = 'http://my_server_ip/update';
fetch(url, {
  method: 'POST',
  body: JSON.stringify('arbitrary_string'),
  headers: new Headers({
    'Content-Type': 'application/json'
  })
})
.then(response => response.json())
.then((data) => {
  console.log(data);
})

What’s going wrong here? Why can I make the GET/POST requests with Postman just fine but run into errors making the same requests with Javascript?