2014-06-24 3 views
2

나는 nodejs + Passport + MySQL을 사용하는 방법을 알아 내려고하고있다. 마치 mongoDB를 사용하고있는 튜토리얼에 관한 것만 큼 그렇게 보이고 싶지는 않습니다. 사실이 유형의 일부 빠른 검색은 (http://nodejsrocks.blogspot.com/2012/04/nodejs-expressjs-mysql.html)과 같은 웹 페이지를 생성하고 로그인하는 것 뿐인 사람 (실제로는 사용중인 것을 알고 있지만 페이지는 3K + 조회수를 가졌습니다) 인 유튜브 비디오를 생성합니다 . 개발자 중 일부는 MySQL을 사용하여 포괄적 인 비 MVC 타입과 같은 것을 사용하고 있다고 말할 수 있기를 바랍니다. 내 이유는 내가 IOS와 안드로이드 기능을 얻으려고하고 큰 발판 오버 헤드가 필요 없다는 것입니다. 쿼리를 처리하고 JSON 객체를 전화기로 반환하는 DB 및 서버 측 스크립트.Nodejs + Passport + MySQL

이렇게 말하면 실제 경험이있는 사람이 나를 도와주세요. (그리고 mongoDB를 사용하지 않기 때문에 심층적 인 튜토리얼없이 비슷한 일을하려고하는 나머지 세계와 전면 발판).

사용자가 (ID (PK), 사용자 이름, 이메일, 소금, 암호) twitterusers (ID (PK), 이름, 화면 이름, 위치, 설명, 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 란 무엇입니까? 자습서는 승인을 위해 트위터에 사용자로 보이는 것에서 전달되고 있습니까? 또한 트위터의 콜백에서 무엇을 기대해야합니까? 어쨌든이 모든 것을 어딘가에 게시하여 다른 사람들이 한번 볼 수있게 해줘서 기쁘다. 그래서 우리는 MySQL과 노드를 사용하는 우리 모두가 손을 떼지 않고 보이는 것을 찾기 위해 구글을 검색해야만한다. 마치 똑같은 nodejs + mongoDB + express 튜토리얼 (scotch io를 제외하고는 구식 인 많은 것들을 가지고 있습니다. mongo를 사용하고 싶다면 아주 잘 보이는 ...)을 추가 할 수 있습니다. 아마존에서의 인스턴스는 저급에서 한달에 약 279 달러를 기록했다.) "튜토리얼"이 나와있는 거의 모든 사람들이 떠 다니고 재배포되고있다. 다시 한번 감사드립니다. process.nextTick에서

+0

이 글은 지금까지는 오래된 글이지만 앞으로 누군가가 올 경우를 대비하여이 Github 프로젝트를 살펴 보시기 바랍니다 : https://github.com/manjeshpv/node-express-passport-mysql – Gikkman

+0

[Javascript Passport, MySQl 및 Express를 사용한 인증] (http://denisahac.xyz/javascript-authentication-using-passport-mysql-and-express/) –

답변

0

시도 포장 전략 기능, 예를 들어,

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

이 사물 명확하게 바랍니다.

관련 문제