【问题标题】:Checking if a user exists with mongodb and passport.js?使用 mongodb 和 passport.js 检查用户是否存在?
【发布时间】:2016-06-08 15:58:04
【问题描述】:

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

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

./server/models/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

./server/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))
  }
}

【问题讨论】:

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


    【解决方案1】:

    我猜你需要类似的东西:

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

    【讨论】:

      猜你喜欢
      • 2018-10-27
      • 2019-08-04
      • 2013-11-20
      • 2016-02-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多