溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

nodejs漸入佳境[25]-express-middleware+mongoDB實現用戶權限驗證

發布時間:2020-04-02 18:18:56 來源:網絡 閱讀:311 作者:jonson_jackson 欄目:開發技術

查找token

查找數據庫Token是否存在

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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'
 });
};

auth-middleware

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//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();
 });
};

url

1
2
3
app.get('/users/me', authenticate, (req, res) => {
 res.send(req.user);
});

完整代碼

postman.js

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
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');
//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
   }
});





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.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'
 });
};


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.get('/users/me', authenticate, (req, res) => {
 res.send(req.user);
});



//express route
app.post('/todos',(req,res)=>{
//  console.log(req.body);

   //建立對象document
   var todo = new Todo({
       text:req.body.text
   });
   //保存
     todo.save().then((doc)=>{
     res.send(doc);
   },(e)=>{
       res.status(400).send(e);
   });

})
//獲取所有屬性

app.get('/todos', (req, res) => {
 Todo.find().then((todos) => {
   res.send({todos});
 }, (e) => {
   res.status(400).send(e);
 })
});


//查詢id
app.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();
 })
});


// 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);
 })
});

//監聽
app.listen(port,()=>{
   console.log(`Start on port ${port}`);
});
module.exports = {
  app,
  Todo
}

測試

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
1、打開mongoDB > ./mongod -dbpath /Users/jackson/Downloads/mongodb-data
2、運行 >node postman.js
3、打開postman 選擇post 輸入 >localhost:3000/users
Body中填入:
{
"email": "zhuimengshaonian07@gmail.com",
"password" : "123abc!"
}
返回:
{
   "_id": "5bfe716591e78c6a4ad8c164",
   "email": "zhuimengshaonian07@gmail.com"
}

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

4、localhost:3000/users/me
增加header:
x-auth →eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1YmZlNzE2NTkxZTc4YzZhNGFkOGMxNjQiLCJhY2Nlc3MiOiJhdXRoIiwiaWF0IjoxNTQzNDAxODI5fQ.wOKNzkls_w_jA5YVkCo0r9gFZ4-KtD6GarRiCDpAPr8

查詢后返回:
{
   "_id": "5bfe716591e78c6a4ad8c164",
   "email": "zhuimengshaonian07@gmail.com"
}
  • 本文鏈接: https://dreamerjonson.com/2018/11/29/node-25-auth-middleware/

  • 版權聲明: 本博客所有文章除特別聲明外,均采用 CC BY 4.0 CN協議 許可協議。轉載請注明出處!

nodejs漸入佳境[25]-express-middleware+mongoDB實現用戶權限驗證

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女