-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
69 lines (57 loc) · 1.67 KB
/
index.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
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const port = process.env.PORT || 3000
const headers = [
">,MqBuN?$uS&+v:|t/2Yesgt4JJC,@",
"mv{MBiZJc0TJ|C()c(xlD[s$Q,~f)B",
"xPDVUk!Ib@l[a]r%T~~%iL#C`>,4-A",
"y^D(*Rj?a(-D33G#rZM9K@asTW3V={"
]
const names = []
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }))
// parse application/json
app.use(bodyParser.json())
const authMiddleware = (req, res, next) => {
const header = req.header('Authorization')
if (header && headers.includes(header)) {
return next()
}
res.status(401)
res.json({ error: 'Invalid Authorization header. You can get one at /random_header' })
}
app.use((req, res, next) => {
console.log(`${req.method} @ ${req.path}`)
next()
})
app.get('/random_header', (req, res) => {
const header = headers[Math.floor(Math.random() * headers.length)]
res.send(`Hello paw student. Your Authorization header is: ${header}`)
})
app.post('/name', [authMiddleware], (req, res) => {
if (!req.body || !req.body.name) {
res.status(400)
res.json({ error: '"name" param missing' })
} else {
names.push(req.body.name)
res.status(200)
res.json({ message: `Position ${names.length}` })
}
})
app.get('/names', (req, res, next) => {
if (req.header('paw-secret') != process.env.SECRET) {
next()
} else {
res.status(200)
res.json({ names })
}
})
app.use((req, res) => {
res.status(404)
res.json({ message: 'Nothing here!' })
})
app.listen(port, () => {
console.log(`PAW CURL exercise listening at port: ${port}.`)
console.log('We expect students to POST their names at /name')
})