Java Web Tokens
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

49 lines
1.1 KiB

require('dotenv').config()
const express = require ('express')
const app = express()
const jwt = require('jsonwebtoken')
app.use(express.json())
const posts = [
{
username: 'Reimu',
title: 'Post 1'
},
{
username: 'Marisa',
title: 'Post 2'
}
];
app.get('/posts', authenticateToken, (req, res) => {
res.json(posts.filter(post => post.username === req.user.name))
})
app.post('/login', (req, res) => {
//AUTH USER
const username = req.body.username
const user = { name: username }
const accessToken = jwt.sign(user, process.env.ACCESS_TOKEN_SECRET)
res.json({ accessToken: accessToken })
})
function authenticateToken(req, res, next){
const authHeader = req.headers['authorization']
const token = authHeader && authHeader.split(' ')[1]
if (token == null) return res.sendStatus(401)
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, user) => {
console.log(err)
if (err) return res.sendStatus(403)
//after the previous verifications, this should be a valid token
req.user = user
next()
})
}
app.listen(4000);