8

Node.js (Express フレームワークを使用) で Web サイトを開発しています。Twitter 認証を使用するために、私は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'));
});

ログインに関連付けられている URI は次のとおりですhttp://local.host:3000/auth/twitter。Twitter にアクセスすると、自分のアカウントを自分の Web サイトにリンクするための認証フォームが表示されますが、この手順の後、次のエラーが発生します。

Express
500 ReferenceError: User is not defined

どうすればこの問題を解決できますか? よろしく、ヴィ。

4

5 に答える 5

7

User タイプをどこかで定義する必要があります。Userこのものが存在し、関数findOrCreateとがあることを期待しているように見えますがfindById、それをどこにも定義していません。これらのユーザーをどこで「見つけていますか?」見つからないものは、どこで「作成」されていますか? データベースを使用していますか?どのようにデータベースに接続しますか? 「モデル」のステップを忘れたと思います。Passport に似たMongoose Authをご覧になることをお勧めしますが、Mongooseデータベースに接続するMongooseに直接プラグインします。

于 2012-10-14T20:40:26.630 に答える
0

ユーザーのデータベース統合を必要としない場合には、API の準備ができていないと思います。私の解決策は、関数を無視done()して成功ページにリダイレクトすることでした。

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');
  }
));
于 2015-05-12T15:22:43.773 に答える
0

マックスの答えをさらに説明するには、「自分で作成する必要がありUserます」

ここを読む

TL:DR - 基本的に、ユーザーを設定してユーザーを確認するために使用するユーザースキーマが必要です。実際には設定が簡単な mongoose db バックエンドが必要です。

基本的にこのミドルウェアを作成します:

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);
于 2016-10-25T20:27:58.497 に答える