Nodejs + Passport + MySQL

时间:2014-06-24 18:54:00

标签: mysql node.js passport.js passport-twitter

我正在试图弄清楚如何使用nodejs + Passport + MySQL。好像几乎每个教程都使用mongoDB,我不想这样做。事实上,这种类型的快速搜索会产生像(http://nodejsrocks.blogspot.com/2012/04/nodejs-expressjs-mysql.html)和youtube视频这样的网页(https://www.youtube.com/watch?v=jGBbMVJx3h0)除了登录之外什么也不做,以及谁知道他真正使用的是什么,但页面有3K +视图。我希望有些开发人员能够看到这一点,并说可能有类似于MySQL的综合非MVC类型的东西。我的理由是我只想获得iOS和Android功能,而不需要大量的脚手架开销。只是DB和服务器端脚本处理查询并将JSON对象返回给手机。

所以,有人说,有真正经验的人可以帮助我(并且世界其他地方试图在没有任何深入的教程的情况下做类似的事情,因为我们没有使用mongoDB和完整吹制脚手架)。

我为'TwitterStrategy'设置的表是用户(id(PK),用户名,电子邮件,盐,密码)和twitterusers(id(PK),名称,屏幕名称,位置,描述,网址,img) ,令牌,tokensecret)。

以下是我试图从单个main.js文件中获取的代码。我知道这不是最佳实践,我打算稍后进行清理,但就目前而言,我想了解我所缺少的内容并使其工作正常。如果有人可以提供帮助,我将非常感激,我确信其他人也会发现这非常有用。感谢。

var http  = require('http'),
    mysql = require('mysql'),
    url   = require('url'),
    crypto = require('crypto'),
    express = require('express'),
    flash = require('connect-flash'),
    passport = require('passport'),
    TwitterStrategy = require('passport-twitter').Strategy;

var db = mysql.createConnection({
    host     : "****",
    user     : "****",
    password : "****",
    port     : '****',
    database : '****' 
});

// Connect the connection to DB and throw error if exists
db.connect(function(err) {
    if (err) { 
        console.error('Error connecting to db');
        console.error(err);
        return;
    }
    console.log('Database connected');
});

var TWITTER_CONSUMER_KEY = "****";
var TWITTER_CONSUMER_SECRET = "****";

passport.use(new TwitterStrategy({
    consumerKey: TWITTER_CONSUMER_KEY,
    consumerSecret: TWITTER_CONSUMER_SECRET,
    callbackURL: 'http://127.0.0.1:3000/auth/twitter/callback'},
    function(accessToken, refreshToken, profile, done) {
        //db.query(SELECT ........ FROM ...... WHERE ........, function (err, user){
            if (err) {
                console.log(err);
            }
            if (!err && user != null){
                done(null, result);
            } else {
                console.log(result);
            }
        })
        });
    }
));

passport.serializeUser(function(user, done) {
    console.log('serializeUser: ' + user.id);
    done(null, user.id);
});

passport.deserializeUser(function(id, done) {
    db.query('SELECT * FROM users WHERE id = ' + id, function(err, result) {
        if (err){
            console.log(err);
        } else {
        console.log(result);
        }
        if (!err) {
            done(null, result);
        } else {
            done(err, null);
        }
    });
});

var app = express();

app.set(function(){

    // app.set('views', __dirname + '/views'); // Definitely for some views which aren't being used here
    // app.set('view engine', 'jade'); // Using jade for views, not used
    // app.use(express.favicon()); // Not really sure this is important, should be web only
    app.use(express.logger('dev')); // Again, not really sure this is important
    app.use(express.bodyParser()); // Have no idea what this is used for
    app.use(express.methodOverride()); // Same no Fn clue
    app.use(express.cookieParser('what the F'));
    app.use(express.session());
    app.use(passport.initialize());
    app.use(passport.session());
    app.use(flash());
    // app.use(app.router); // Here again we are defining our routes in main, so shouldn't need this.
    // app.use(express.static(__dirname + '/public'));

});

var server = http.createServer(function(req, res) {
    console.log('url: ' + req.url); 

    var params = url.parse(req.url, true)
    var path = params.pathname;
    if (path == '/signup') {
        console.log("User signing up");
        onSignUp(params, res);
    } else if (path == '/signin') {
        console.log("User signing in");
        onSignIn(params, res);
    } else if (path == '/auth/twitter'){
        passport.authenticate('twitter'),
        function(req, res){
            console.log('Twitter User Created or Signed In');
        }
    }
});

//Keep server alive and listening to requests with DB connected also
server.listen(3000);

我错过了另一个身份验证表吗?我需要在MySQL语句中放置什么,以便我可以找到用户,以及从用户请求传递什么参数以获取查询,即我在此中看到的这个oauth ID是什么从似乎是用户传递给twitter进行授权的教程?另外,我应该从Twitter的回调中得到什么?无论如何,我很乐意将其他所有内容发布给其他所有人,一旦我有一个解决方案,所以我们所有人使用MySQL和节点都不会被遗漏,必须搜索谷歌找到一些似乎好像它应该是随时可用的,而不是相同的nodejs + mongoDB + express教程的副本(除了scotch io之外,许多已经过时了,如果你想使用mongo看起来非常好......我可以添加在亚马逊上运行的实例在低端每月估计大约279美元,这种情况在几乎每个有“教程”的人身上都会被重新分配。再次感谢。

1 个答案:

答案 0 :(得分:0)

尝试在process.nextTick下包装策略功能,例如,

passport.use(new TwitterStrategy({
    consumerKey: TWITTER_CONSUMER_KEY,
    consumerSecret: TWITTER_CONSUMER_SECRET,
    callbackURL: 'http://127.0.0.1:3000/auth/twitter/callback'},
    function(accessToken, refreshToken, profile, done) {
        process.nextTick(function(){
        // this is where you put logic to check the profile sent from twitter already in your DB or not, 
        // its totally up to you whether you keep a separate auth table for it or not
        // NB: there will be some unique value in profile that can be used for next references
        db.query(SELECT ........ FROM ...... WHERE ........, function (err, user){
            if (err) {
                console.log(err);
            }
            if (!err && user != null){
                done(null, result);
            } else {
                console.log(result);
            }
        })
        });
       });
    }
));

你还必须有一条接受回调的路线,例如,

app.get('/auth/twitter/callback', function(req, res, next) {
   passport.authenticate('twitter', 
                           { }, 
                           function(err, user) {
                            // the result you send from the strategy function will be here
                            // do anything you like with the user send 
                           }

                         )(req, res, next);
});

希望它能让事情更加清晰。