Couldn't get everyauth's req.user inside router functions - node.js

I am a newbie of node.js and everyauth. While I just playing around everyauth I have realized that everyauth.user works in jade views but I couldnt get req.user work inside page callbacks.
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, everyauth = require('everyauth')
, Promise = everyauth.Promise
, util = require('util')
, models = require('./models');
//Everyauth setup
everyauth.twitter
.consumerKey('XXX')
.consumerSecret('XXX')
.findOrCreateUser(function(session, accessToken, accessTokenSecret, twitterData){
var promise = new Promise();
models.findOrCreateTwitterUser(twitterData,promise);
return promise;
})
.redirectPath('/');
var app = module.exports = express.createServer();
// Configuration
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.static(__dirname + '/public'));
app.use(express.cookieParser());
app.use(express.session({secret:"Iam james bond"}));
app.use(express.methodOverride());
//app.use(app.router);
app.use(everyauth.middleware());
});
app.configure('development', function(){
everyauth.debug = true;
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
app.use(express.errorHandler());
});
// Routes
app.get('/', function(req, res){
if(req.loggedIn){
console.log(req.user); //<--This is always undefined
}
console.log("index");
res.render('index', { title: 'Welcome to Chat app' });
});
//Helpers
everyauth.helpExpress(app);
app.listen(3000);
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
Here is the problematic part
app.get('/', function(req, res){
if(req.loggedIn){
console.log(req.user); //<--This is always undefined
}
console.log("index");
res.render('index', { title: 'Welcome to Chat app' });
});
It seems I am missing some point. The weird part is req.loggedIn works as expected but somehow everyauth don't populate user data.

To access the 'user' by req.user you need to configure everyauth.everymodule.findUserById like below
//Everyauth setup
....
....
everyauth.everymodule.findUserById( function (userId, callback) {
var db = app.set('db');
var User = db.main.model('User');
User.findById(userId, callback);
// callback has the signature, function (err, user) {...}
});
....
....
var app = module.exports = express.createServer();
//Configuration

I've been having issues with everyauth req.user with the latest versions. What I do is I use "req.session...". So If I want to get the user while under the facebook oauth, I'd use req.session.auth.facebook.user.id, and this gives me the users Id.
console.log(req.session) and from there extract whatever information you want to use.

Related

How to use session in ExpressJS?

As i understood i can use sessions only inside the requests, something like:
app.get('/', function (req, res) {
if (req.session.log_in)
res.render('index.html', config);
else
res.render('authorization.html', config);
});
But if i have for example 20 or more routes so i need to write authorization check in each route? Is there something global with sessions like in php that i could check sessions before all routes and determinate and decide on follow-up actions?
Express allows a middle parameter of middleware called for that route. Use an authorization system like Passport and call it like this:
app.get('/account', ensureAuthenticated, function(req, res){
res.render('account', { user: req.user });
});
We can manage session in ExpressJS using express-session package. If you are running it in shared resource, you need to use Redis or something to keep it consistent.
Server.js
var express = require('express');
var session = require('express-session');
var bodyParser = require('body-parser');
var app = express();
app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);
app.use(session({secret: 'ssshhhhh'}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
var sess;
app.get('/',function(req,res){
sess=req.session;
//Session set when user Request our app via URL
if(sess.email)
{
/*
* This line check Session existence.
* If it existed will do some action.
*/
res.redirect('/admin');
}
else{
res.render('index.html');
}
});
app.post('/login',function(req,res){
sess=req.session;
//In this we are assigning email to sess.email variable.
//email comes from HTML page.
sess.email=req.body.email;
res.end('done');
});
app.get('/admin',function(req,res){
sess=req.session;
if(sess.email)
{
res.write('
<h1>Hello '+sess.email+'</h1>
');
res.end('Logout');
}
else
{
res.write('
<h1>Please login first.</h1>
');
res.end('Login');
}
});
app.get('/logout',function(req,res){
req.session.destroy(function(err){
if(err){
console.log(err);
}
else
{
res.redirect('/');
}
});
});
app.listen(3000,function(){
console.log("App Started on PORT 3000");
});
Read complete tutorial here : http://codeforgeek.com/2014/09/manage-session-using-node-js-express-4/

Subdomains in Node.js with Express for Nodejitsu

I'd like to set up some subdomains for my Node.js app. I've built my site with express.js, and now I'd just like to throw up a little web tool on a subdomain of my site. I've tried using the vhost middleware with little luck, but am open to other approaches.
Any help would rock!
Ideally, I could just drop a new express app in a sub directory change a few lines of code, maybe change some DNS settings at it would work. The reason I'd like this is so that I can reuse a fresh instance of stylus and jade with new layouts and css styles and so forth.
Here's my normal app.js, the commented line is the attempt to use vhost.
var express = require('express'),
routes = require('./routes');
var app = module.exports = express.createServer();
// Configuration
app.configure(function() {
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.set('view options', { layout: false });
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use('/courses', function (req, res, next) {
var privates = require('./.private.json'),
couch = require('nano')('https://' + privates.dbCreds.username + ':' + privates.dbCreds.password + '#wamoyo.iriscouch.com/');
});
app.use(require('stylus').middleware({
src: __dirname + '/public'
}));
app.use(app.router);
app.use(express.static(__dirname + '/public'));
// VHOST - SUBDOMAIN
// app.use(express.vhost('adventures.innovationbound.com', require('./adventures/index').app));
app.use(function (req, res, next) {
res.status(404);
res.render('four', {
title: "Innovation Bound",
now: new Date().getFullYear()
});
});
app.use(function (err, req, res, next){
console.error(err.stack);
res.send(500, 'Something broke!');
});
});
app.configure('development', function() {
app.use(express.errorHandler({
dumpExceptions: true,
showStack: true
}));
});
app.configure('production', function() {
app.use(express.errorHandler());
});
// Routes
app.get('/', routes.index);
app.get('/about', routes.about);
app.get('/services', routes.services);
app.get('/events', routes.events);
app.get('/blog', routes.blog);
app.post('/contact', routes.contact);
// Courses
// app.get('/heartbeat', routes.heartbeat);
app.get('/courses', routes.courses);
// Tools
app.get('/point', routes.point);
app.listen(3000, function() {
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
});
This is using express 2.5, I wouldn't mind migrating over to 3 if need be.

Express: unable to access POST data and set cookie at the same time

I'm writing an application that takes in a post request and sets a cookie pulled from the POST info. I'm stuck in a catch 22. In the first code sample I can set the cookie but can't access the data, in the second I can access the data but can't set the cookie. I'm sure I'm missing some basic concept of how the middle ware works but I can't for the life of me find the info I need.
The code below creates the cookie as expected but my post variable become undefined
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, handshake = require('./routes/handshake')
, http = require('http')
, path = require('path');
var app = express();
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(function (req, res, next) {
var cookie = req.cookies.cokkieName;
console.log("cookie_name" , cookie);
if (cookie === undefined)
{
//cookie is set but I can't use req.post.xxxx. It"s always undefined
res.cookie("price", 111, { maxAge: 10000 });
console.log('cookie has been created successfully');
}
else
{
console.log('cookie exists', cookie);
}
next();
});
app.use(app.router);
app.use(require('stylus').middleware(__dirname + '/public'));
app.use(express.static(path.join(__dirname, 'public')));
app.post('/handshake', handshake.token);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
The following code executes the setCookie callback (because the console output shows up), and on the console the variables are properly defined, but the cookie is not set.
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, handshake = require('./routes/handshake')
, http = require('http')
, path = require('path');
var app = express();
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.methodOverride());
var setCookie = function (req, res, next) {
var cookie = req.cookies.cokkieName;
console.log("cookie_name" , cookie);
if (cookie === undefined)
{
res.cookie("price", 111, { maxAge: 10000 });
//in the console the post.body.xxxx data appears correctly but no cookie!!!
console.log('cookie has been created successfully',post.body.xxx);
}
else
{
console.log('cookie exists', cookie);
}
next();
};
app.use(app.router);
app.use(require('stylus').middleware(__dirname + '/public'));
app.use(express.static(path.join(__dirname, 'public')));
app.post('/handshake', setCookie ,handshake.token);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Trying to make the code more readable introduced too many typos that weren't relevant to my code. I took the suggestion and changed the code in the following way but it still doesn't write a cookie to the client.
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, handshake = require('./routes/handshake')
, http = require('http')
, crypt = require('crypto')
, io = require('socket.io')
, db = require('levelup')('./mydb')
, path = require('path');
var app = express();
app.use(express.cookieParser());
app.use(express.bodyParser());
var cookieMiddleware = function (req, res, next) {
var cookie = req.cookies.user;
console.log("cookie_name" , cookie);
if (cookie === undefined)
{
// no: set a new cookie
var random = Math.random().toString();
random=random.substring(2,random.length);
sessionToken = Date.now() + random;
salt = sessionToken + req.body.address;
sha2 = crypt.createHash('sha256');
sha2.update(sessionToken);
var price = req.body.price;
var encryptedSession = sha2.digest('hex');
console.log('post body',price );
res.cookie('user','price' , { maxAge: 100000 });
console.log('existing cookies', req.cookies);
}
else
{
console.log('cookie exists', req.cookies);
}
next();
};
//development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.logger('dev'));
app.use(express.session({secret: "TheSuperSecretStringForHashing"}));
app.use(express.methodOverride());
app.use(app.router);
//app.use(express.favicon());
app.use(require('stylus').middleware(__dirname + '/public'));
app.use(express.static(path.join(__dirname, 'public')));
app.post('/handshake', cookieMiddleware , handshake.token);
app.get('/', routes.index);
app.get('/users', user.list);
var server = http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
io = io.listen(server);
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
The handshake.js handler
exports.token = function(req, res){
req.body.title = 'Payment Portal';
res.render('payment_init', req.body);
};
You are checking for a cookie named cokkieName, but the cookie you are setting has the name price.
Try changing this to:
var cookie = req.cookies.price;
cookie should now contain your cookie value.

Node.js and Native MongoDB Connection fails

I am trying to set up a simple mongodb test server within my app.js node application but I keep getting "TypeError: Cannot read property 'arbiterOnly' of undefined". I am running it on local host and I have installed mongo db by running npm install mongodb in the folder I am making the application in. any help one what I am doing wrong would be greatly apreciated
here is my code for my application
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path');
var Db = require('mongodb').Db;
var Server = require('mongodb').Server;
var client = new Db('test', new Server('localhost:', 3100, {}));
var insertData = function(err, collection) {
collection.insert({name: "Kristiono Setyadi"});
collection.insert({name: "Meghan Gill"});
collection.insert({name: "Spiderman"});
// you can add as many object as you want into the database
}
var removeData = function(err, collection) {
collection.remove({name: "Spiderman"});
}
var updateData = function(err, collection) {
collection.update({name: "Kristiono Setyadi"}, {name: "Kristiono Setyadi", sex: "Male"});
}
var listAllData = function(err, collection) {
collection.find().toArray(function(err, results) {
console.log(results);
});
}
var app = express();
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(express.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
client.open(function(err, pClient) {
client.collection('test_insert', insertData);
// client.collection('test_insert', removeData);
// etc.
});
var people = [{name:'Keth',age:'33',email:'ktater#gmail.com'},
{name:'Donny',age:'20',email:'donjuan86#hotmail.com'},
{name:'Loran',age:'26',email:'geegeenat#facebook.com'},
{name:'Max',age:'18',email:'axxanan#gmail.com'}];
app.configure('development', function(){
app.use(express.errorHandler());
});
app.get('/', routes.index);
app.get('/users', user.list);
app.get('/people', function(req, res){
res.render('peeps', {people:people});
});
app.get('/people/:id', function(req, res){
var guy;
for (var i =0 ; i < people.length ; i++)
{
if(people[i].name == req.params.id)
guy = people[i];
}
res.render('viewPerson', {guy:guy});
});
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
My first guess here is that the connection is not opening. Try logging err with console.log in the client.open function. Also, the post you're getting your test code from is about 18 months old, it's possible that the code is out of date.

How can I use director as router in expressjs

I want to use express.js with Flatiron's director (router) and Resourceful (ODM) because I need like the benefits of routing tables and clean multi-db schemas with validation.
The reason why I now completly switch to Flatiron is, is because I think it needs some more time and there is not much doc material.
However, that is the current way I use director in express:
var express = require('express')
, director = require('director');
function hello(){
console.log('Success');
}
var router = new director.http.Router({
'/': {
get: hello
}
});
Unfortunatly this doesn't work and gives me just a "Cannot GET /"
So what's to do?
var express = require('express')
, director = require('director')
, http = require('http');
var app = express();
var hello = function () {
this.res.send(200, 'Hello World!');
};
var router = new director.http.Router({
'/': {
get: hello
}
});
var middleware = function (req, res, next) {
router.dispatch(req, res, function (err) {
if (err == undefined || err) next();
});
};
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.bodyParser());
app.use(middleware);
app.use(express.static(__dirname + '/public'));
});
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
There is a sample app using express, resourceful and director here.
If you have more doubts, you can ask them in our IRC room #nodejitsu on freenode.
First, in order to use director you need to wrap it up as a middleware and pass it to express, like so:
app.use(function (req, res, next) {
router.dispatch(req, res, function (err) {
if (err) {
// handle errors however you like. This one is probably not important.
}
next();
});
};
Aside from that: You don't need director to use resourceful, and express has its own router (so you may not even need/want director).

Resources