护照:本地护照,快递和rethinkdb

时间:2016-03-06 14:03:12

标签: javascript node.js passport.js rethinkdb passport-local

我在使用Passport与RethinkDB一起工作时遇到了问题。我正在尝试使用本地护照进行身份验证并基于本教程的解决方案:Passport Tutorial with RethinkDB

我一直收到回复错误请求

我的节点模块的结构如下:

- server
  - auth
    - auth-controller.js
    - auth-router.js
    - index.js
  - db
    - index.js
  - views
    - index.html
- index.js

AUTH / AUTH-controller.js

var authController = {};

authController.getUser = function (req, res) {
  if (req.user && req.user.id) {
    res.json(req.user);
    return;
  }
  res.status(400).json(null);
};
authController.logout = function (req, res) {
  req.logout();
  res.redirect('/');
};

authController.login = function (req, res) {
  res.redirect('/');
};

module.exports = authController;

AUTH / AUTH-router.js

var express = require('express');
var authControllers = require('./auth-controller');
var auth = require('./index');
var authRouter = express.Router();

// Local
authRouter.use('/login/callback/local', auth.authenticate('local'), function (req, res) {
  res.redirect('/');
});
authRouter.post('/login/local', auth.authenticate('local'));

// All
authRouter.use('/user', authControllers.getUser);
authRouter.use('/logout', authControllers.logout);

module.exports = authRouter;

AUTH / index.js

var config = require('config');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var r = require('../db');

passport.serializeUser(function (user, done) {
  return done(null, user.id);
});

passport.deserializeUser(function (id, done) {
  r
    .table('Users')
    .get(id)
    .run(r.conn)
    .then(function (user) {
      done(null, user);
    });
});

var loginCallbackHandler = function (objectMapper) {
  return function (accessToken, refreshToken, profile, done) {
    if (accessToken !== null) {
      r
        .table('Users')
        .getAll(profile.username, { index: 'username' })
        .run(r.conn)
        .then(function (cursor) {
          return cursor.toArray()
            .then(function (users) {
              if (users.length > 0) {
                return done(null, users[0]);
              }
              return r.table('Users')
                .insert(objectMapper(profile))
                .run(r.conn)
                .then(function (response) {
                  return r.table('Users')
                    .get(response.generated_keys[0])
                    .run(r.conn);
                })
                .then(function (newUser) {
                  done(null, newUser);
                });
            });
        })
        .catch(function (err) {
          console.log('Error Getting User', err);
        });
    }
  };
};

var callbackURL = 'http://' + config.get('url') + ':' + config.get('ports').http + '/auth/login/callback/login';

// Local
passport.use(new LocalStrategy({
    callbackURL: callbackURL
  },
  loginCallbackHandler(
    function (profile) {
      return {
        'username': profile.username,
        'password': profile.password
      };
    }
  )
));

passport.checkIfLoggedIn = function (req, res, next) {
  if (req.user) {
    return next();
  }
  return res.status(401).send('You\'re not logged in');
};

module.exports = passport;

分贝/ index.js

var r = require('rethinkdb');
require('rethinkdb-init')(r);
var config = require('config');

r.connections = [];
r.getNewConnection = function () {
  return r.connect(config.get('rethinkdb'))
    .then(function (conn) {
      conn.use(config.get('rethinkdb').db);
      r.connections.push(conn);
      return conn;
    });
};

r.init(config.get('rethinkdb'), [
  {
    name: 'Users',
    indexes: ['username']
  }
]).then(function (conn) {
  r.conn = conn;
  r.connections.push(conn);
  r.conn.use(config.get('rethinkdb').db);
});

module.exports = r;

视图/ index.html中

<body>
  <h1>Passport/RethinkDB Example</h1>
{{#user}}
  <img style='width: 100px; height: 100px;' src='{{ avatarUrl }}'>
  <p>You are logged in as <span style="font-weight: bold;">{{ login }}</span>. Account created through <span style="font-weight: bold;">{{ type }}</span>.</p>
  <a href='/auth/user'>See user data</a>
  </br>
  <a href='/auth/logout'>Logout</a>
{{/user}}
{{^user}}
  <p>You are not logged in.</p>

  <form action="/auth/login/local" method="post">
    Username: <input type="text" name="username" value="sam"><br>
    Password: <input type="text" name="password" value="123"><br>
    <input type="submit" value="Submit">
</form>
{{/user}}
</body>

index.js

var config = require('config');
var express = require('express');
var session = require('express-session');
var engines = require('consolidate');

var app = express();
var auth = require('./auth');
var authRouter = require('./auth/auth-router');

// Middleware
app
  .use(session({
    secret: '#########',
    resave: false,
    saveUninitialized: true
  }))
  .use(auth.initialize())
  .use(auth.session());

// Views
app
  .set('views', __dirname + '/views')
  .engine('html', engines.mustache)
  .set('view engine', 'html');

// Routes
app
  .use('/auth', authRouter)
  .get('/', function (req, res) {
    res.render('index.html', { user: req.user });
  })
  .use(express.static(__dirname + '/../client'))
  .use('*', function (req, res) {
    res.status(404).send('404 Not Found').end();
  });

app.listen(config.get('ports').http);

我做了什么导致错误请求问题并且有一种简单的方法来调试它吗?

当我从表单提交用户名和密码时出现错误请求 ...这是我相信它发生在../ auth / login / local

的网址

1 个答案:

答案 0 :(得分:0)

您不显示您的服务器代码。我有一个类似的问题,这是因为我的bodyparser没有在服务器中设置:      const bodyParser = require('body-parser'); app.use(bodyParser.json()) app.use(bodyParser.urlencoded({ extended: true }))

或类似的东西。 POST请求通过正文发送信息。如果这不起作用,那么很高兴看到你的服务器代码。