-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.js
44 lines (40 loc) · 1.05 KB
/
auth.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
const jsonwebtoken = require('jsonwebtoken')
const secretkey = 'yabbykey'
const dbOperations = require('./db.js')
// 生成 token
const sign = function (data = {}) {
return jsonwebtoken.sign(data, secretkey, {
expiresIn: 60 * 60 * 24 * 107,
})
}
const verify = (req, res, next) => {
let authorization = req.headers.authorization || ''
let token = ''
if (authorization.includes('Bearer')) {
token = authorization.replace('Bearer ', '')
} else {
next()
}
jsonwebtoken.verify(token, secretkey, async (error, data) => {
if (error) {
res.status(403).send({ error: 1, msg: '请先登录', data: null })
} else {
try {
const result = await dbOperations.findUserByMail(data.mail)
if (!result) {
res.status(401).send({ error: 1, msg: '请先登录', data: null })
return
}
req._id = result._id
} catch (error) {
res.status(401).send({ error: 1, msg: '请先登录', data: null })
return
}
next()
}
})
}
module.exports = {
sign,
verify,
}