如何使用Node.js在会话中使用记录的用户的电子邮件发布数据

时间:2018-10-06 20:19:29

标签: node.js angular express mean-stack

我正在使用带有Angular 6的MEAN堆栈开发Web应用程序。在那里,我有一个表单来提交“ height value”。我想将其与登录用户的电子邮件一起提交。我为用户提供了一个单独的架构。以下是我的身高模式。

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;

// Schema for height panel
var heightSchema = new mongoose.Schema({
userName: {
        type: Schema.ObjectId,
         ref: 'user'
    },
    height: {
        type: Number
    },
});

module.exports = mongoose.model('heightValue', heightSchema);

以下是我的发布路线。

    //post height values
router.post("/save", function (req, res) {
    var mod = new height(req.body,{userName : req.body["user.email"]});
    height.findOneAndUpdate(
        {
            userName: req.user.email,
            height: req.body.height,
        },
        req.body,
        { upsert: true, new: true },
        function (err, data) {
            if (err) {
                console.log(err);
                res.send(err);
            } else {
                console.log(res);
                res.send(mod);
            }
        }
    );
});

我尝试过的

我尝试过了。

userName: req.user.email,

但是我无法获取登录用户的用户ID。响应显示“输入意外结束”错误。我怎样才能达到我的要求。 在尝试了许多方法之后,最终更新了路由和架构。但是问题仍然是一样的。谁能确定我哪里出了问题?

-更新-

我在这里返回令牌。

passport.use('login', new localStrategy({
     usernameField : 'email',
     passwordField : 'password'
   }, async (email, password, done) => {
     try {

       //Find the user associated with the email provided by the user
       const user = await UserModel.findOne({ email });

       if( !user || user.status === false){
         //If the user isn't found in the database, return a message
         return done(null, false, { message : 'User not found'});
       }
       //Validate password and make sure it matches with the corresponding hash stored in the database
       //If the passwords match, it returns a value of true.
       const validate = await user.isValidPassword(password);
       if( !validate ){
         return done(null, false, { message : 'Wrong Password'});
       }
       //Send the user information to the next middleware
       return done(null, user, { message : 'Logged in Successfully'});
     } catch (error) {
       return done(error);
     }
   }));


passport.use(new JWTstrategy({
      //secret we used to sign our JWT
      secretOrKey : 'top_secret',
      //we expect the user to send the token as a query paramater with the name 'secret_token'
      jwtFromRequest : ExtractJWT.fromUrlQueryParameter('secret_token')
    }, async (token, done) => {
      try {
        //Pass the user details to the next middleware
        return done(null, token.user);
      } catch (error) {
        done(error);
      }
    }));


class Service
{

    constructor()
    {

    }

    /**
     * 
     * @param {type} req
     * @param {type} res
     * @param {type} next
     * @returns {undefined}
     *  Authenticate functionality.
     */
    async authenticate(req,res,next)
    {               
        passport.authenticate('login', async (err, user, info) => {
        try {
          if(err || !user){
            const error = new Error('An Error occured');        
            return next(error);
            } 

            req.login(user, { session : false }, async (error) => {
            if( error ) return next(error);  
             const token = this.getJWT(user);

            return res.json({ token });
          });   
        } catch (error) {
          return next(error);
        }
        })(req, res, next);
    }    

    /**
     * 
     * @param {type} user
     * @returns {Service.getJWT.token}
     * Create JWT token.
     */
    getJWT(user)
    {
        //We don't want to store the sensitive information such as the
        //user password in the token so we pick only the email and first name 
        const body = { email : user.email , firstName : user.firstName};
        // Token will be expired in 24 hours.
        const token = jwt.sign({ user : body },'top_secret',
        {
            expiresIn : '24h'
        }); 
        return token;
    }
}

module.exports = Service;

0 个答案:

没有答案