-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
36 lines (28 loc) · 845 Bytes
/
server.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
require('dotenv').config()
const express = require('express')
const app = express()
const jwt = require('jsonwebtoken')
const posts = [
{
username: 'Kyle',
title: 'Post 1'
},{
username: 'Jim',
title: 'Post 2'
}
]
app.use(express.json())
app.get('/posts', authenticateToken, (req, res) => {
res.json(posts.filter(post => post.username === req.user.name))
})
function authenticateToken(req, res, next) {
const authHeader = req.headers['authorization']
const token = authHeader && authHeader.split(' ')[1]
if (token == null) return res.sendStatus(401) //No token
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, user) => {
if (err) return res.sendStatus(403) //Has token but no longer has access
req.user = user
next()
})
}
app.listen(3000)