gpt-4o-mini-2024-07-18· OpenAI
WildChat-4.8M (AI2)
Description: Create a role based access check middle ware functions, please check the…
- User
Description: Create a role based access check middle ware functions, please check the roles from token,, if the role is admin i have to verify the user from db does it exist or not
Generate source code based on the description above and respond in the following JSON format ONLY: ```json { "name": "prompt_name", "schema": { "type": "string", "code": "Generated code here" } } ``` IMPORTANT: - Ensure the JSON response is error-free. - Include no additional text or explanations. Respond with the JSON object only. - Assistant
{ "name": "roleBasedAccessCheck", "schema": { "type": "string", "code": "const jwt = require('jsonwebtoken');\nconst db = require('./db'); // assumes you have a db module to interact with your database\n\nconst roleBasedAccessCheck = async (req, res, next) => {\n const token = req.headers['authorization']?.split(' ')[1];\n if (!token) {\n return res.status(403).json({ message: 'No token provided.' });\n }\n\n try {\n const decoded = jwt.verify(token, process.env.JWT_SECRET);\n const userRole = decoded.role;\n\n if (userRole === 'admin') {\n const user = await db.getUserById(decoded.id); // function to get user from DB\n if (!user) {\n return res.status(404).json({ message: 'User not found.' });\n }\n }\n\n next();\n } catch (error) {\n return res.status(500).json({ message: 'Failed to authenticate token.' });\n }\n};\n\nmodule.exports = roleBasedAccessCheck;" } }