Browse Source

Personal working JWT from zero

master
okasion 2 years ago
parent
commit
b6b986aff5
  1. 49
      server.js

49
server.js

@ -0,0 +1,49 @@
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);
Loading…
Cancel
Save