-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathindex.js
More file actions
73 lines (57 loc) · 1.49 KB
/
index.js
File metadata and controls
73 lines (57 loc) · 1.49 KB
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
import './setup/db'
import { server } from './setup/server'
import * as jwt from './setup/jwt'
import { UserModel } from './models/user'
const authMiddleware = async (req, res, next) => {
const [, token] = req.headers.authorization.split(' ')
console.log(req.headers.authorization)
try {
const payload = await jwt.verify(token)
const user = await UserModel.findById(payload.user)
if (!user) {
return res.send(401)
}
req.auth = user
next()
} catch (error) {
res.send(401, error)
}
}
server.post('/signup', async (req, res) => {
try {
const result = await UserModel.create(req.body)
const { password, ...user } = result.toObject()
const token = jwt.sign({ user: user.id })
res.send({ user, token })
} catch (error) {
res.send(400, error)
}
})
server.get('/login', async (req, res) => {
const [, hash] = req.headers.authorization.split(' ')
const [email, password] = Buffer.from(hash, 'base64')
.toString()
.split(':')
try {
const user = await UserModel.findOne({ email, password })
if (!user) {
return res.send(401)
}
const token = jwt.sign({ user: user.id })
res.send({ user, token })
} catch (error) {
res.send(error)
}
})
server.get('/users', authMiddleware, async (req, res) => {
try {
const users = await UserModel.find()
res.send(users)
} catch (error) {
res.send(error)
}
})
server.get('/me', authMiddleware, (req, res) => {
res.send(req.auth)
})
server.start()