From b6b986aff5fd4a049bc309162c1d572ce3e56d57 Mon Sep 17 00:00:00 2001 From: okasion Date: Mon, 29 Aug 2022 06:18:56 -0400 Subject: [PATCH] Personal working JWT from zero --- server.js | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 server.js diff --git a/server.js b/server.js new file mode 100644 index 0000000..5a74b0d --- /dev/null +++ b/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); \ No newline at end of file