This repository has been archived by the owner on Feb 9, 2022. It is now read-only.
/
token.js
113 lines (85 loc) · 1.85 KB
/
token.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
import koaRouter from 'koa-router'
import jwt from 'koa-jwt'
import User from '../../models/user'
import { log } from '../../utils'
const router = koaRouter()
router.post('/token-auth', function *(next) {
const body = this.request.body
if (!body.username || !body.password) {
this.status = 400
this.body = {
error: 'User and/or password empty'
}
return
}
const query = User.where({ _id: body.username })
let user = false
try {
user = yield query.findOne()
} catch (err) {
log('Couldn\'t load user', err)
}
if (!user) {
this.status = 400
this.body = {
error: 'User doesn\'t exist'
}
return
}
// Compare password with the one within the DB
const isMatch = user.tryPassword(body.password)
if (isMatch) {
const token = jwt.sign(body, process.env.SESSION_SECRET, {
expiresIn: 300
})
this.body = {
token
}
return
}
this.status = 400
this.body = {
error: 'Wrong password'
}
yield next
})
router.post('/token-refresh', function *(next) {
const token = this.request.body.token
let decoded = false
try {
decoded = jwt.verify(token, process.env.SESSION_SECRET)
} catch (err) {
this.status = 401
this.body = { error: err }
return
}
const query = User.where({ _id: decoded.username })
let user = false
try {
user = yield query.findOne()
} catch (err) {
log('Couldn\'t load user', err)
}
if (!user) {
this.status = 401
this.body = {
error: 'User doesn\'t exist'
}
return
}
const isMatch = user.tryPassword(decoded.password)
if (isMatch) {
this.body = {
token: jwt.sign(decoded, process.env.SESSION_SECRET, {
expiresIn: 300
})
}
return
}
this.status = 401
this.body = {
error: 'Wrong password'
}
yield next
})
module.exports = router