This project is an authentication example built with Node.js, Express, and MongoDB. It demonstrates user signup, login, and role-based access control using JWT for authentication.
- User Signup
- User Login
- Role-based Access Control
- JWT Authentication
- User Deletion (Admin only)
- Node.js
- MongoDB
-
Clone the repository:
git clone https://github.com/mathisdev7/auth-example
-
Navigate to the project directory:
cd auth-example
-
Install the dependencies:
npm install
or
pnpm install
or
yarn add
-
Create a
.env
file in the root directory and add your MongoDB URI and JWT secret:MONGO_URI=your_mongo_uri JWT_SECRET=your_jwt_secret
To start the server, run:
npm start
or
pnpm start
or
yarn start
The server will be running on http://localhost:3000
.
To run the tests, use:
npm test
or
pnpm test
or
yarn test
-
Endpoint:
/api/auth/signup
-
Method: POST
-
Request Body:
{ "name": "string", "email": "string", "password": "string", "username": "string", "role": "user" | "admin" }
-
Response:
201 Created
on success400 Bad Request
if user already exists or validation fails
- Endpoint:
/api/auth/login
- Method: POST
- Request Body:
{ "email": "string", "password": "string" }
- Response:
200 OK
with JWT token on success400 Bad Request
if credentials are incorrect
- Endpoint:
/api/users/me
- Method: GET
- Headers:
Authorization: Bearer <token>
- Response:
200 OK
with user data401 Unauthorized
if token is missing or invalid
- Endpoint:
/api/users/delete/:id
- Method: GET
- Headers:
Authorization: Bearer <token>
- Response:
200 OK
if user is deleted403 Forbidden
if the user is not an admin404 Not Found
if user does not exist
interface IUser {
name: string;
email: string;
password: string;
username: string;
role: "user" | "admin";
createdAt: Date;
updatedAt: Date;
}
interface CustomRequest extends express.Request {
user?: {
_id: string;
name: string;
email: string;
password: string;
username: string;
role: string;
};
}
This project is licensed under the MIT License.