温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

nodejs渐入佳境[31]-mongodb+express+middleware绑定用户权限2

发布时间:2020-07-08 21:58:08 阅读:196 作者:jonson_jackson 栏目:开发技术
GO开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

继续绑定用户权限,要执行操作必须要有token

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
var mongoose = require('mongoose');var express = require('express');var bodyParser = require('body-parser');const {ObjectID} = require('mongodb');var _ = require('lodash');const validator = require('validator');const jwt = require('jsonwebtoken');const bcrypt = require('bcryptjs');//appvar app = express();const port = process.env.PORT || 3000;//express middleware  Jonson对象与字符串转换。app.use(bodyParser.json());//mongoose.Promise = global.Promise;//连接mogodbmongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/TodoApp');//模版var Todo = mongoose.model('Todo',{    text:{      type:String,  //类型      required:true, //必须要有      minlength:1, //最小长度      trim:true   //去除空格    },    completed:{      type:Boolean,      default:false  //默认值    },    completedAt:{      type:Number,      default:null    },    _creator: {      type: mongoose.Schema.Types.ObjectId,      required: true    }});var UserSchema = new mongoose.Schema({  email: {    type: String,    required: true,    trim: true,    minlength: 1,    unique: true,    validate: {      validator: validator.isEmail,      message: '{VALUE} is not a valid email'    }  },  password: {    type: String,    require: true,    minlength: 6  },  tokens: [{    access: {      type: String,      required: true    },    token: {      type: String,      required: true    }  }]});UserSchema.methods.toJSON = function () {  var user = this;  var userObject = user.toObject();  return _.pick(userObject, ['_id', 'email']);};UserSchema.methods.generateAuthToken = function () {  var user = this;  var access = 'auth';  var token = jwt.sign({_id: user._id.toHexString(), access}, 'abc123').toString();  user.tokens = user.tokens.concat([{access,token}]);  return user.save().then(() => {    return token;  //返回token  });};UserSchema.methods.removeToken = function (token) {  var user = this;  return user.update({    $pull: {      tokens: {token}    }  });};UserSchema.statics.findByToken = function (token) {  var User = this;  var decoded;  try {    decoded = jwt.verify(token, 'abc123');  } catch (e) {    return Promise.reject();  }  return User.findOne({    '_id': decoded._id,    'tokens.token': token,    'tokens.access': 'auth'  });};UserSchema.statics.findByCredentials = function (email, password) {  var User = this;  return User.findOne({email}).then((user) => {    if (!user) {      return Promise.reject();    }    return new Promise((resolve, reject) => {      // Use bcrypt.compare to compare password and user.password      bcrypt.compare(password, user.password, (err, res) => {        if (res) {          resolve(user);        } else {          reject();        }      });    });  });};//在保存之前执行操作。UserSchema.pre('save', function (next) {  var user = this;//保存时对于密码的更新  if (user.isModified('password')) {    bcrypt.genSalt(10, (err, salt) => {      //密码变为了hash      bcrypt.hash(user.password, salt, (err, hash) => {        user.password = hash;        next();      });    });  } else {    next();  }});var User = mongoose.model('User', UserSchema);//auth middlewirevar authenticate = (req, res, next) => {  var token = req.header('x-auth');  User.findByToken(token).then((user) => {    if (!user) {      return Promise.reject();    }    req.user = user;    req.token = token;    next();  }).catch((e) => {    res.status(401).send();  });};app.delete('/users/me/token', authenticate, (req, res) => {  req.user.removeToken(req.token).then(() => {    res.status(200).send();  }, () => {    res.status(400).send();  });});app.get('/users/me', authenticate, (req, res) => {  res.send(req.user);});// POST /users/login {email, password}app.post('/users/login', (req, res) => {  var body = _.pick(req.body, ['email', 'password']);  User.findByCredentials(body.email, body.password).then((user) => {    return user.generateAuthToken().then((token) => {      res.header('x-auth', token).send(user);    });  }).catch((e) => {    res.status(400).send();  });});// POST /usersapp.post('/users', (req, res) => {  var body = _.pick(req.body, ['email', 'password']);  var user = new User(body);  user.save().then(() => {    return user.generateAuthToken(); //调用方法,产生auth token并保存。  }).then((token) => {    res.header('x-auth', token).send(user); //设置了响应头  }).catch((e) => {    res.status(400).send(e);  })});//express routeapp.post('/todos',authenticate,(req,res)=>{//  console.log(req.body);    //建立对象document    var todo = new Todo({        text:req.body.text,        _creator:req.user._id    });    //保存      todo.save().then((doc)=>{      res.send(doc);    },(e)=>{        res.status(400).send(e);    });})//获取所有属性app.get('/todos', authenticate,(req, res) => {  Todo.find({      _creator:req.user._id  }).then((todos) => {    res.send({todos});  }, (e) => {    res.status(400).send(e);  })});//查询idapp.get('/todos/:id', authenticate,(req, res) => {  var id = req.params.id;  if (!ObjectID.isValid(id)) {    return res.status(404).send();  }  Todo.findOne({    _id:id,    _creator:req.user._id  }).then((todo) => {    if (!todo) {      return res.status(404).send();    }    res.send({todo});  }).catch((e) => {    res.status(400).send();  });});//删除app.delete('/todos/:id',  authenticate,(req, res) => {  var id = req.params.id;  if (!ObjectID.isValid(id)) {    return res.status(404).send();  }  Todo.findOneAndRemove({    _id: id,  _creator: req.user._id  }).then((todo) => {    if (!todo) {      return res.status(404).send();    }    res.send({todo});  }).catch((e) => {    res.status(400).send();  });});//更新app.patch('/todos/:id',authenticate, (req, res) => {  var id = req.params.id;  var body = _.pick(req.body, ['text', 'completed']);  if (!ObjectID.isValid(id)) {    return res.status(404).send();  }  if (_.isBoolean(body.completed) && body.completed) {    body.completedAt = new Date().getTime();  } else {    body.completed = false;    body.completedAt = null;  }  Todo.findOneAndUpdate({_id: id, _creator: req.user._id}, {$set: body}, {new: true}).then((todo) => {    if (!todo) {      return res.status(404).send();    }    res.send({todo});  }).catch((e) => {    res.status(400).send();  })});//监听app.listen(port,()=>{    console.log(`Start on port ${port}`);});module.exports = {   app,   Todo}

测试

1234567891011121314151617181920212223242526272829303132333435363738
1、打开mongoDB > ./mongod -dbpath /Users/jackson/Downloads/mongodb-data2、运行 >node postman.js3、打开postman 选择post 输入 >localhost:3000/users  保存userBody中填入:{	"email": "zhuimengshaonian08@gmail.com",	"password" : "123abc!"}返回:{    "_id": "5c00a66978dd038d39dc4b89",    "email": "zhuimengshaonian08@gmail.com"}header:x-auth →eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1YmZlNzE2NTkxZTc4YzZhNGFkOGMxNjQiLCJhY2Nlc3MiOiJhdXRoIiwiaWF0IjoxNTQzNDAxODI5fQ.wOKNzkls_w_jA5YVkCo0r9gFZ4-KtD6GarRiCDpAPr84、 选择patch 输入 >localhost:3000/todos/5c00a66978dd038d39dc4b89  准备修改Body中填入:{	"text": "zhuimengshaonian09@gmail.com",}header附带返回:x-auth →eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1YmZlNzE2NTkxZTc4YzZhNGFkOGMxNjQiLCJhY2Nlc3MiOiJhdXRoIiwiaWF0IjoxNTQzNDAxODI5fQ.wOKNzkls_w_jA5YVkCo0r9gFZ4-KtD6GarRiCDpAPr8返回:{    "completed": false,    "completedAt": null,    "_id": "5c00a66978dd038d39dc4b89",    "text": "zhuimengshaonian09@gmail.com",    "_creator": "5c00a58c78dd038d39dc4b87",    "__v": 0}
  • 本文链接: https://dreamerjonson.com/2018/12/01/node-31-bind-user-auth3/

  • 版权声明: 本博客所有文章除特别声明外,均采用 CC BY 4.0 CN协议 许可协议。转载请注明出处!

nodejs渐入佳境[31]-mongodb+express+middleware绑定用户权限2

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI

开发者交流群×