Nodejs + Passport + MySQL

3
我正在尝试使用nodejs + Passport + MySQL。似乎每个教程都在使用mongoDB,而我不想这样做。实际上,这种类型的快速搜索将产生网页,例如(http://nodejsrocks.blogspot.com/2012/04/nodejs-expressjs-mysql.html)和一个YouTube视频,其中一个人(https://www.youtube.com/watch?v=jGBbMVJx3h0)什么都没有做,只是登录,谁知道他真正使用的是什么,但该页面已经有3000多次浏览。我希望一些开发人员能看到这一点,并说也许有类似综合非MVC类型的MySQL东西的用途。我的原因是我只想获取iOS和Android功能,并且不需要大量的脚手架开销。只需DB和服务器端脚本处理查询并将JSON对象返回到手机即可。
那么,有没有真正经验的人可以帮助我(以及其他试图进行类似操作但没有深入教程的人,因为我们不使用mongoDB和完整的脚手架)。
我为“TwitterStrategy”设置的表是users(id(PK),username,email,salt,password)和twitterusers(id(PK),name,screenname,location,description,url,img,token,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和Node的人不会被落下,不必搜索Google以寻找似乎应该易于获取的东西,而不是那些已经过时(除了Scotch io外,看起来非常好,如果你想使用Mongo...我可以补充说,在Amazon上运行的实例每月低至$279)的完全相同的nodejs + mongoDB + express教程,几乎任何人都在重新分发它们。再次感谢。

这是一篇旧文章,但如果将来有人路过这里,请查看此Github项目:https://github.com/manjeshpv/node-express-passport-mysql - Gikkman
使用Passport、MySQL和Express进行Javascript身份验证 - Den Isahac
1个回答

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);
});

希望它能使事情更清晰。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接