express session management not working - node.js

I am new to the node.js world. I am trying to write a REST services and I am stuck with session management. So I created a separate app just to see if I can get the session to work, but it doesn't, here is the code. The req.session.username is always undefined:
var express = require('express');
var url = require('url');
var app = express()
app.use(express.cookieParser('Hiren'))
app.use(express.session({ secret: 'HirenAdesara' }))
app.use(express.bodyParser())
app.use(app.router)
//Sniff HTTP
app.all('*', function(req, res, next) {
//Check for Authentication
console.log(req.session)
if ((!(/^\/auth/g.test(req.url))) && (!req.session)) {
console.log('in app.all: Unauthorized')
res.send(401)
}
else
{
return next()
}
})
app.post('/auth', function(req, res) {
var query = req.body
console.log('Query' + JSON.stringify(query))
username = query.username;
password = query.password;
if(username == 'Hiren' && password == 'Adesara')
{
req.session.username = 'Hiren';
console.log('New Session Created..')
res.send(200)
}
else
{
console.log('New session could not be created.')
res.send(401)
}
})
app.get('/projects', function(req,res) {
console.log('inside projects' + req.session.username);
res.send(req.session.username); })
app.listen(2048)
console.log('Listening on port 2048...')
It doesn't work and I have no idea what is wrong here.

Star by moving the 3 lines in your app.get('/'...) outside of it:
var express = require('express');
var querystring = require('querystring');
var app = express()
app.use(express.cookieParser('Hiren')); // This line
app.use(express.session({ secret: 'HirenAdesara' })); // This line
app.use(express.bodyParser()); // This line
app.get('/', function(req, res){
res.send('hello from the root page');
})
// the rest of your code

Related

mynodejs login page is not responding

I'm new to node js and i tried creating a simple login page. but when i run my code it takes me to the login page alright. the problem is when i enter a user name and password, it doesn't display the information it supposed to display.
var express = require('express');
var sessions = require('express-session');
var session;
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(sessions({
secret: '2937#&&#',
resave: false,
saveUninitialized: true
}))
app.get('/login', function(req, resp){
session = req.session;
if(session.uniqueID){
resp.redirect('/redirects');
}
resp.sendFile('./files/login.html', {root: __dirname});
});
app.post('/login', function(req, resp){
// resp.end(JSON.stringify(req.body));
session = req.session;
if(session.uniqueID) {
resp.redirect('/redirects');
}
if(req.body.username == 'admin' && req.body.password == 'admin'){
session.uniqueID = req.body.username;
}
resp.redirect('/redirects');
});
app.get('/logout', function(req, resp){
req.session.destroy();
resp.redirect('/login');
});
app.get('/admin', function(req, resp){
session = req.session;
if(session.uniqueID != 'admin'){
resp.end('Unauthorised acess')
}
resp.end('You are good');
})
app.get('/redirects', function(req, resp){
session = req.session;
if(session.uniqueID =='admin') {
console.log(session.uniqueID)
resp.redirect('/admin');
} else {
resp.send(req.session.uniqueID + 'not found KILL SESSION');
}
})
app.listen(1337, function() {
console.log('Listening at port 1337');
});
Nothing happens because you can't redirect on an AJAX call. Your POST probably works, but then your redirect directive has no effect.
Try sending a "success" response if the username and password are good (a simple res.send('OK'); would do) and then on the client side redirect the user to /redirects (window.location.replace('https://yoursite.com/redirects')); if a success code is returned.
This will be handled by your GET route for /redirects and you should see what you want.

Unable to make app.post working using nodeJs

I am trying to connect my Angular2 to my nodeJs server. I have an authentication form which makes a post request. And I would like to use node to handle the post request.
But so far I am unable to make my post request working. The console.log doesn't display anything.
What I am missing?
This is my server.js which points to the folder dist in which i made the build of angular.
const express = require('express');
const path = require('path');
const http = require('http');
var walker = require('node-sync-walker');
const bodyParser = require('body-parser');
// Get our API routes
const api = require('./server/routes/api');
var app = express();
// Parsers for POST data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// Point static path to dist
app.use(express.static(path.join(__dirname, 'dist')));
// Set our api routes
app.use('/api', api);
// Catch all other routes and return the index file
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
walker.routeWalker(__dirname + '/server/routes', app);
/**
* Get port from environment and store in Express.
*/
const port = process.env.PORT || '3000';
app.set('port', port);
/**
* Create HTTP server.
*/
const server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port, () => console.log(`API running on localhost:${port}`));
This is my api.js
var users = [{username: "user", password: "password"}];
var router = require('express').Router();
module.exports = function(app) {
router.post('/api/authenticate',
function(req, res) {
console.log("print something");
let params = JSON.parse(req.body);
// find if any user matches login credentials
let filteredUsers = users.filter(user => {
return user.username === params.username && user.password === params.password;
});
if (filteredUsers.length) {
res.sendStatus(200);
} else {
console.log("print something else");
return res.sendStatus(400)
}
//return;
});
}
You are configuring the route as '/api/api/authenticate'
You should remove '/api' from routes in api.js
Finally, it worked! I removed the api in /api/authenticate as #catalacs suggested. Then I changed how I import the module router from api.js to server.js.
server.js
var users = [{username: "test", password: "test"}];
var router = require('express').Router();
router.post('/authenticate',
function(req, res) {
console.log("print something");
let params = JSON.parse(req.body);
// find if any user matches login credentials
let filteredUsers = users.filter(user => {
return user.username === params.username && user.password === params.password;
});
if (filteredUsers.length) {
res.sendStatus(200);
} else {
console.log("print something else");
return res.sendStatus(400)
}
//return;
});
module.exports = router;
And in my server.js, I commented out this line:
walker.routeWalker(__dirname + '/server/routes', router);

NodeJs Session, Work in Postman but not in browser

I have some problems with the express session where I cannot retrieve my session variable that I had stored previously. Below are parts of my codes that I had written.
server.js
let express = require('express'),
path = require('path'),
bodyParser = require('body-parser'),
cors = require('cors'),
config = require('./config/database'),
expressSession = require('express-session'),
uid = require('uid-safe'),
db;
let app = express();
//Import Routes
let auth = require('./routes/auth'),
chimerListing = require('./routes/chimer-listing'),
brandListing = require('./routes/brand-listing');
//Specifies the port number
let port = process.env.PORT || 3000;
// let port = 3000;
// Express session
app.use(expressSession({
secret: "asdasd",
resave: true,
saveUninitialized: false,
cookie: {
maxAge: 36000000,
secure: false
}
}));
//CORS Middleware
app.use(cors());
//Set Static Folder
var distDir = __dirname + "/dist/";
app.use(express.static(distDir));
//Body Parser Middleware
app.use(bodyParser.json());
//MongoDB
let MongoClient = require('mongodb').MongoClient;
MongoClient.connect(config.database, (err, database) => {
if (err) return console.log(err)
db = database;
//Start the server only the connection to database is successful
app.listen(port, () => {
console.log('Server started on port' + port);
});
});
//Make db accessbile to routers;
app.use(function(req, res, next) {
req.db = db;
res.set('Access-Control-Allow-Origin', '*');
res.set('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.set('Access-Control-Allow-Headers', 'Content-Type');
next();
});
//Routes
app.use('/login', auth);
app.use('/user-listing', userListing);
app.use('/brand-listing', brandListing);
//Index Route
app.get('/', (req, res) => {
res.send('Invalid Endpoint');
});
genuuid = function() {
return uid.sync(18);
};
auth.js
let express = require('express'),
router = express.Router(),
db;
//Login Router for chimer
router.post('/chimer', (req, res, next) => {
db = req.db;
// let client = req.client;
db.collection('chimeUser').find({
Username: req.body.username,
Password: req.body.password
}).toArray().then(function(docs) {
//If there is such user
if (docs.length >= 1) {
req.session.chimerId = docs[0]._id;
console.log(req.session);
req.session.save(function(err) {
// session saved
if (err)
console.log(err)
res.json({
success: true,
chimerId: docs[0]._id
//objects: docs
});
})
} else {
res.json({
success: false,
//objects: docs
})
}
});
});
//Login Router brand
router.post('/brand', (req, res, next) => {
db = req.db;
db.collection('brand').find({
Username: req.body.username,
Password: req.body.password
}).toArray().then(function(docs) {
req.session.brand = docs;
console.log(req.session.brand);
//If there is such user
if (docs.length >= 1) {
res.json({
success: true,
//objects: docs
})
} else {
res.json({
success: false,
//objects: docs
})
}
//db.close()
});
});
});
module.exports = router;
user-listing.js
let express = require('express'),
moment = require('moment'),
router = express.Router(),
// ObjectID = require('mongodb').ObjectID,
db, client;
// let applyListing = require('../models/chimer-listing');
//Retrieve All Listing
router.get('/getAllListing', (req, res, next) => {
db = req.db;
console.log(req.session)
db.collection('listing').find().toArray().then(function(listing) {
//If there is any listing
if (listing.length >= 1) {
res.json({
success: true,
results: listing
})
} else {
res.json({
success: false,
})
}
//db.close()
});
});
module.exports = router;
So in my server.js, I have three routes file which is auth, user-listing, and brand-listing.
Firstly, a user will need to login with the web application which is developed in angular2 and this will trigger the auth route. It will then check for the credentials whether does it exist in the database if it exists I will then assign an ID to req.session.chimerId so that in other routes I will be able to use this chimerId.
Next, after the user has logged in, they will then retrieve an item listing. The problem arises where I can't seem to retrieve the req.session.chimerId that I had previously saved. It will be undefined
NOTE: I tried this using Postman and the browser. In the Postman it works, I am able to retrieve back the req.session.chimerId whereas when I use the angular2 application to hit the endpoints req.session.chimerId is always null

Express middlware not called on sub paths

I am building an API backend with Express (v4) and facing an issue that my middleware function is not called
on sub-paths of my route. E.g. it is called for /movie but not for /movie/search.
I have split my routes into separate files. Below is the code, shortened to the relevant parts.
Any help is appreciated!
app.js
var express = require('express');
var app = express();
var router = require('routes')(app);
/routes/index.js
module.exports = function(app) {
app.use('/movie', check_authentication, require('movie'));
};
/routes/movie.js
var Movie = require(../models/movie');
// Middleware is working for this route (/movie?movie_id=123)
router.get('/', function(req, res) {
Movie.findById(req.query.movie_id)
.then(function(movie) {
res.status(200).json(movie);
}, function(err) {
res.status(400).send(err);
});
});
// Middleware is NOT working for this route (/movie/search?keyword=matrix)
router.get('/search', function(req, res) {
Movie.findById(req.query.keyword)
.then(function(movie) {
res.status(200).json(movie);
}, function(err) {
res.status(400).send(err);
});
});
/routes/check_authentication.js
var express = require('express');
var router = express.Router();
var firebaseAdmin = require('firebase-admin');
var path = require('path');
var config = require(path.resolve(__dirname, '../config/config.json'));
firebaseAdmin.initializeApp({
credential: firebaseAdmin.credential.cert(path.resolve(__dirname, '../config/' + config.firebase.serviceAccount)),
databaseURL: config.firebase.databaseURL
});
// AUTHENTICATION MIDDLEWARE
// needs to be included in any request which requires authorization
// =============================================================================
router.all('/', function(req, res, next) {
// check if authorization header is present
var token = req.headers['authorization'];
if (typeof token === 'undefined') {
res.status(403).json({ Error: 'Unauthenticated' });
}
else {
firebaseAdmin.auth().verifyIdToken(token).then(function(decodedToken) {
req.email = decodedToken.email;
next(); // all good. go ahead with the request
}).catch(function(error) {
res.status(403).json({ Error: 'Unauthenticated' });
});
}
});
module.exports = router;
It seems I found the problem.
Changing the middleware to trigger on * fixes it.
router.all('*', function(req, res, next)
Maybe someone can confirm that this is the way to go.
The check_authentication module should export the middleware function, not a router.
module.exports = function(req, res, next) {
// check if authorization header is present
// ...
});

Node.js Express Serve static files only with SIMPLE authentification

I've a problem since two days ago now.
I just want an authentification on my static files.
I look at a lot of post on the internet and nothing answer my question simply.
I try to use basic-auth, but it has no effect on my webpages.
I just want a simple dialog box before open my static pages that ask name and password and in my server.js just a thing like : if name == 'foo' and password =='pwd' then "send my static content".
But it seems to be not simple as it might be.
There is my code :
/***************************************************************************/
//Server Node.js
/** ************************************************************************ */
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
// Routers
var router = express.Router();
var mongoose = require("mongoose");
mongoose.connect('mongodb://localhost:27017/mydb');
var conn = mongoose.connection;
var assert = require("assert");
var basicAuth = require('basic-auth');
var auth = function (req, res, next) {
function unauthorized(res) {
res.set('WWW-Authenticate', 'Basic realm=Authorization Required');
return res.send(401);
};
var user = basicAuth(req);
if (!user || !user.name || !user.pass) {
return unauthorized(res);
};
if (user.name === 'foo' && user.pass === 'bar') {
return next();
} else {
return unauthorized(res);
};
};
app.use('/', auth);
app.use(express.static('public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({"extended" : false}));
router.route("/data").get(function(req, res) {
// A non static route
});
}).post(function(req, res) {
// A non static route
});
router.route("/data/:id?").get(function(req, res) {
// A non static route
});
router.route("/remove/:id?").get(function(req, res) {
// A non static route
});
app.use('/', router);
app.listen(8080);
console.log("Listening to PORT 8080");
Thanks.
Have a nice day.

Resources