在Node中使用Passport中间件进行Twitter身份validation
我正在开发一个网站与Node.js(使用Express框架)。 为了使用Twitter身份validation,我正在使用passport
模块(http://passportjs.org),他的Twitter包装器称为passport-twitter
。
我的服务器端脚本是:
/** * Module dependencies. */ var express = require('express') , routes = require('./routes') , user = require('./routes/user') , http = require('http') , path = require('path') , passport = require('passport') , keys = require('./oauth/keys') , TwitterStrategy = require("passport-twitter").Strategy; var app = express(); app.configure(function(){ app.set('port', process.env.PORT || 3000); app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.cookieParser('foo')); app.use(express.session()); // Initialize Passport! Also use passport.session() middleware, to support // persistent login sessions (recommended). app.use(passport.initialize()); app.use(passport.session()); app.use(app.router); app.use(require('less-middleware')({ src: __dirname + '/public' })); app.use(express.static(path.join(__dirname, 'public'))); }); app.configure('development', function(){ app.use(express.errorHandler()); }); passport.serializeUser(function(user, done) { done(null, user.id); }); passport.deserializeUser(function(id, done) { User.findById(id, function (err, user) { done(err, user); }); }); passport.use(new TwitterStrategy({ consumerKey: keys.twitterConsumerKey, consumerSecret: keys.twitterConsumerSecret, callbackURL: "http://local.host:3000/auth/twitter/callback" }, function(token, tokenSecret, profile, done) { User.findOrCreate({ twitterId: profile.id }, function (err, user) { if (err) { return done(err); } else { return done(null, user); } }); } )); app.get('/', routes.index); app.get('/contacts', routes.contacts); app.get('/cv', routes.cv); app.get('/projects', routes.projects); app.get('/users', user.list); // Redirect the user to Twitter for authentication. // When complete, Twitter will redirect the user back to the // application at /auth/twitter/callback app.get('/auth/twitter', passport.authenticate('twitter')); // Twitter will redirect the user to this URL after approval. Finish the // authentication process by attempting to obtain an access token. If // access was granted, the user will be logged in. Otherwise, // authentication has failed. app.get('/auth/twitter/callback', passport.authenticate('twitter', { successRedirect: '/', failureRedirect: '/login' } ) ); http.createServer(app).listen(app.get('port'), function(){ console.log("Express server listening on port " + app.get('port')); });
与login相关的URI是http://local.host:3000/auth/twitter
; 当我访问它时,Twitter向我显示了用于将我的帐户与我自己的网站链接的身份validation表单,但是在此步骤之后,发生以下错误:
Express 500 ReferenceError: User is not defined
我怎么解决这个问题? 最好的问候,六。
您必须在某处定义您的用户types。 它看起来像你期望这个东西User
存在,并有函数findOrCreate
和findById
,但你从来没有在任何地方定义。 你在哪里“find”这些用户? 那些没有find的,他们在哪里被“创造”? 你在使用数据库吗? 你如何连接到数据库? 我想你忘了“模型”的一步。 你可能想看看Mongoose Auth ,就像护照,但它直接插入Mongoose ,它连接到一个Mongo数据库
这是我遇到同样的错误,说User
没有定义时,我做了什么:
passport.use(new TwitterStrategy({ consumerKey: keys.twitterConsumerKey, consumerSecret: keys.twitterConsumerSecret, callbackURL: "http://local.host:3000/auth/twitter/callback" }, function(token, tokenSecret, profile, done) { done(null, profile); } ));
当我们在Kraken中整合了Passport的BeatsMusic OAuth2策略时,我遇到了同样的问题。 它看起来像各种Kraken Passport集成策略的例子使用相同的简单的示例文档,没有明确讨论用户对象(可以理解)。
在我包含User = require('../PATH_TO/user')
并将此插件添加到用户模型后,瞧! 没有更多的错误:)
听起来就像你不需要数据库function,所以你可能是很好的删除身份validation检查。
希望这有助于任何有类似问题的人。
我觉得api没有准备好的情况下不需要用户的数据库集成。 我的解决scheme是忽略done()
函数,并redirect到成功页面。
passport.use(new TwitterStrategy({ consumerKey: keys.twitterConsumerKey, consumerSecret: keys.twitterConsumerSecret, callbackURL: "http://local.host:3000/auth/twitter/callback" }, function(token, tokenSecret, profile, done) { //done(null, profile); this.redirect('/auth/success'); } ));
为了进一步解释Max的答案:“你需要自己创buildUser
”
阅读这里
TL:DR – 基本上你必须有一个用户模式来设置用户和validation用户,它需要一个mongoose数据库后端,这实际上很容易configuration。
本质上是创造这个中间件:
var mongoose = require('mongoose'); var bcrypt = require('bcrypt-nodejs'); // define the schema for our user model var userSchema = mongoose.Schema({ local : { email : String, password : String, group : String, }, facebook : { id : String, token : String, email : String, name : String }, twitter : { id : String, token : String, displayName : String, username : String }, google : { id : String, token : String, email : String, name : String } }); // methods ====================== // generating a hash userSchema.methods.generateHash = function(password) { return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null); }; // checking if password is valid userSchema.methods.validPassword = function(password) { return bcrypt.compareSync(password, this.local.password); }; // create the model for users and expose it to our app module.exports = mongoose.model('User', userSchema);