Dynamic Role Based Access
Dynamic Role-Based Access and Permission Procedures System
User Authentication:
Users log in via a POST request to
/login
.The server verifies credentials against the database.
If valid, a JWT token is generated and sent to the client as a cookie.
Token Verification Middleware: Custom Middleware
verifyUser
middleware checks for the presence of a JWT token in cookies.If the token is valid, the user ID is extracted and added to the request object.
This middleware protects routes, ensuring only authenticated users can access them.
Fetching User Profile:
On component mount, a GET request to
/api/profile
is made.The
verifyUser
middleware verifies the token.If successful, it returns the user ID.
Fetching Detailed User Info:
The
fetchProfileInfo
function is called with the user ID.A GET request to
/api/profileInfo/:id
retrieves detailed user information from the database.
Role-Based Access Control:
The user’s role is determined by
authority_adminType
from the profile info.If the user is a manager (
authority_adminType === "ম্যানেজার"
), thestatus
state is set tofalse
.
Conditional Rendering in Frontend:
Menu items are conditionally rendered based on the
status
state.Authorized menu items are always visible.
Unauthorized menu items are only visible if
status
istrue
.
Key Components and Functions
Backend Routes and Logic:
/login
: Handles user authentication and token generation.verifyUser
: Middleware to verify JWT tokens./api/profile
: Returns user ID if token is valid./api/profileInfo/:id
: Fetches detailed user information based on user ID.
Frontend Logic:
useEffect
: Fetches user ID and profile information on component mount.fetchProfileInfo
: Fetches and processes detailed profile info to determine user role.Conditional rendering: Uses
status
to control the visibility of menu items.
useEffect(() => {
// Fetch the user ID
axios
.get("http://localhost:3001/api/profile", { withCredentials: true })
.then((res) => {
if (res.data.statusbar === "success") {
console.log(res.data.id);
fetchProfileInfo(res.data.id);
} else {
console.log("error");
}
});
}, []);
async function fetchProfileInfo(id) {
try {
const response = await axios.get(
`http://localhost:3001/api/profileInfo/${id}`
);
if (response.data) {
console.log(response.data.id);
console.log(response.data.authority_adminType);
if (response.data.authority_adminType === "ম্যানেজার") {
setStatus(false);
}
} else {
console.log("error");
}
} catch (error) {
console.log("Error:", error);
}
}
app.post("/login", (req, res) => {
const sql = "SELECT * FROM user WHERE `username` = ? AND `password` = ?";
db.query(sql, [req.body.email, req.body.password], (err, data) => {
console.log(data);
if (err) {
return res.json(err);
}
if (data.length === 0) {
return res.json({ message: "Invalid username or password" });
}
console.log(data[0].id);
const id = data[0].id;
const token = jwt.sign({ id }, "screet-token", { expiresIn: "1d" });
res.cookie("token", token);
return res.json("success");
});
});
const verifyUser = (req, res, next) => {
const token = req.cookies.token;
if (!token) {
return res.json("error");
} else {
jwt.verify(token, "screet-token", (err, decoded) => {
if (err) {
return res.json("error");
} else {
req.id = decoded.id;
next();
}
});
}
};
app.get("/api/profile", verifyUser, (req, res) => {
return res.json({ statusbar: "success", id: req.id });
});
app.get("/api/profileInfo/:id", (req, res) => {
const id = req.params.id; // Get the id from the request parameters
const query = "SELECT * FROM user WHERE id = ?"; // Modify the SQL query to fetch user data based on id
db.query(query, [id], (err, results) => {
if (err) {
console.error("Error executing SQL query: " + err);
res.status(500).json({ error: "Internal Server Error" });
} else {
if (results.length === 0) {
// If no user with the specified id is found, return a 404 Not Found response
res.status(404).json({ error: "User not found" });
} else {
// Send the retrieved user data as a JSON response
console.log(results[0]);
res.json(results[0]); // Assuming you expect only one user with the given id
}
}
});
});
Last updated