2

我已经在 Stackoverflow 上检查了多个答案,并且还阅读了文档,但我仍然无法弄清楚我的问题。当我尝试登录并注册时,它运行良好,我有我的令牌。只获取我的 current_user get('/isAuth') 是一场噩梦,我得到了 undefined !!!

const Authentication = require("../controllers/authentication");
const passport = require("passport");

const requireAuth = passport.authenticate('jwt', {session: false});
const requireSignin = passport.authenticate('local', {session: false});

module.exports = app => {
   app.post('/signup', Authentication.signup);
   app.post('/signin', requireSignin, Authentication.signin);

  //  Current User is undefined !!!!!
  app.get('/isAuth', Authentication.fetchUser);

我的护照.js

const keys = require("../config/keys");
const passport = require("passport");
const User = require("../models/User");
const JwtStrategy = require("passport-jwt").Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const localStrategy = require("passport-local");

// Create local strategy
const localOptions = { usernameField: "email" };
const localLogin = new localStrategy(localOptions, function(email,password,done) {
  // verify this username and password, call done with the user
  // if it is the correct username and password
  // otherwise, call done with false
  User.findOne({ email: email }, function(err, user) {
    if (err) {return done(err);}
    if (!user) {return done(null, false);}
    // compare passwords - is password is equal to user.password?
    user.comparePassword(password, function(err, isMatch) {
      if (err) {return done(err);}
      if (!isMatch) {return done(null, false);}
      return done(null, user);
    });
  });
});

// setup option for jwt Strategy
const jwtOptions = {
  jwtFromRequest: ExtractJwt.fromHeader('authorization'),
  secretOrKey: keys.secret
};

// Create Jwt strategy
const jwtLogin = new JwtStrategy(jwtOptions, function(payload, done) {
  // See if the user Id in the payload exists in our database
  // If does, call 'done' with that other
  // otherwise, call done without a user object
  User.findById(payload.sub, function(err, user) {
    if (err) {return done(err, false);}
    if (user) {
      done(null, user);
    } else {
      done(null, false);
    }
  });
});

// Tell passport to use this strategy
passport.use(jwtLogin);
passport.use(localLogin);

// Generate token
passport.serializeUser((user, done) => {
  done(null, user.id);
});

passport.deserializeUser((id, done) => {
  User.findById(id).then(user => {
    done(null, user);
  });
});

./controller/authentication.js

const User = require('../models/User');
const jwt = require('jwt-simple');
const config = require('../config/keys');

function tokenForUser(user){
    const timestamp = new Date().getTime();
    return jwt.encode({sub: user.id, iat: timestamp}, config.secret);
}
exports.signup = function(req,res,next){
    console.log(req.body)
    const email = req.body.email;
    const password = req.body.password;

    if(!email || !password){
        return res.status(422).send({error: 'You must provide email and password'});
    }
    // See if user with the given email exists
    User.findOne({email: email}, function(error, existingUser){
        if (error){return next(error)};
        // if a user with email does exist, return an error
        if (existingUser){
            return res.status(422).send({error: 'Email is in use'});
        }
        // if a user with email does not exist, create and save record
        const user = new User({
            email: email,
            password: password
        });

        user.save(function(error){
            if (error){return next(error);}
            // respond to request indicating the user was created
            res.json({token: tokenForUser(user)});
        })
    })
}

exports.signin = function (req,res,next){
    // user has already had their email and password auth
    // we just need to give them a token
    res.send({token: tokenForUser(req.user)});
}

// here is my problem...
exports.fetchUser = function (req, res, next) {
    console.log('this is ',req.user)
  };

仍然卡了很多天......这是一场噩梦!如果有人有解决方案。

登录后,如果我想去我的路线 /isAuth 检查我的用户数据: 在此处输入图像描述

4

1 回答 1

0

您是否尝试过使用调用isAuthenticatedreq 对象上的函数的中间件?此功能由添加passport并且通常是检查请求是否经过身份验证的推荐方法。

function isLoggedIn(req, res, next) {
  if (req.isAuthenticated()) {
    return next();
  }

  res.redirect("/");
}

然后,当用户到达您的isAuth路线时,您可以调用此函数:

app.get('/isAuth', isLoggedIn, Authentication.fetchUser);
于 2019-08-01T15:10:57.050 回答