增加_creator,将用户绑定起来
123456789101112131415161718192021 | //模版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 }}); |
添加权限控制并且存储了用户的id。
用户访问/todos 必须要有authenticate这个middleware。通过以后,说明用户是可信的。就可以保存todo到数据库中。并且将todo与创建的用户链接在了一起
12345678910111213141516171819202122232425262728 | //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); })}); |
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346 | 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', (req, res) => { var id = req.params.id; if (!ObjectID.isValid(id)) { return res.status(404).send(); } Todo.findById(id).then((todo) => { if (!todo) { return res.status(404).send(); } res.send({todo}); }).catch((e) => { res.status(400).send(); });});//删除app.delete('/todos/:id', (req, res) => { var id = req.params.id; if (!ObjectID.isValid(id)) { return res.status(404).send(); } Todo.findByIdAndRemove(id).then((todo) => { if (!todo) { return res.status(404).send(); } res.send({todo}); }).catch((e) => { res.status(400).send(); });});//更新app.patch('/todos/:id', (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.findByIdAndUpdate(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} |
12345678910111213141516171819202122232425262728293031323334353637 | 1、打开mongoDB > ./mongod -dbpath /Users/jackson/Downloads/mongodb-data2、运行 >node postman.js3、打开postman 选择post 输入 >localhost:3000/users 保存userBody中填入:{ "email": "zhuimengshaonian07@gmail.com", "password" : "123abc!"}返回:{ "_id": "5bfe716591e78c6a4ad8c164", "email": "zhuimengshaonian07@gmail.com"}header:x-auth →eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1YmZlNzE2NTkxZTc4YzZhNGFkOGMxNjQiLCJhY2Nlc3MiOiJhdXRoIiwiaWF0IjoxNTQzNDAxODI5fQ.wOKNzkls_w_jA5YVkCo0r9gFZ4-KtD6GarRiCDpAPr84、 选择post 输入 >localhost:3000/todosBody中填入:{ "text": "zhuimengshaonian07@gmail.com",}header附带返回:x-auth →eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1YmZlNzE2NTkxZTc4YzZhNGFkOGMxNjQiLCJhY2Nlc3MiOiJhdXRoIiwiaWF0IjoxNTQzNDAxODI5fQ.wOKNzkls_w_jA5YVkCo0r9gFZ4-KtD6GarRiCDpAPr8返回:{ "completed": false, "completedAt": null, "_id": "5c00a66978dd038d39dc4b89", "text": "zhuimengshaonian07@gmail.com", "_creator": "5c00a58c78dd038d39dc4b87", "__v": 0} |
本文链接: https://dreamerjonson.com/2018/11/30/node-30-bind-user-auth/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY 4.0 CN协议 许可协议。转载请注明出处!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。