This project is an authentication and authorization API built with Node.js, Express, MongoDB, and Mongoose. It supports user registration, login, and role-based access control.
- 🔒 User registration and login with JWT-based authentication
- 🛡️ Role-based access control (RBAC) for endpoints
- 🔑 Secure password handling with bcrypt
- 🧩 Custom role-based middleware
-
Clone the repository:
git clone https://github.com/your-username/Authentication-NodeJS-ExpressJS.git cd auth-project -
Install dependencies:
npm install
-
Set up environment variables:
Create a
.envfile in the root directory of your project and add the following:MONGODB_SRV="mongodb+srv://username:password@cluster0.tosao.mongodb.net/?retryWrites=true&w=majority&appName=ClusterName" PORT=3000 SECRET_KEY="your_jwt_secret_key" -
Run the project:
npm start
- 📁
models/: Contains Mongoose models forUserandRole. - 📁
controllers/: Defines logic for user authentication and authorization (authController.js). - 📁
middleware/: Custom middleware for authorization. - 📁
routes/: Defines routes for registration, login, and user management.
| Method | Endpoint | Description | Authentication Required |
|---|---|---|---|
| POST | auth/registration |
Registers a new user with username and password | No |
| POST | auth/login |
Logs in a user and returns a JWT token | No |
| GET | auth/users |
Retrieves a list of users (admin-only) | Yes |
| GET | auth/admin/create |
Creates a new admin role | Yes |
| GET | auth/users/create |
Creates a new user role | Yes |
POST /registration
Content-Type: application/json
{
"username": "exampleUser",
"password": "password123"
"role":"USER" // "ADMIN" (role = "USER" by default)
}POST /login
Content-Type: application/json
{
"username": "exampleUser",
"password": "password123"
}Requires Bearer <JWT_TOKEN> in the Authorization header.
GET /users
Authorization: Bearer <JWT_TOKEN>Checks if the request contains a valid JWT token.
Checks if the user has the required role(s) for accessing a specific route.
Example:
router.get('/users', roleAuthMiddleware(["ADMIN"]), controller.getUsers);MONGODB_SRV: MongoDB connection stringPORT: Port for the server to run on
IDK, it is for official view, ha-ha. R.Harutyunyan