检查用户是否存在mongodb和passport.js?

时间:2016-06-06 19:20:04

标签: node.js mongodb passport.js passport-local

我使用猫鼬和护照本地作为我的策略。使用Redux我发送一个注册用户的动作,它工作正常。注册后,我想使用相同的凭据来登录用户。

我已登录使用JWT,但它没有击中任何后端,只有用户对象。我想知道如何使用护照对我的mongo后端进行身份验证,给出成功的响应,然后我可以继续使用我当前的设置来发布JWT。我知道我可能可以将其更改为更清洁并仅使用护照,但是到目前为止我还有这个工作,我现在只想将它连接到registerUser成功使用的真实数据库。

./服务器/模型/ account.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var passportLocalMongoose = require('passport-local-mongoose');

var Account = new Schema({
    username: String,
    password: String
});

Account.plugin(passportLocalMongoose);

module.exports = mongoose.model('Account', Account);

./ index.js (服务器入口点)

var bodyParser    = require('body-parser')

// db
var db            = require('./server/db'); // just db url
var mongoose      = require('mongoose');
var passport      = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var Account       = require('./server/models/account');

var app = new (require('express'))()
var port = 3000

// webpack stuff went here

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.use(passport.initialize());

app.get("/", function(req, res) {
  res.sendFile(__dirname + '/client/index.html')
})

passport.use(new LocalStrategy(Account.authenticate()));
mongoose.connect(db.url);

app.use(require('./server/routes')); <------------------------------ file below

app.listen etc

./服务器/ routes.js

var express = require('express'),
    _       = require('lodash'),
    config  = require('./config'),
    jwt     = require('jsonwebtoken');

var app = module.exports = express.Router();

// XXX: This should be a database of users :).
var users = [{                    <----------------------------dummy account
  id: 1,
  username: 'test',
  password: 'test'
}];
function createToken(user) {
  return jwt.sign(_.omit(user, 'password'), config.secret, { expiresIn: 60*60*5 });
}
function getUserScheme(req) {
  var username;
  var type;
  var userSearch = {};
  -- error stuff --
  return {
    username: username,
    type: type,
    userSearch: userSearch
  }
}

app.post('/sessions/create', function(req, res) {
  var userScheme = getUserScheme(req);
  -- error stuff --
  res.status(201).send({
    id_token: createToken(user)
  });
});

./ client / actions / index.js - 调用注册/登录的操作(注册与mongo一起使用,登录仅适用于虚拟对象)

export function registerUser(creds) {
  let config = {
    method: 'POST',
    headers: { 'Content-Type':'application/x-www-form-urlencoded' },
    body: `username=${creds.username}&password=${creds.password}`
  }
  return dispatch => {
    // dispatch(requestLogin(creds))
    return fetch('http://localhost:3000/register', config)
      .then((response) =>  {
        if (!response.ok) { console.log("err"); }
        else { dispatch(loginUser(creds)) }
      }).catch(err => console.log("Error: ", err))
  }
}
// Calls the API to get a token and
// dispatches actions along the way
export function loginUser(creds) {
  let config = {
    method: 'POST',
    headers: { 'Content-Type':'application/x-www-form-urlencoded' },
    body: `username=${creds.username}&password=${creds.password}`
  }
  return dispatch => {
    // We dispatch requestLogin to kickoff the call to the API
    // console.log(creds)
    dispatch(requestLogin(creds))
    return fetch('http://localhost:3000/sessions/create', config)
      .then(response =>
        response.json()
          .then(user => ({ user, response }))
      )
      .then(({ user, response }) =>  {
        if (!response.ok) {
          // If there was a problem, we want to
          // dispatch the error condition
          dispatch(loginError(user.message))
          return Promise.reject(user)
        }
        else {
          // If login was successful, set the token in local storage
          localStorage.setItem('id_token', user.id_token)
          // Dispatch the success action
          dispatch(receiveLogin(user))
        }
      }).catch(err => console.log("Error: ", err))
  }
}

1 个答案:

答案 0 :(得分:0)

我想你需要这样的东西:

export const passportJWT = function (passport) {
  passport.use(new JwtStrategy({
    jwtFromRequest: ExtractJwt.fromAuthHeader(),
    secretOrKey: config.JwtSecret,
  }, (jwtPayload, done) => {
  Account.findOne({ username: jwtPayload.username}, (err, account) => {
    if (err) return done(err, false);
    if (user) {
      return done(null, account);
    }
    return done(null, false);
  });
 }));
};

export const JWTAuthentication = (req, res, next) => {
  passport.authenticate('jwt', { session: false })(req, res, next);
};

然后将此中间件用于需要JWT身份验证的路由。 像:

yourRouter.get('/login', JWTAuthentication, (req, res) => {
  //if jwt authentication passed
  //you can access user object as req.user
});