fixed cors issues
updated token verification middleware reworked blog post POST controller username acquisition
This commit is contained in:
parent
8e1f4a2b08
commit
73ca135cc3
4 changed files with 23 additions and 13 deletions
13
app.js
13
app.js
|
|
@ -37,7 +37,18 @@ app.use(express.urlencoded({ extended: false }));
|
||||||
app.use(express.static(path.join(__dirname, "public")));
|
app.use(express.static(path.join(__dirname, "public")));
|
||||||
|
|
||||||
// cors
|
// 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
|
// routing
|
||||||
app.use("/", indexRouter);
|
app.use("/", indexRouter);
|
||||||
|
|
|
||||||
|
|
@ -16,6 +16,8 @@ exports.post = asyncHandler(async (req, res, next) => {
|
||||||
return res
|
return res
|
||||||
.cookie("JWT_TOKEN", token, {
|
.cookie("JWT_TOKEN", token, {
|
||||||
httpOnly: true,
|
httpOnly: true,
|
||||||
|
sameSite: "none",
|
||||||
|
secure: true,
|
||||||
})
|
})
|
||||||
.status(200)
|
.status(200)
|
||||||
.json({
|
.json({
|
||||||
|
|
|
||||||
|
|
@ -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
|
// else data is valid, make post object
|
||||||
const post = new Post({
|
const post = new Post({
|
||||||
title: req.body.title,
|
title: req.body.title,
|
||||||
date: new Date(),
|
date: new Date(),
|
||||||
text: req.body.text,
|
text: req.body.text,
|
||||||
author: req.user.username,
|
author: username,
|
||||||
_id: new mongoose.Types.ObjectId(),
|
_id: new mongoose.Types.ObjectId(),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -4,19 +4,10 @@ const hasToken = (req, res, next) => {
|
||||||
if (!token) {
|
if (!token) {
|
||||||
// if none, error
|
// if none, error
|
||||||
return res.status(403).json({
|
return res.status(403).json({
|
||||||
message: "Not authorized!",
|
message: "Token not found!",
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
try {
|
|
||||||
jwt.verify(token, process.env.SECRET_KEY);
|
|
||||||
// move forward
|
|
||||||
return next();
|
return next();
|
||||||
} catch {
|
|
||||||
// if incorrect, error
|
|
||||||
return res.status(403).json({
|
|
||||||
message: "Not authorized!",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
module.exports = hasToken;
|
module.exports = hasToken;
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue