3

nodejs + Passport + MySQL の使い方を理解しようとしています。そこにあるほぼすべてのチュートリアルがmongoDBを使用しているように見えますが、私はそれをしたくありません。実際、このタイプのいくつかのクイック検索では、( http://nodejsrocks.blogspot.com/2012/04/nodejs-expressjs-mysql.html ) のような Web ページや、男である youtube ビデオ ( https://www .youtube.com/watch?v=jGBbMVJx3h0) ログインするだけで、実際に何を使用しているかは誰にもわかりませんが、このページには 3K 以上のビューがありました。開発者の何人かがそれを見て、MySQL で包括的な非 MVC タイプのもののようなものを使用する可能性があると言ってくれることを願っています。この理由は、iOS と Android の機能のみを取得しようとしており、大きな足場のオーバーヘッドを必要としないためです。クエリを処理し、JSON オブジェクトを電話に返す DB とサーバー側のスクリプトだけです。

そうは言っても、これを実際に経験したことがある人が私を助けてくれませんか(そして、mongoDBと本格的な足場を使用していないため、詳細なチュートリアルなしで同様のことをしようとしている世界の残りの部分) .

「TwitterStrategy」用に設定したテーブルは、users(id (PK)、username、email、salt、password) と twitterusers(id (PK)、name、screenname、location、description、url、img、token、トークンシークレット)。

これは、単一の 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 +エクスプレスチュートリアルのコピーの代わりに、すぐに利用できるようにする必要があります(スコッチioを除いて多くは古くなっています)mongo を使用したい場合、これは非常に良さそうです...Amazon でインスタンスを追加してもよいでしょう。ローエンドで月額約 279 ドルで実行されます)。再度、感謝します。

4

1 に答える 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);
});

それが物事をより明確にすることを願っています。

于 2014-06-24T23:32:23.603 に答える