(This README file contains the description of the project along with instructions to access and test it)
A backend project implementing Role-Based Access Control (RBAC) using Node.js, Express, and MongoDB. This project provides user authentication, role-based authorization, and secure access to resources.
- User authentication using JWT (JSON Web Tokens).
- Password hashing with bcrypt.js.
- Role-based authorization for restricted routes.
- Secure database integration with MongoDB.
- Node.js: Runtime environment.
- Express.js: Web framework.
- MongoDB: NoSQL database.
- Mongoose: ODM for MongoDB.
- bcrypt.js: Password hashing.
- Clone the repository:
git clone https://github.com/ayush-jain-09/Backend_Role_based_Acess_control.git- Navigate to the project directory:
cd Backend_Role_based_Acess_control- Install dependencies:
npm install- Set up environment variables:
Create a .env file in the root directory.
Add the following variables:
PORT=7002
MONGO_URI=your_mongo_connection_string
JWT_SECRET=your_secret_key
- Run the server:
npm run devThe server will start on http://localhost:7002.
Base URL: For local development: http://localhost:7002
URL:
POST /api/auth/register
Description: Registers a new user with a username, password, and role.
Request Body:
{
"username": "exampleUser",
"password": "examplePassword",
"role": "admin"
}
Response (Success):
{
"message": "User registered with username exampleUser"
}
Response (Error):
{
"message": "Something went wrong"
}
URL:
POST /api/auth/login
Description: Authenticates a user and returns a JWT token.
Request Body:
{
"username": "exampleUser",
"password": "examplePassword"
}
Response (Success):
{
"token": "your_jwt_token"
}
Response (Error):
{
"message": "Invalid credentials"
}
URL:
GET /api/users/admin
Description: Accessible only to users with the admin role.
Headers:
Authorization: Bearer <your_jwt_token>
Response (Success):
{
"message": "Welcome Admin"
}
Response (Error):
{
"message": "Access denied"
}
URL:
GET /api/users/manager
Description: Accessible to users with either admin or manager roles.
Headers:
Authorization: Bearer <your_jwt_token>
Response (Success):
{
"message": "Welcome Manager"
}
Response (Error):
{
"message": "Access denied"
}
URL:
GET /api/users/user
Description: Accessible to users with roles admin, manager, or user.
Headers:
Authorization: Bearer <your_jwt_token>
Response (Success):
{
"message": "Welcome User"
}
Response (Error):
{
"message": "Access denied"
}
401 Unauthorized:
{
"message": "No token, authorization denied"
}
403 Forbidden:
{
"message": "Access denied"
}
404 Not Found:
{
"message": "User with username exampleUser not found"
}
500 Internal Server Error:
{
"message": "Something went wrong"
}