Skip to content

Commit

Permalink
jwt auth (#4)
Browse files Browse the repository at this point in the history
Co-authored-by: Rogeh Beshay <[email protected]>
  • Loading branch information
RogehBeshay and Rogeh Beshay authored Oct 30, 2024
1 parent d621c6b commit ae4a287
Show file tree
Hide file tree
Showing 3 changed files with 160 additions and 42 deletions.
165 changes: 123 additions & 42 deletions server/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"express": "^4.21.1",
"express-fileupload": "^1.5.1",
"express-validator": "^7.2.0",
"jsonwebtoken": "^9.0.2",
"mongodb": "^6.9.0",
"multer": "^1.4.5-lts.1",
"multer-s3": "^3.0.1",
Expand Down
36 changes: 36 additions & 0 deletions server/routes/auth.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,29 @@
const bcrypt = require("bcryptjs");
const { body, validationResult } = require("express-validator");
const { getUserByEmail, createUser } = require("../models/userModel");
const jwt = require("jsonwebtoken");
const jwtSecret = process.env.JWT_SECRET;

module.exports = (app, client) => {
const database = client.db("UserInfo");
const users = database.collection("users");

const auth = (req, res, next) => {
const token = req.header("Authorization")?.split(" ")[1];

if (!token) {
return res.status(401).json({ msg: "No token, authorization denied" });
}

try {
const decoded = jwt.verify(token, jwtSecret);
req.user = decoded.user;
next();
} catch (err) {
res.status(401).json({ msg: "Token is not valid" });
}
};

// Register route
app.post(
"/api/register",
Expand Down Expand Up @@ -79,7 +97,25 @@ module.exports = (app, client) => {
return res.status(400).json({ msg: "Invalid credentials" });
}

const payload = {
user: {
id: user._id,
email: user.email,
},
};

jwt.sign(
payload,
jwtSecret,
{ expiresIn: "1h" },
(err, token) => {
if (err) throw err;
res.status(200).json({ token });
}
);

res.status(200).json({ msg: "Logged in successfully" });

} catch (error) {
console.error(error);
res.status(500).send("Server error");
Expand Down

0 comments on commit ae4a287

Please sign in to comment.