Skip to content

Commit

Permalink
Add
Browse files Browse the repository at this point in the history
JWT-Cookies-RefreshToken
  • Loading branch information
OKK53 committed Feb 24, 2023
1 parent f965b90 commit 51ab809
Show file tree
Hide file tree
Showing 8 changed files with 140 additions and 34 deletions.
57 changes: 54 additions & 3 deletions api/routes/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const verify = require("../utils/verifyToken");

//REGISTERs
//REGISTER
router.post("/register", async (req, res) => {
try {
const userExist = await User.findOne({ email: req.body.email });
Expand Down Expand Up @@ -39,32 +39,83 @@ router.post("/login", async (req, res) => {
const accessToken = jwt.sign(
{ id: user._id, username: user.username },
process.env.MY_SECRET_KEY,
{ expiresIn: "30d" }
{ expiresIn: "30s" }
);

const refreshToken = jwt.sign(
{ id: user._id, username: user.username },
process.env.MY_SECRET_REFRESH
);

if (req.cookies["accessToken"]) {
req.cookies["accessToken"] = "";
}
if (req.cookies["refreshToken"]) {
req.cookies["refreshToken"] = "";
}

const { password, ...others } = user._doc;
res
.cookie("accessToken", accessToken, {
httpOnly: true,
})
.cookie("refreshToken", refreshToken, {
httpOnly: true,
})
.status(200)
.json(others);
} catch (err) {
res.status(500).json(err);
}
});

//REFRESH
router.get("/refresh", async (req, res, next) => {
const prevToken = req.cookies.refreshToken;
if (prevToken) {
jwt.verify(prevToken, process.env.MY_SECRET_REFRESH, (err, user) => {
if (err) res.status(403).json("Token is not valid!");
res.clearCookie("accessToken");
res.clearCookie("refreshToken");

const newaccesstoken = jwt.sign(
{ id: user._id, username: user.username },
process.env.MY_SECRET_KEY,
{ expiresIn: "30s" } //30 seconds
);
console.log("Regenerated accessToken\n", newaccesstoken);
const newrefreshToken = jwt.sign(
{ id: user._id, username: user.username },
process.env.MY_SECRET_REFRESH
);
console.log("Regenerated refreshToken\n", newrefreshToken);
console.log("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\n");

res.cookie("accessToken", newaccesstoken, {
expires: new Date(Date.now() + 1000 * 30), // 30 seconds
httpOnly: true,
});
res
.cookie("refreshToken", newrefreshToken, {
httpOnly: true,
})
.sendStatus(200);
req.user = user;
next();
});
} else {
return res.status(401).json("You are not authenticated!");
}
});

//LOGOUT
router.post("/logout", verify, async (req, res) => {
const token = req.cookies.accessToken;
if (token) {
jwt.verify(token, process.env.MY_SECRET_KEY, (err, user) => {
if (err) return res.status(403).json("Token is not valid!");
res.clearCookie("accessToken");
req.cookies["accessToken"] = "";
res.clearCookie("refreshToken");
return res.status(200).json("Successfully Logged Out.");
});
} else {
Expand Down
40 changes: 40 additions & 0 deletions api/utils/verifyRefreshToken.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
const jwt = require("jsonwebtoken");

function verifyRefreshToken(req, res, next) {
const prevToken = req.cookies.refreshToken;
if (prevToken) {
jwt.verify(prevToken, process.env.MY_SECRET_REFRESH, (err, user) => {
if (err) res.status(403).json("Token is not valid!");
res.clearCookie("accessToken");
res.clearCookie("refreshToken");

const newaccesstoken = jwt.sign(
{ id: user._id, username: user.username },
process.env.MY_SECRET_KEY,
{ expiresIn: "30s" } // 30 seconds
);
console.log("Regenerated accessToken\n", newaccesstoken);
const newrefreshToken = jwt.sign(
{ id: user._id, username: user.username },
process.env.MY_SECRET_REFRESH
);
console.log("Regenerated refreshToken\n", newrefreshToken);

res.cookie("accessToken", newaccesstoken, {
expires: new Date(Date.now() + 1000 * 30), // 30 seconds
httpOnly: true,
});
res
.cookie("refreshToken", newrefreshToken, {
httpOnly: true,
})
.sendStatus(200);
req.user = user;
next();
});
} else {
return res.status(401).json("You are not authenticated!");
}
}

module.exports = verifyRefreshToken;
5 changes: 4 additions & 1 deletion api/utils/verifyToken.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@ function verify(req, res, next) {
const token = req.cookies.accessToken;
if (token) {
jwt.verify(token, process.env.MY_SECRET_KEY, (err, user) => {
if (err) res.status(403).json("Token is not valid!");
if (err) {
res.status(403).json("Token is not valid!");
console.log("hataburada1");
}
req.user = user;
next();
});
Expand Down
18 changes: 0 additions & 18 deletions api/verifyToken.js

This file was deleted.

27 changes: 26 additions & 1 deletion client/src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,37 @@ import Contact from "pages/Contact";
import Single from "pages/Single";
import Page404 from "pages/Page404";
import { Routes, Route } from "react-router-dom";
import { useContext } from "react";
import { useContext, useEffect } from "react";
import { Context } from "context/AuthContext";
import axios from "axios";

function App() {
const { user } = useContext(Context);

const credentials = {
withCredentials: true,
};

const refreshToken = async () => {
try {
await axios.get("/auth/refresh", credentials);
} catch (err) {
console.log(err);
}
};

useEffect(() => {
if (user) {
const interval = setInterval(() => {
refreshToken();
}, 1000 * 29);

return () => {
clearInterval(interval);
};
}
});

return (
<>
<Topbar />
Expand Down
8 changes: 4 additions & 4 deletions client/src/components/SinglePost.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,6 @@ export default function SinglePost() {
const [desc, setDesc] = useState("");
const [updateMode, setUpdateMode] = useState(false);

const credentials = {
withCredentials: true,
};

useEffect(() => {
const getPost = async () => {
const res = await axios.get("/posts/" + path);
Expand All @@ -30,6 +26,10 @@ export default function SinglePost() {
getPost();
}, [path]);

const credentials = {
withCredentials: true,
};

const handleDelete = async () => {
try {
await axios.delete(`/posts/${post._id}`, credentials);
Expand Down
1 change: 1 addition & 0 deletions client/src/pages/Settings.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export default function Settings() {
const credentials = {
withCredentials: true,
};

const handleSubmit = async (e) => {
e.preventDefault();
dispatch({ type: "UPDATE_START" });
Expand Down
18 changes: 11 additions & 7 deletions client/src/pages/Write.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ export default function Write() {
const [file, setFile] = useState(null);
const { user } = useContext(Context);

const credentials = {
withCredentials: true,
};

const handleSubmit = async (e) => {
e.preventDefault();
const newPost = {
Expand All @@ -29,15 +33,15 @@ export default function Write() {
} catch (err) {}
}
try {
const res = await axios.post("/posts", newPost, {
headers: {
token:
"Bearer " + JSON.parse(localStorage.getItem("user")).accessToken,
},
});
const res = await axios.post("/posts", newPost, credentials);
console.log("bug1");
window.location.replace("/post/" + res.data._id);
} catch (err) {}
console.log("bug2");
} catch (err) {
console.log(err);
}
};

return (
<div className="pt-12">
<Helmet>
Expand Down

0 comments on commit 51ab809

Please sign in to comment.