An open API service indexing awesome lists of open source software.

https://github.com/kornetas/api-forge

Node.js REST API with user authentication, JWT, roles, and product management โ€“ fully tested with Jest.
https://github.com/kornetas/api-forge

api authentication autorization backend bcrypt express jest jwt mongodb mongoose nodejs rest-api roles supertest

Last synced: 12 days ago
JSON representation

Node.js REST API with user authentication, JWT, roles, and product management โ€“ fully tested with Jest.

Awesome Lists containing this project

README

          

# Express API โ€“ Products + Auth + JWT ๐Ÿ”

Simple Node.js + Express API with user authentication, JWT, roles (admin/user), and CRUD for products.

## ๐Ÿ”ง Tech Stack

- Node.js
- Express
- MongoDB
- JWT
- Bcrypt
- Jest + Supertest

## ๐Ÿš€ Features

- User registration and login
- Password hashing with bcrypt
- JWT token authentication
- Role system (admin, user)
- Auth middleware
- Role middleware (for example: only admin can add products)
- Product CRUD (Create, Read, Update, Delete)
- Authorization: only product owner or admin can edit/delete

## ๐Ÿ“ Folder Structure

```
/controllers โ†’ logic for auth and products
/routes โ†’ API endpoints
/models โ†’ Mongoose schemas
/middleware โ†’ auth and role checks
/tests โ†’ basic auth + product tests
app.js โ†’ express app setup
server.js โ†’ DB connection + app start
```

## ๐Ÿงช Basic Test Example

```
npm test
```

- Runs Jest tests for auth and products
- Uses test database (`api-test`, `api-test-products`)

## ๐Ÿ›  How to Run

1. Clone the repo
2. Install packages:

```
npm install
```

3. Create `.env` file in the main folder

4. Copy and paste the following into your .env file:

```
PORT=5000
MONGO_URI=mongodb://localhost:27017/api-forge
JWT_SECRET=yourSecretKeyHere
```

## Database Seeding

To seed the database with a default admin, a normal user, and example products, run:

```bash
node seed.js

```

5. Start server:

```
npm run dev
```

---

## ๐Ÿ” Example Routes

### Auth:

- `POST /api/auth/register` โ€“ register user
- `POST /api/auth/login` โ€“ login and get token

### Products:

- `GET /api/products` โ€“ public
- `POST /api/products` โ€“ admin only
- `PUT /api/products/:id` โ€“ owner or admin
- `DELETE /api/products/:id` โ€“ owner or admin

Add token in header:

```
Authorization: Bearer your_token_here
```

---