System Information
- Strapi Version: 4.4.0
- Operating System: Windows 11 Build 22000.1219
-
Database: SQLite (
better-sqlite 7.4.6
) - Node Version: 16.16.0
- NPM Version: 8.11.0
I’m building an e-commerce and I want to store a shopping cart for a logged-in user in the database (as well as localStorage). I have created a couple of custom routes
// path: ./src/api/cart/routes/custom-cart.js
module.exports = {
routes: [
{
method: "GET",
path: "/cart",
handler: "cart.getMyCart",
},
{
method: "PUT",
path: "/cart",
handler: "cart.updateCart",
},
],
};
and created a couple of custom controllers
module.exports = createCoreController("api::cart.cart", ({ strapi }) => ({
async getMyCart(ctx) {
try {
ctx.body = "ok";
} catch (err) {
ctx.body = err;
}
},
async updateCart(ctx) {
try {
ctx.body = "ok";
} catch (err) {
ctx.body = err;
}
},
}));
If I set the Authenticated role to allow for calling these two routes in the Admin panel (but still leave them unchecked in the Public role) then it properly disallows calling with a bad JWT, but it allows for calling them without an Authorization Bearer token. I have a workaround that just has me checking to see if the ctx.state
has a user, but I would like a more official way to have this working properly.
async getMyCart(ctx) {
if (!ctx.state.user) {
ctx.status = 403;
ctx.body = {
data: null,
error: {
status: 403,
name: "ForbiddenError",
message: "Forbidden",
details: {},
},
};
return;
}
try {
ctx.body = "ok";
} catch (err) {
ctx.body = err;
}
},