-
Notifications
You must be signed in to change notification settings - Fork 72
Open
Description
I'm trying to make a custom server using json-server and auth to access user profile and other custom routes with express. The problem is, I can't specify any custom permissions or the routes won't work. Here is my server.js file:
const express = require("express");
const jsonServer = require("json-server");
const dotenv = require("dotenv");
const auth = require("json-server-auth");
const jwt = require("jsonwebtoken");
const cors = require("cors");
const server = express();
dotenv.config({ path: "./.env" });
const router = jsonServer.router("db.json");
const JWT_SECRET_KEY =
require("./node_modules/json-server-auth/dist/constants").JWT_SECRET_KEY;
server.use(cors());
server.get("/users/me", auth, (req, res) => {
const authorization = req.header("Authorization");
if (!authorization) {
res.statusCode = 401;
return res.json("Not authenticated");
}
const token = authorization.replace("Bearer ", "");
let data;
try {
data = jwt.verify(token, JWT_SECRET_KEY);
} catch (err) {
res.statusCode = 401;
return res.json("JWT expired");
}
try {
const { db } = req.app;
let user = db.get("users").find({ email: data.email }).value();
const { password, ...rest } = user;
res.json(rest);
} catch (error) {
console.log(error.message);
res.statusCode = 500;
return res.json("Error while processing user data");
}
});
const rules = auth.rewriter({
users: 600,
transactions: 640,
});
server.db = router.db;
server.use(auth);
server.use(rules);
server.use(router);
const port = process.env.PORT;
server.listen(port, () => {
console.log("Server running on port", port);
});Whenever I try to make a request using the following permissions, I can get all the transactions without problems:
const rules = auth.rewriter({
users: 600,
});But when I try to specify any permissions it returns undefined:
const rules = auth.rewriter({
users: 600,
transactions: 600
});Here is my db.json:
{
"users": [
{
"email": "[email protected]",
"password": "$2a$10$bNAXGPL/Xs3Wu7CXb8p.UeKB///KIAjcuMdkAlXeDlM09K/1e6eIe",
"firstName": "John",
"lastName": "Doe",
"id": 1
}
],
"transactions": [
{
"name": "Car fix",
"value": 200,
"date": "2023-01-06T03:00:00.000Z",
"categoryId": "0",
"paymentType": "pix",
"id": "f10e0e56-72aa-451c-916b-1a1ce2bfa350",
"userId": 1
}
]
}Same happens with /users: can only access if no permission is specified, otherwise returns undefined.
Only my custom route can be accessed normally and returns 401 if request doesn't have JWT (as expected). Any help is appreciated!
Metadata
Metadata
Assignees
Labels
No labels