From 670969fe03560074ba4ab0d3d4644717e57f44f9 Mon Sep 17 00:00:00 2001 From: Hanieh-Sadeghi Date: Fri, 27 Oct 2023 17:56:59 +0330 Subject: [PATCH] change now server --- server/server.js | 57 +++++++++++++++++++++++------------------------- 1 file changed, 27 insertions(+), 30 deletions(-) diff --git a/server/server.js b/server/server.js index 1ce6425..e5295a4 100644 --- a/server/server.js +++ b/server/server.js @@ -12,40 +12,37 @@ app.use(express.static(path.join(__dirname, "../client"))); app.use(bodyParser.urlencoded({ extended: false })); // app.use(bodyParser.json) -const users = []; -const bcrypt = require("bcrypt"); -app.get("/users", (req, res) => { - res.json(users); -}); +const jwt = require('jsonwebtoken') +app.use(express.json()) -app.post("/users", async (req, res) => { - try { - // const salt = await bcrypt.genSalt(); - const hashedPassword = await bcrypt.hash(req.body.password.salt); - const user = { name: req.body.name, password: req.body.password }; - users.push(user); - res.status(201).send(); - } catch { - res.status(500).send(); +const posts = [ + { + username: 'Kyle', + title: 'Post 1' + }, + { + username: 'Jim', + title: 'Post 2' } -}); +] -app.post("/users/login", async (req, res) => { - const user = users.find((user) => (user.name = req.body.name)); - if (user == null) { - return res.status(400).send("Cannot find user"); - } - try { - if (await bcrypt.compare(req.body.password, user.password)) { - res.send("Success"); - } else { - res.send("Not Allowed"); - } - } catch { - res.status(500).send(); - } -}); +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) + + jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, user) => { + console.log(err) + if (err) return res.sendStatus(403) + req.user = user + next() + }) +} app.listen(3000, () => { console.log(`listening pn port ${PORT}`);