Skip to content

Commit

Permalink
change now server
Browse files Browse the repository at this point in the history
  • Loading branch information
Hanieh-Sadeghi committed Oct 27, 2023
1 parent 435e0e5 commit 670969f
Showing 1 changed file with 27 additions and 30 deletions.
57 changes: 27 additions & 30 deletions server/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -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}`);
Expand Down

0 comments on commit 670969f

Please sign in to comment.