如何在仅发布发布者的用户可以访问的NodeJ中创建待办事项列表?

时间:2019-04-03 00:05:09

标签: node.js mongodb express mongoose

几天来我一直在努力解决以下问题。 我有一个Web应用程序,需要登录后,用户才能创建学生列表。我正在尝试使列表仅对发布它的用户可见。 这是我到目前为止的工作。

students.controller.js

 const express = require('express');
    var router = express.Router();
    var bodyParser = require('body-parser')
   const mongoose = require('mongoose');
   const passport = require('passport');

   const Student = require('../models/student');
   const passportConfig = require('../config/passport');

   const app = express();


   router.get('/',passportConfig.isAuthenticated,(req, res) => {
    res.render('students');

   });

    router.post('/',(req, res) => {
    InsertRecord(req, res);

     });

     function InsertRecord(req, res){
    var student = new Student();
    student.fullName = req.body.fullname;
    student.phone = req.body.phone;
    student.save((err, doc) => {
        if (!err)
            res.redirect('students/list');
        else {
            console.log(' Error during insertion: '+ err);
        }
    });

}

router.get('/list',passportConfig.isAuthenticated, (req, res) => {
    Student.find((err, docs) => {
        if (!err) {
            res.render('list', {
                list:docs

            });
        }
        else {
            console.log('Error in retrieving students: '+ err);
        }
    });
});



module.exports = router;

模型架构Student.js

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


const studentSchema = new mongoose.Schema({
    fullName: {
        type: String
    },
    phone: {
        type: Number
    },
    author: {
      id: {
          type: mongoose.Schema.Types.ObjectId,
          ref: "User"
    },
   }

});

const Student = mongoose.model('Student', studentSchema);

module.exports = Student;


User.js架构

const bcrypt = require('bcrypt');
const crypto = require('crypto');
const mongoose = require('mongoose');
const Student = require('../models/student');


const userSchema = new mongoose.Schema({
  email: { type: String, unique: true },
  password: String,
  passwordResetToken: String,
  passwordResetExpires: Date,
  author: { 
    id: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User"
    }
  },

  snapchat: String,
  facebook: String,
  twitter: String,
  google: String,
  github: String,
  instagram: String,
  linkedin: String,
  steam: String,
  tokens: Array,

  profile: {
    name: String,
    gender: String,
    location: String,
    website: String,
    picture: String
  }
}, { timestamps: true });

/**
 * Password hash middleware.
 */
userSchema.pre('save', function save(next) {
  const user = this;
  if (!user.isModified('password')) { return next(); }
  bcrypt.genSalt(10, (err, salt) => {
    if (err) { return next(err); }
    bcrypt.hash(user.password, salt, (err, hash) => {
      if (err) { return next(err); }
      user.password = hash;
      next();
    });
  });
});

/**
 * Helper method for validating user's password.
 */
userSchema.methods.comparePassword = function comparePassword(candidatePassword, cb) {
  bcrypt.compare(candidatePassword, this.password, (err, isMatch) => {
    cb(err, isMatch);
  });
};

/**
 * Helper method for getting user's gravatar.
 */
userSchema.methods.gravatar = function gravatar(size) {
  if (!size) {
    size = 200;
  }
  if (!this.email) {
    return `https://gravatar.com/avatar/?s=${size}&d=retro`;
  }
  const md5 = crypto.createHash('md5').update(this.email).digest('hex');
  return `https://gravatar.com/avatar/${md5}?s=${size}&d=retro`;
};

const User = mongoose.model('User', userSchema);


module.exports = User;

请让我知道是否还有其他需要。

1 个答案:

答案 0 :(得分:0)

如何使用JWT

JWT是基于令牌的授权方式。您可以将用户的电子邮件或_id存储在jwt中。 用户登录后,服务器将提供用于存储用户电子邮件的jwt。当用户使用jwt请求列表时,您可以在jwt中找到具有用户_id的学生,例如student.findById({author: token.id})

您不必制作jwt模块,但是可以使用已经提供的jsonwebtoken