How to generate session after user login in express-session? - mysql

I am using express.js , express-mysql-session and passport.js. The express session middleware is creating session for the static file requests such as login page which is creating another entry in the session table.
I have moved the static middleware before the express session middleware. But when I make a login request after moving the static middleware before the session middleware the passport throws an error "passport.initialize middlware not in use".
I guessing that this might be happening because there is no "connect.sid" cookie in the request!
That's how my configure function looks like
app.configure(function () {
app.set('mode', process.argv[2] || 'local');
app.set('port', config.port || 8080);
app.use(express.favicon(__dirname + '/public/favicon.ico'));
app.use(express.logger('dev'));
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.cookieParser());
app.use(express.json());
app.use(express.urlencoded());
// this is a route handler for serving public file incase user doesn't have session
app.get("/*", policies.publicRoute.handleRoute());
app.use(busboy({
limits: {
fileSize: maxFileSize,
files : 1
}
}));
//create session store
var sessionStore = new SessionStore({}, connection);
// required for passport
app.use(express.session({
secret: 'mySecret',
cookie: { maxAge : myNumber },
store: sessionStore,
resave: true,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
});

Related

Expressjs session : undefined sessionid

I am getting null sessionId in my expressjs application
here is app.js file
var session = require('express-session');
var app = express();
app.use(cookieParser());
app.use('/loginaction',loginaction);
//session handling
app.set('trust proxy', 1) // trust first proxy
app.use(session({
secret: 'hellokitty',
resave: false,
saveUninitialized: true,
cookie: { secure: true }
}));
In my loginaction.js file which is located in routes folder.
router.post('/', function(req, res, next) {
console.log("Session id"+req.sessionID);
//test session
req.session.test= 'something';
});
But i will get session id as undefined
also req.session.test through another error cannot resolved test
Your getting an unidentified on req.sessionid because you are never sending the sessionid to the client. You are requesting information the request doesn't have. Should try sending the sessionid in the initial login response. It should then remain persistent in the request after that (not sure on it's persistence tho, I use a different framework that keeps it persistent)

How to authenticate a java web app with KeyRock?

We are trying to create a user authentication in our web app ( that we are developing in Java Spring MVC). For our authentication we want to use the token and user info acquired from the users fiware.lab account on global instance of keyrock.
Since Keyrock is based on OAuth2 protocol, what is the best approach to use keyrock from our web app?
Is there a java library that we could use for this purpose?
Is there a way to integrate spring security or apache oltu?
Every example would be more than welecome.
We only have the implementation of node.js but we need a java version of this:
var express = require('express');
var OAuth2 = require('./oauth2').OAuth2;
var config = require('./config');
// Express configuration
var app = express();
app.use(express.logger());
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({
secret: "skjghskdjfhbqigohqdiouk"
}));
app.configure(function () {
"use strict";
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
//app.use(express.logger());
app.use(express.static(__dirname + '/public'));
});
// Config data from config.js file
var client_id = config.client_id;
var client_secret = config.client_secret;
var idmURL = config.idmURL;
var response_type = config.response_type;
var callbackURL = config.callbackURL;
// Creates oauth library object with the config data
var oa = new OAuth2(client_id,
client_secret,
idmURL,
'/oauth2/authorize',
'/oauth2/token',
callbackURL);
// Handles requests to the main page
app.get('/', function(req, res){
// If auth_token is not stored in a session cookie it sends a button to redirect to IDM authentication portal
if(!req.session.access_token) {
res.send("Oauth2 IDM Demo.<br><br><button onclick='window.location.href=\"/auth\"'>Log in with FI-WARE Account</button>");
// If auth_token is stored in a session cookie it sends a button to get user info
} else {
res.send("Successfully authenticated. <br><br> Your oauth access_token: " +req.session.access_token + "<br><br><button onclick='window.location.href=\"/user_info\"'>Get my user info</button>");
}
});
// Handles requests from IDM with the access code
app.get('/login', function(req, res){
// Using the access code goes again to the IDM to obtain the access_token
oa.getOAuthAccessToken(req.query.code, function (e, results){
// Stores the access_token in a session cookie
req.session.access_token = results.access_token;
res.redirect('/');
});
});
// Redirection to IDM authentication portal
app.get('/auth', function(req, res){
var path = oa.getAuthorizeUrl(response_type);
res.redirect(path);
});
// Ask IDM for user info
app.get('/user_info', function(req, res){
var url = config.idmURL + '/user/';
// Using the access token asks the IDM for the user info
oa.get(url, req.session.access_token, function (e, response) {
var user = JSON.parse(response);
res.send("Welcome " + user.displayName + "<br> Your email address is " + user.email + "<br><br><button onclick='window.location.href=\"/logout\"'>Log out</button>");
});
});
// Handles logout requests to remove access_token from the session cookie
app.get('/logout', function(req, res){
req.session.access_token = undefined;
res.redirect('/');
});
console.log('Server listen in port 80. Connect to localhost');
app.listen(80);
Edit 1
Here is my set up:
and the end result error I get when I call the token:
Fiware devguide explains how this oauth2 flow works against KeyRock.
There also, you can find linked several oauth2 implementations like scribe-data, where you can find several examples on how to use oauth2 authentication against some of the most extended social networks.

Persistent Session in Nodejs using MySql

new to nodejs. this might be a silly/easy question
I have an Express App and i am using mysql for persistent sessions. (using express-mysql-session to do that).
Here's code snippet from app.js:
var express = require('express');
var session = require('express-session');
var SessionStore = require('express-mysql-session');
var app = express();
app.use(session({
store: new SessionStore({
host: 'localhost',
user: 'test',
password: 'test',
database: 'test'
}),
secret: 'secret_key',
resave: false,
saveUninitialized: false
}));
routes.js
module.exports = function(app) {
app.post('/login', wrap(function* (req, res) {
var email = req.body.email;
var password = req.body.password;
var response = yield new AccountController().login(email, password);
if (response.status === 'success') {
req.session.account = {
accountId: response.accountId,
accountStatus: response.accountStatus
};
req.session.save(function(err) {
if (err) console.log('error in saving session: ' + err);
});
}
}
}));
The get and set method of express-mysql-session are called everytime a request is sent.
I wanted to know how can i set my custom data into the persistent session store without using any other library like passport.
and also how to read the store too.

Trouble modularizing passport.js with node

so I'm sort of having an issue here. I have my login route:
var express = require('express');
var router = express.Router();
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
require('../config/passport')(passport, LocalStrategy);
/* GET /login */
router.get('/', function(req, res) {
//you'll probably write some
res.render('login', { title: 'Please Log In' });
});
router.post('/', function(req, res) {
console.log('posting');
console.log(passport);
passport.initialize();
passport.session();
passport.authenticate('local', { successRedirect: '/',
failureRedirect: '/login'
});
console.log('after');
});
module.exports = router;
my app.js:
var express = require('express'),
path = require('path'),
favicon = require('serve-favicon'),
logger = require('morgan'),
cookieParser = require('cookie-parser'),
bodyParser = require('body-parser'),
session = require('express-session'),
RedisStore = require('connect-redis')(session),
passport = require('passport'),
// LocalStrategy = require('passport-local').Strategy,
pool = require('./config/database'),
routes = require('./routes/index'),
api = require('./routes/api'),
login = require('./routes/login'),
app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session(<<redis store info>>);
app.use(passport.initialize());
app.use(passport.session());
app.use('/', routes);
app.use('/api', api);
app.use('/login', login);
...etc
and my ./config/passport.js
var pool = require('./database');
module.exports = function(passport, LocalStrategy) {
passport.serializeUser(function(user, done) {
done(null, user.id);
});
// used to deserialize the user
passport.deserializeUser(function(id, done) {
mysql.query("select * from users where id = "+id,function(err,rows){
done(err, rows[0]);
});
});
passport.use(new LocalStrategy({
usernameField : 'username',
passwordField : 'password',
passReqToCallback : true // allows us to pass back the entire request to the callback
},
function(req, username, password, done) { // callback with user and password from our form
console.log('hi');
pool.query("SELECT * FROM `users` WHERE `user` = '" + username + "'",function(err,rows){
if (err)
return done(err);
if (!rows.length) {
return done(null, false, req.flash('loginMessage', 'No user found.')); // req.flash is the way to set flashdata using connect-flash
}
// if the user is found but the password is wrong
if (!( rows[0].password == password))
return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // create the loginMessage and save it to session as flashdata
// all is well, return successful user
return done(null, rows[0]);
});
}));
};
And I can't really understand why the passport config just doesn't seem to be getting processed at all. When I call passport.authenticate it's seemingly doing nothing
So, there were a few things I did to get this to work. The first is I moved the following into passport.js Having anything inside require() passport related in my route was nuts. I started without this mess, but trying to tinker had progressed to that point. Furthermore, my deserialize function incorrectly had a mysql reference instead of my pool.
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
I then just set up passport like normal in the config, and did
module.exports = passport;
Then just did this in app.js:
var passport = require('../config/passport');
then I changed my router, removed essentially the whole thing on the post function, and did:
router.post('/', passport.authenticate('local', { successRedirect: '/',
failureRedirect: '/login'
}));
I learned I couldn't just call passport.authenticate. It was meant to be placed in a req handler.
Sorry for the totally insane and ambiguous question guys. Just in case any poor soul looks for this down the line, I figured I at least need to have the courtesy to talk about it.

passport-facebook - 'X-Frame-Options' to 'DENY'

I'm trying to develop a facebook connect with node and passport. But I'm having this error in my browser console:
Refused to display 'https://www.facebook.com/dialog/oauth?response_type=code&redirect_uri=http%…te_event%2Cuser_birthday%2Cemail&client_id=632348833449996&type=web_server' in a frame because it set 'X-Frame-Options' to 'DENY'. about:blank:1
This is part of the code:
passport.use(new FacebookStrategy({
clientID: "XXX",
clientSecret: "XXX",
callbackURL: "`http://localhost:3000/auth/facebook/callback`"
},
function(accessToken, refreshToken, profile, done) {
var fullname = profile._json.first_name + ' ' + profile._json.last_name;
// Web services all for user persistence
}
));
// configure Express
app.configure(function() {
app.use(express.logger());
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.session({ secret: 'keyboard cat' }));
// Initialize Passport! Also use passport.session() middleware, to support
// persistent login sessions (recommended).
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
});
app.all('/auth/facebook', passport.authenticate('facebook', { scope: ['read_stream', 'publish_actions','user_interests','read_friendlists','create_event','user_birthday','email' ]}));
app.all('/auth/facebook/callback', passport.authenticate('facebook',{ successRedirect: '/',failureRedirect: '/login' }));
app.listen(3000);
On my facebook app configuration I've set the App On Facebook configuration with the following URL: http://localhost:3000/auth/facebook/
What I'm doing wrong?