fixed cors issues

updated token verification middleware
reworked blog post POST controller username acquisition
This commit is contained in:
ak 2023-09-30 12:57:31 -07:00
parent 8e1f4a2b08
commit 73ca135cc3
4 changed files with 23 additions and 13 deletions

13
app.js
View file

@ -37,7 +37,18 @@ app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, "public")));
// cors
app.use(cors());
app.use(
cors({
origin: true,
credentials: true,
methods: ["GET", "PUT", "POST"],
allowedHeaders: [
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept",
],
preflightContinue: true,
})
);
// routing
app.use("/", indexRouter);

View file

@ -16,6 +16,8 @@ exports.post = asyncHandler(async (req, res, next) => {
return res
.cookie("JWT_TOKEN", token, {
httpOnly: true,
sameSite: "none",
secure: true,
})
.status(200)
.json({

View file

@ -69,12 +69,18 @@ exports.post = [
});
}
// get current user from jwt token
// get token
const token = req.cookies.JWT_TOKEN;
// extract username from token
const username = jwt.verify(token, process.env.SECRET_KEY).username;
// else data is valid, make post object
const post = new Post({
title: req.body.title,
date: new Date(),
text: req.body.text,
author: req.user.username,
author: username,
_id: new mongoose.Types.ObjectId(),
});

View file

@ -4,19 +4,10 @@ const hasToken = (req, res, next) => {
if (!token) {
// if none, error
return res.status(403).json({
message: "Not authorized!",
});
}
try {
jwt.verify(token, process.env.SECRET_KEY);
// move forward
return next();
} catch {
// if incorrect, error
return res.status(403).json({
message: "Not authorized!",
message: "Token not found!",
});
}
return next();
};
module.exports = hasToken;