nodejs渐入佳境[32]-mongodb+express+auth middleware部署到h

发布时间:2020-07-01 00:14:37 作者:jonson_jackson
来源:网络 阅读:376

package.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
{
 "name": "node-todo-api",
 "version": "1.0.0",
 "description": "",
 "main": "index.js",
 "scripts": {
   "start": "node server/server.js",
   "test": "export NODE_ENV=test || SET NODE_ENV=test && mocha server/**/*.test.js",
   "test-watch": "nodemon --exec 'npm test'"
 },
 "engines": {
   "node": "6.2.2"
 },
 "author": "",
 "license": "ISC",
 "dependencies": {
   "bcryptjs": "^2.3.0",
   "body-parser": "^1.15.2",
   "crypto-js": "^3.1.6",
   "express": "^4.14.0",
   "jsonwebtoken": "^7.1.9",
   "lodash": "^4.15.0",
   "mongodb": "^2.2.5",
   "mongoose": "^4.5.9",
   "validator": "^5.6.0"
 },
 "devDependencies": {
   "expect": "^1.20.2",
   "mocha": "^3.0.2",
   "nodemon": "^1.10.2",
   "supertest": "^2.0.0"
 }
}

git

1
2
3
4
.gitignore里面的文件不会提交
git init
git add .
git commit -m "fitst commit"

heroku

安装heroku-cli 略…

1
2
3
4
heroku login  // 登陆账号密码
heroku create //创建分支
git push heroku master //提交到heroku管理的远程分支
hexoru open   //打开网址 得到:https://mighty-plateau-79112.herokuapp.com

studio 3T 连接mongoDB

heruku config

1
2
3
jacksondeMacBook-Pro:compaign jackson$ heroku config
=== mighty-plateau-79112 Config Vars
MONGODB_URI: mongodb://heroku_10kx7394:ij2q2p51lgsh0grsp2dq56mgu2@ds211694.mlab.com:11694/heroku_10kx7394

添加参数,连接远程mongoDB数据库

1
2
3
4
5
server: ds211694.mlab.com
port: 11694
authentication DB: heroku_10kx7394
Username: heroku_10kx7394
password: ij2q2p51lgsh0grsp2dq56mgu2

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
1、打开mongoDB > ./mongod -dbpath /Users/jackson/Downloads/mongodb-data
2、运行 >node postman.js
3、打开postman 选择post 输入 >https://mighty-plateau-79112.herokuapp.com/users  保存user
Body中填入:
{
"email": "zhuimengshaonian08@gmail.com",
"password" : "123abc!"
}
返回:
{
   "_id": "5c00a66978dd038d39dc4b89",
   "email": "zhuimengshaonian08@gmail.com"
}

header:
x-auth →eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1YmZlNzE2NTkxZTc4YzZhNGFkOGMxNjQiLCJhY2Nlc3MiOiJhdXRoIiwiaWF0IjoxNTQzNDAxODI5fQ.wOKNzkls_w_jA5YVkCo0r9gFZ4-KtD6GarRiCDpAPr8

4、 选择patch 输入 >https://mighty-plateau-79112.herokuapp.com/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
}

##源代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
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');
//app
var app = express();
const port = process.env.PORT || 3000;
//express middleware  Jonson对象与字符串转换。
app.use(bodyParser.json());

//
mongoose.Promise = global.Promise;
//连接mogodb
mongoose.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 middlewire

var 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 /users
app.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 route
app.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);
 })
});


//查询id
app.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
}

nodejs渐入佳境[32]-mongodb+express+auth middleware部署到h

推荐阅读:
  1. Horae开启区块链与Token经济时代的 认知革命
  2. Java如何编译和使用

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

区块链 前端 nodejs

上一篇:Cocos2d-x跨平台开发利器--EasyNDK-for-cocos2dx

下一篇:mysql主从复制实践之单数据库多实例

相关阅读

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

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