EzDevInfo.com

everyauth

node.js auth package (password, facebook, & more) for Connect and Express apps

Node.js EveryAuth Get Google Email Address

I am attempting to retrieve the google email address when making an OAuth2.0 call to google, using EveryAuth NPM lib. Has anyone managed to get the email to return using EveryAuth?

everyauth.google
  .entryPath('/auth/google')
  .callbackPath('/auth/google/callback')
  .appId('216450162097.apps.googleusercontent.com')
  .appSecret('8b6yf2nznWHgAu7iKNyGn-0F')
  .scope(['https://www.googleapis.com/auth/userinfo.email'])
  .findOrCreateUser( function(session, userAttributes) {
    console.log(userAttributes);  })
  .redirectPath('/'); 

The scope: https://www.googleapis.com/auth/userinfo.email causes exception:

Error: Error 401 (Not Found)!!1 display:block;height:55px;margin:0 0 -7px;width:150px}* > #g{margin-left:-2px}#g img{visibility:hidden}* html #g img{visibility:visible}*+html #g img{visibility:visible} Google

401. That's an error.

There was an error in your request. That's all we know.

at [object Object].fail (/Users/thegoleffect/Documents/Projects/Spoondate/nitrous/node_modules/everyauth/lib/promise.js:50:15) at EventEmitter. (/Users/thegoleffect/Documents/Projects/Spoondate/nitrous/node_modules/everyauth/lib/modules/google.js:58:15) at EventEmitter.emit (events.js:67:17) at EventEmitter._respond (/Users/thegoleffect/Documents/Projects/Spoondate/nitrous/node_modules/everyauth/node_modules/restler/lib/restler.js:127:12) at EventEmitter._fireEvents (/Users/thegoleffect/Documents/Projects/Spoondate/nitrous/node_modules/everyauth/node_modules/restler/lib/restler.js:131:52) at /Users/thegoleffect/Documents/Projects/Spoondate/nitrous/node_modules/everyauth/node_modules/restler/lib/restler.js:115:19 at IncomingMessage. (/Users/thegoleffect/Documents/Projects/Spoondate/nitrous/node_modules/everyauth/node_modules/restler/lib/restler.js:205:5) at IncomingMessage. (/Users/thegoleffect/Documents/Projects/Spoondate/nitrous/node_modules/everyauth/node_modules/restler/lib/restler.js:113:32) at IncomingMessage.emit (events.js:81:20) at HTTPParser.onMessageComplete (http.js:133:23)


Source: (StackOverflow)

Configuring findByUserId for everyauth - node, express, mongoose, everyauth

I'm rather new to Node.js and Express. I'm trying to finish the configuration of everyauth with Twitter and I'm trying to access the 'res.user' on the server side which according to the documentation of everyauth requires that .findByUserId gets configured. That's where I'm having my trouble. How do you configure findByUserId?

Here's what I got. It's currently working to create a new user or log them in, I haven't setup the .findByUserId correctly yet giving me access to req.user which I need on the server side. If you have other suggestions on how to optimize this code, please let me know too since I'm just learning.

Code edited below...

App.js

var express = require('express')
  , everyauth   = require('everyauth')
  , util        = require('util')
  , Promise     = everyauth.Promise
  , users       = require('./lib/users')
  , config      = require('./config.js')
  , twitter     = require('./lib/twitter')
  , games        = require('./lib/games')

  everyauth.twitter
    .consumerKey(config.twitter.consumerKey)
    .consumerSecret(config.twitter.consumerSecret)
    .findOrCreateUser( function (session, accessToken, accessTokenSecret, twitterUserMetadata) {
      var promise = this.Promise();
      users.findOrCreateUserbyTwitterData(twitterUserMetadata, accessToken, accessTokenSecret, promise)
      return promise;
    })
    .redirectPath('/');
  everyauth.everymodule.findUserById(function (userId, callback) {
      users.findById(userId, callback);
  });

var app = module.exports = express.createServer();
everyauth.helpExpress(app);
// Configuration

app.configure(function(){
  app.set('views', __dirname + '/views');
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.cookieParser());
  app.use(express.session({secret: "FxT10477A93d54HJx5"}));
  app.use(everyauth.middleware());
  app.set('view engine', 'jade');
  app.use(express.static(__dirname + '/public'));
});

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function(){
  app.use(express.errorHandler());
});

// Routes

app.get('/', function(req, res){
  console.log(req.user);
  res.render('index', { title: 'Zeitheist 2' });
});

Users.js

var twitter = require(__dirname + "/twitter");
var mongoose = require('mongoose');
var Schema = mongoose.Schema
  , ObjectId = Schema.ObjectId;

var userSchema = new Schema({
    user                  : ObjectId
    , id                  : Number
    , twitterId           : Number
    , twitterName         : String
    , profileImageUrl     : String
    , name                : String
    , dateCreated         : Date
    , session             : String
    , accessToken         : String
    , accessTokenSecret   : String
});

var conn = mongoose.createConnection('mongodb://localhost/zeitheist2_test');
var userModel = conn.model('User', userSchema);

this.findOrCreateUserbyTwitterData = function(twitterData, accessToken, accessTokenSecret, promise) {
  userModel.find({'twitterId' : twitterData.id}, function(err, users) {
     if(err) throw err;
     if(users.length > 0) {
       promise.fulfill(users[0]);
     } else {
       var user = new userModel();
       user.twitterId = twitterData.id
       user.twitterName = twitterData.screen_name
       user.profileImageUrl = twitterData.profile_image_url
       user.name = twitterData.name
       user.accessToken = accessToken
       user.accessTokenSecret = accessTokenSecret
       user.save(function(err) {
         if (err) throw err;
         twitter.follow(accessToken, accessTokenSecret);
         promise.fulfill(user);
       });
     }
   });
}
this.findById = function(userId, callback) {
  userModel.findOne({'_id' : userId}, function(err, user) {
    if(err) throw err;
    if(callback) 
      callback(user);
    else
      return user;
  }); 
}

How does the everyauth.everymodule.findUserById need to look in order for me to access req.user? In the default route when I log req.user after I successfully login, it's showing "undefined"


Source: (StackOverflow)

Advertisements

Handling Facebook registration via my Facebook application - using nodejs everyauth

We have Facebook authentication integrated into our User Accounts system (nodejs, express) using everyauth.

What is done now (in pseudo code):

everyauth
  .facebook
    .appId('....')
    .appSecret('.....')
    .findOrCreateUser( 
      function (session, accessToken, accessTokenExtra, fbUserMetadata) {
      ...
      }
    .redirectPath('/internal/facebook');

Authentication works perfectly. The issue is when going through this flow:

  1. User does not have Facebook cookies for his User Agent now (User is not logged in into Facebook).

  2. User invokes authentication via Facebook (/auth/facebook service of everyauth is called)

  3. Facebook "Login/Sign in" page is loaded. User wants to create new facebook account and select "Sign up for Facebook".
  4. User finishes with registration details and then should confirm his Facebook account registration via our App by clicking the link in the mail he just received.
  5. So user goes to his mail, click the link and - he is redirected to the root - "/" - of our User-Account. - which is a web-service with no UI that provides User-Account service to different application...

Questions are following :

  1. How can we get the user after he is signed up for Facebook via our Application? findOrCreateUser() is not called in this scenario.
  2. How can we override the behavior of redirecting to "/" of our App after user is signed up to Facebook via our App (after successful user registration)?

Source: (StackOverflow)

Does dnode have authentication middleware?

I'm building an express app that uses everyauth and would like to use dnode. I want to be able to use the req.loggedIn boolean set up, but for dnode rpc calls.

Can this be done by having dnode listen to express? Can it access express middleware stuff??


Source: (StackOverflow)

Does connect.session work with node-azure

I'm starting to develop an application using node.js on azure. I'm using everyauth to provide authentication because I want to support lots of different authentication methods. I plan to deploy to Azure. The potential problem I have is that everyauth requires the connect.session helper. Will this work with azure when running multiple instances? Or do I need an alternative session provider?


Source: (StackOverflow)

new cookie value from socket.io doesn't work?

I try to use socket.io id for multiple browser Window/Page. It's for SNS-auth-process using everyauth, and the project is based on express.

Here is my project design:

A full ajax main page maintaining a socket.io connection. No reload, no redirect etc.

When a user try to login via some SNS account, a popup window opens, which will be managed by everyauth and SNS Auth. Inside the popup window, many redirects occur, but the main window is persistent, so as the socket.io connection.

Finally, after the successful authorization, everyauth redirects 'authdone.html' in the popup window.

On the browser, this popup window is no longer useful, so window.close();

but, a successful login info can be obtained throughout the everyauth, but in my case, cookie is more important since I don't exactly need a session management with express framework because what I intend to do is session management through socket.IO.

app.get('*',
    function (req, res)
    { 
        console.log("----------get------------");
        console.log(req.url);
        if (req.url == '/public/authdone.html')
        {
            console.log("----------get /public/authdone.html------------");
            console.log(req.cookies);  
            // express(connect) sessionID(sid) cookie available here.
            //{ 'connect.sid': '2DLlayNx90wtTsyeq5w83N9g.Kc1ZFd8I7omf6u4fk4FFyKAt4dP1V6IufSf1ZtRudVI' }
        }
        onreq(req, res);
    });

Currently, I managed to obtain express sessionID via cookie on the popup window redirected to the landing page(/public/authdone.html), however, this is not enough. I also need to obtain a socket.IO oriented ID here in the cookie.

Actually, I confused here, and asked a question. Adding a cookie value on Socket.IO

Thanks to Wes, I slightly find a way to add a new cookie value(in my case, some socket client ID) as below:

io.configure(function ()
{
    io.set('authorization', function (handshake, callback)
    {
        if (handshake.headers.cookie)
        {
            var cookie = handshake.headers.cookie;
            var newS = ";" 
                + "socketClientID" + "=" 
                + "999999999999999";// eventually randomize for every client
            cookie += newS;
            console.log("=========================================");
            console.log(cookie);  
        } else
        {
            return callback('Cookie not found', false);
        }
        callback(null, true);
    });
});

In this block, I add a cookie value as "socketClientID=999999999999999"

So the current cookie output via console.log is

connect.sid=fc2iTJW3ETD7nIyxI5ZwpayK.S0qGhp1Ryw7Msg2r03yB6g822qVZIZTbZyWUSpQL0aU;
socketClientID=999999999999999

So far so good, however, on the everyauth redirected page, I still get

----------get /public/authdone.html------------  
{ 'connect.sid': 'fc2iTJW3ETD7nIyxI5ZwpayK.S0qGhp1Ryw7Msg2r03yB6g822qVZIZTbZyWUSpQL0aU' }

only express sessionID(connect.sid) can be obtained via the cookie, added clientID cookie value on the socket.IO handshake phase is not reflected.

I really need a help. thanks.


Source: (StackOverflow)

Can't get custom user from everyauth

I did read manuals about access to current user via everyauth. It's say, that I can read current user info from: req.user on my server, everyauth.user and user on my views, but they are undefined. But if I'm try get access from, for example, everyauth.twitter or everyauth.facebook, I'm get user info from this social networks.

I'm want, when get user from database (find or create by social data) it's must save in session variable, like currentUser, and i can get it in helpers and in other databare requests.

My app.js code:

var express     = require('express')
  , everyauth   = require('everyauth')
  , Promise     = everyauth.Promise
  , util        = require('util')
  , mongoose    = require('mongoose')
  , routes      = require('./routes')
  , _           = require('underscore')

mongoose.connect('mongodb://127.0.0.1/base');
var Schema = mongoose.Schema
  , ObjectId = Schema.ObjectId;

// Everyauth settings above that app.configure

everyauth.twitter
  .consumerKey('secretKey')
  .consumerSecret('secret')
  .findOrCreateUser(function (session, accessToken, accessTokenSecret, twitterUserData){
      var promise = this.Promise();
      User.findOrCreateByUidAndNetwork(twitterUserData.id, 'twitter', twitterUserData, promise);
      return promise;
  })
  .redirectPath('/')
everyauth.facebook
    .appId("secretId")
    .appSecret("secret")
    .findOrCreateUser( function (session, accessToken, accessTokenExtra, fbUserMetadata) {
      var promise = this.Promise();
      User.findOrCreateByUidAndNetwork(fbUserMetadata.id, 'facebook', fbUserMetadata, 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.cookieParser());
  app.use(express.session({secret:'blablabla'}));
  app.use(everyauth.middleware()); // Yes, i'm use it
  app.use(express.methodOverride());
  app.use(app.router); // And it
  app.use(express['static'](__dirname + '/public'));
});

everyauth.helpExpress(app); // And this above that routes

app.dynamicHelpers({
    currentUser: function (req, res){
        return req.user; //it's empty!
    }
})

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);
require("./controllers/user");

app.listen(80);

And user Scheme:

var Schema = mongoose.Schema
  , ObjectId = Schema.ObjectId;

var UserSchema = new Schema({
    "uid":{type:String},    
    "name":{type:String},   
    "network":{type:String},
    "profile":{}        
});


mongoose.model('User', UserSchema);

var User = mongoose.model('User');

And user find or create function:

this.findOrCreateByUidAndNetwork = function(uid, network, profile, promise) {
    User.find({uid: uid, network: network}, function(err, users) {
        if(err) throw err;
        if(users.length > 0) {
            promise.fulfill(users[0]);// <-- what i want:)
        } else {
            var user = new User();
            user.network = network;
            user.uid = uid;
            user.profile = profile;
            user.name = profile.first_name || profile.name;
            user.save(function(err) {
                if (err) throw err;
                promise.fulfill(user);
            });
        }
    });
};

Thanks, for watching my question. Best regards, Asci


Source: (StackOverflow)

NowJS current session

I am creating node.js app using express, everyauth and now.js.

I have a server-side now.js function in which I want to be able access the 'User' object for the authenticated user calling this function. I dont have access to the a 'request' or 'session' object, I only have the user cookie and connect.sid

My question is, whats best way to get the session information I'm looking for? Do I store these details in the cookie when the original page request comes in? Or Is there a way to get the session object from the connect.sid?

Thanks


Source: (StackOverflow)

Express.js: how to bypass Everyauth for certain routes?

I'm writing an application based on Express.js, while using Everyauth for authentication.

To initialize everyauth, I use:

app.use(everyauth.middleware());

I'd like to bypass authentication for certain routes. Specifically, I noticed findUserById is called for every request, and I'd like to skip it for certain routes (e.g. no authentication for /getImage).

Is that possible?


Source: (StackOverflow)

User Permission Level in Passport

Any tutorials on using the Dynamic scope and permissions of the Passport authentication library for Node.

Did not find any in the documentation.

How do we set the user type for the authenticated user?

Is it easier to do in everyauth?


Source: (StackOverflow)

Why does this code with nodejs, and everyauth crash with an empty array from MySQL?

Hello my friends, I have some code that connects to a mysql db to auth any user... this code works fine. The problem is when I receive an empty array from mysql, it crashes nodejs...

This is part of the code in everyauth... sql is a exported function...

var promise = this.Promise();

            sql.getUserInfo(userInfo, function(user, err) {
                if(err) return promise.fulfill([ err ]);

                promise.fulfill(user);
            });

            return promise;

I have no idea what promise is, but don't think that's the problem. This is the error in console when nodejs crashes:

starting step - extractLoginPassword
...finished step
starting step - authenticate
[]//--- it cames from mysql when there is no user and password 

timers.js:96
            if (!process.listeners('uncaughtException').length) throw e;

This is the exported function that calls the db and extracts information:

exports.getUserInfo = function(user, callback) {
  var email = user.email;
  var passwd = user.password;
  var sql = "SELECT id_email, contrasena FROM usuarios.usuario WHERE id_email = ? AND contrasena = ? ";
  var params = [email, passwd];

  client.query(sql, params, function(err, rows) {

    if (err) return callback(null, err);
    if (rows && rows.length > 0) {
      var user = rows[0];

      callback(user,err);
    }

Thanks all! ^


Source: (StackOverflow)

How can I deny a user from logging in with mongoose-auth / everyauth

Using node.js / expressjs / mongoose / mongoose-auth / everyauth. All versions are up to date.

I'm trying to use a database table to whitelist users by email address during development, but I want the primary method of auth to be facebook. I'm looking to have mongoose-auth only create the account if the facebook email is found in alpha_whitelist. This creates accounts as expected for addresses that are in the table, but it times out and crashes the server if the user is not in the whitelist.

findOrCreateUser:   function (sess, accessTok, accessTokExtra, fbUser) {
    var promise = this.Promise(),
        User = this.User()();
        // TODO Check user in session or request helper first
        // e.g., req.user or sess.auth.userId
        User.findOne({'fb.id': fbUser.id}, function (err, foundUser) {
            if(foundUser)
                return promise.fulfill(foundUser);
            alpha_whitelist.findOne(
                {email: fbUser.email},
                function(err,doc) {
                    if(doc) {
                        console.log("CREATING");
                        User.createWithFB(fbUser, accessTok, accessTokExtra.expires, function (err, createdUser) {
                            console.log(err,createdUser);
                            if (err) return promise.fail(err);
                            return promise.fulfill(createdUser);
                        });
                    } else {
                        console.log('Denied');
                        //not sure what to do here... i need to break the auth chain and redirect the user back to '/'
                    }
                });
        });
        return promise;
    }

It seems that no matter what I put there, it fails and crashes the server. I'm clearly missing something. Any help would be appreciated.


Source: (StackOverflow)

Concerns in using everyauth

I am having serious trouble in using everyauth. All I need is facebook login. For that I am trying to use the example of everyauth. Once I do facebook authentication, how can I check in every page if the user is logged in or not/ get his facebook information. What I have done is

var exp = require('express');
var app = exp.createServer();

var conf = require('/Users/lakeshkansakar/clicker/node_modules/everyauth/example/conf')
var everyauth = require('everyauth');

everyauth.debug = true;

var usersById = {};
var nextUserId = 0;

function addUser (source, sourceUser) {
  var user;
  user = usersById[++nextUserId] = {id: nextUserId};
  user[source] = sourceUser;
  return user;
}

var usersByFbId = {};
var usersByTwitId = {};

everyauth.everymodule
  .findUserById( function (id, callback) {
    callback(null, usersById[id]);
  });

everyauth
  .facebook
    .appId(conf.fb.appId)
    .appSecret(conf.fb.appSecret)
    .findOrCreateUser( function (session, accessToken, accessTokenExtra, fbUserMetadata) {
      return usersByFbId[fbUserMetadata.id] || (usersByFbId[fbUserMetadata.id] = addUser('facebook', fbUserMetadata));;
    })
    .redirectPath('/');

everyauth
  .twitter
    .consumerKey(conf.twit.consumerKey)
    .consumerSecret(conf.twit.consumerSecret)
    .findOrCreateUser( function (sess, accessToken, accessSecret, twitUser) {
      return usersByTwitId[twitUser.id] || (usersByTwitId[twitUser.id] = addUser('twitter', twitUser));;
    })
    .redirectPath('/');

In every get request, I then tried to check if everyauth.loggedIn is true or not. However, everyauth.loggedIn is shown to be undefined. Why is it so? How to check if the user has logged in using facebook?


Source: (StackOverflow)

triggering everyauth login process without page refresh (facebook auth)

I've set up everyauth and it seems quite nice.

Right now, as illustrated in this NodeTuts episode, one has to go to http://www.example.com/auth/facebook or http://www.example.com/auth/twitter in order to authenticate.

How can I configure everyauth to allow me to attach a JavaScript event to a button to trigger authentication?

For example, in the following code, the button at the bottom when clicked should popup a Facebook authentication window. How do I do that with everyauth?

<html>
    <head>
      <title>My Facebook Login Page</title>
    </head>
    <body>
      <div id="fb-root"></div>
      <script>
        window.fbAsyncInit = function() {
          FB.init({
            appId      : 'YOUR_APP_ID',
            status     : true, 
            cookie     : true,
            xfbml      : true,
            oauth      : true,
          });
        };
        (function(d){
           var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
           js = d.createElement('script'); js.id = id; js.async = true;
           js.src = "//connect.facebook.net/en_US/all.js";
           d.getElementsByTagName('head')[0].appendChild(js);
         }(document));
      </script>
      <div class="fb-login-button">Login with Facebook</div>
    </body>
</html>

Source: (StackOverflow)

everyauth.twitter.redirectPath('/'); - change based on original page URL

I want a user to be able to share a link to secure content eg. www.mysite.com/#/article1, then when another user opens this link, they get redirected to the login page, then on complete they get redirected to the same URL.

I have a single page app so using hash tags, but I don't see any way to do this with normal URLs either.

Currently .redirectPath('/') has to be a string so I cannot make it a function that returns a string, also it does not have access to req.url so not sure how I would be able to dynamically get that value.

This is not a twitter specific issue, it is the same with all the oAuth logins I believe.


Source: (StackOverflow)