{"id":43896298,"url":"https://github.com/muhammad4dev/auth-nest","last_synced_at":"2026-02-06T17:30:48.405Z","repository":{"id":298346576,"uuid":"999618299","full_name":"muhammad4dev/auth-nest","owner":"muhammad4dev","description":null,"archived":false,"fork":false,"pushed_at":"2025-06-10T16:06:34.000Z","size":72,"stargazers_count":0,"open_issues_count":1,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-06-10T17:32:39.358Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/muhammad4dev.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-06-10T14:23:44.000Z","updated_at":"2025-06-10T16:06:41.000Z","dependencies_parsed_at":"2025-06-10T17:38:54.614Z","dependency_job_id":"6c08dc00-87ac-4c34-8d45-9738699fe0ba","html_url":"https://github.com/muhammad4dev/auth-nest","commit_stats":null,"previous_names":["muhammad4dev/auth-nest"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/muhammad4dev/auth-nest","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/muhammad4dev%2Fauth-nest","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/muhammad4dev%2Fauth-nest/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/muhammad4dev%2Fauth-nest/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/muhammad4dev%2Fauth-nest/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/muhammad4dev","download_url":"https://codeload.github.com/muhammad4dev/auth-nest/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/muhammad4dev%2Fauth-nest/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29170039,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-06T16:33:35.550Z","status":"ssl_error","status_checked_at":"2026-02-06T16:33:30.716Z","response_time":59,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2026-02-06T17:30:47.609Z","updated_at":"2026-02-06T17:30:48.396Z","avatar_url":"https://github.com/muhammad4dev.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Secure Nest.js Authentication API\n\nThis project provides a production-ready foundation for handling user authentication. It uses JSON Web Tokens (JWTs) stored in `HttpOnly` cookies and features a full suite of security best practices, including refresh token rotation and active session management.\n\nThe primary database ORM used is [MikroORM](https://mikro-orm.io/ \"null\") with a SQLite driver, making it easy to get started while being configurable for production databases like PostgreSQL or MySQL.\n\n## ✨ Features\n\n- **Secure User Registration \u0026 Login:** Passwords are never stored in plaintext, using strong hashing via `bcryptjs`.\n- **JWT-Based Authentication:** Utilizes a secure two-token system:\n\n  - **Short-Lived Access Tokens (15m):** Used for frequent API access, minimizing the risk of token theft.\n  - **Long-Lived Refresh Tokens (7d):** Used securely and infrequently only to obtain new access tokens.\n\n- **`HttpOnly` Cookie Storage:** Tokens are stored in secure `HttpOnly` cookies, which are inaccessible to client-side JavaScript, protecting them from XSS attacks.\n- **Refresh Token Rotation:** Each time a refresh token is used, it is invalidated and a new one is issued. This prevents token replay attacks and helps detect potential token theft.\n- **Strict Session Management:**\n\n  - **Single Active Session:** A new login invalidates all previous sessions for that user, ensuring only the most recent login is active. This is a strong security default.\n  - **Active Session Management:** Provides endpoints for users to view and manage all their active sessions (device, IP, last used) and revoke any they don't recognize.\n\n- **Database Integration:** Uses **MikroORM** for elegant and powerful database interaction with a repository pattern.\n- **Configuration Driven:** All sensitive information (`JWT_SECRET`, `DATABASE_URL`, etc.) and environment-specific settings are managed through a `.env` file.\n- **Validation:** Employs DTOs (`Data Transfer Objects`) and `class-validator` for robust, type-safe request body validation.\n\n## 🏛️ Architecture \u0026 Design Patterns\n\nThis project is built following modern software design principles to ensure it is scalable, maintainable, and testable.\n\n- **Modular Architecture:** The entire authentication system is encapsulated within a self-contained `AuthModule`, making the codebase organized and easy to navigate.\n- **Layered Architecture (Separation of Concerns):**\n\n  - **Controllers:** Handle incoming HTTP requests and responses. They delegate business logic to services and are the entry point to the API.\n  - **Services:** Contain the core business logic. They are responsible for tasks like creating users, generating tokens, and validating credentials.\n  - **Repositories:** Abstract database communication via MikroORM's `EntityRepository`.\n\n- **Dependency Injection (DI):** Leverages Nest.js's built-in DI container for loosely coupled and easily testable components.\n- **Strategy Pattern:** Uses `passport-jwt` to create a `JwtStrategy` for validating tokens, making the authentication logic pluggable and easy to swap or extend.\n- **Data Transfer Object (DTO) Pattern:** Employs `CreateUserDto` and `LoginUserDto` for type-safe and validated data transfer between the client and server.\n- **Decorator Pattern:** Uses decorators (`@Controller`, `@Injectable`, `@UseGuards`, etc.) extensively to add functionality to classes and methods in a declarative way.\n\n## 📁 Project Structure\n\n```\nsrc\n├── auth\n│   ├── decorators\n│   ├── dto\n│   ├── entities\n│   ├── guards\n│   ├── strategies\n│   ├── auth.controller.ts\n│   ├── auth.module.ts\n│   └── auth.service.ts\n├── config\n├── app.module.ts\n└── main.ts\n\n```\n\n## Endpoints\n\n| Method   | Endpoint                  | Protection          | Description                                                         |\n| -------- | ------------------------- | ------------------- | ------------------------------------------------------------------- |\n| `POST`   | `/api/auth/register`      | Public              | Registers a new user.                                               |\n| `POST`   | `/api/auth/login`         | Public              | Logs in a user, returning tokens as `HttpOnly` cookies.             |\n| `POST`   | `/api/auth/logout`        | _JWT_               | Logs out the user by invalidating their current refresh token.      |\n| `POST`   | `/api/auth/refresh-token` | **_Refresh Token_** | Issues a new access/refresh token. Requires a valid refresh cookie. |\n| `GET`    | `/api/auth/me`            | _JWT_               | Retrieves the profile of the currently authenticated user.          |\n| `GET`    | `/api/auth/sessions`      | _JWT_               | Retrieves a list of all active sessions for the current user.       |\n| `DELETE` | `/api/auth/sessions/:id`  | _JWT_               | Revokes a specific session by its ID.                               |\n\n## 🚀 Getting Started\n\nFollow these instructions to get a copy of the project up and running on your local machine.\n\n### Prerequisites\n\n- [Node.js](https://nodejs.org/ \"null\") (v16 or later recommended)\n- [npm](https://www.npmjs.com/ \"null\") or [yarn](https://yarnpkg.com/ \"null\")\n\n### 1. Installation\n\nClone the repository and install the dependencies.\n\n```\n# Clone the repository\ngit clone \u003cyour-repository-url\u003e\ncd \u003crepository-folder\u003e\n\n# Install dependencies\nnpm install\n\n```\n\n### 2. Environment Configuration\n\nThe application requires a `.env` file in the root of the project. You can create one by copying the example file.\n\n```\ncp .env.example .env\n```\n\nNow, open the `.env` file and set your variables. **It is critical to generate strong, unique secrets.**\n\n```\n# .env\n\n# --- Server Config ---\nPORT=5000\nNODE_ENV=development # or production\nCLIENT_URL=http://localhost:3000 # Your React/Vue/etc. frontend URL\n\n# --- JWT Secrets ---\n# Generate strong random strings for these (e.g., using `openssl rand -hex 32` in your terminal)\nJWT_ACCESS_SECRET=your_super_strong_jwt_access_secret\nJWT_REFRESH_SECRET=your_super_strong_jwt_refresh_secret\n\n```\n\n### 3. Database Setup\n\nThis project uses SQLite, so no external database server is required.\n\n**For Development:** When you first run the application, MikroORM will automatically create the `database.sqlite` file and generate the necessary tables based on your entities.\n\n**For Production:** In a production environment, you should use migrations to manage database schema changes safely.\n\n1.  **Create a new migration:**\n\n    ```\n    npx mikro-orm migration:create\n    ```\n\n2.  **Apply all pending migrations:**\n\n    ```\n    npx mikro-orm migration:up\n    ```\n\n### 4. Running the Application\n\n- **Development Mode (with hot-reloading):**\n\n  ```\n  npm run start:dev\n  ```\n\n  The server will be available at `http://localhost:5000`.\n\n- **Production Mode:** First, build the application:\n\n  ```\n  npm run build\n  ```\n\n  Then, start the optimized server:\n\n  ```\n  npm run start:prod\n  ```\n\n## 📝 Frontend Integration Notes\n\nIf you are building a frontend client for this API, remember these key points:\n\n- **CORS:** Ensure your frontend URL is correctly set in the `CLIENT_URL` variable in the `.env` file.\n- **Cookies:** Your HTTP client (e.g., Axios, fetch) **must** be configured to send credentials with requests. This enables the browser to automatically handle the `HttpOnly` cookies.\n\n  - **For Axios:** `axios.defaults.withCredentials = true;`\n  - **For Fetch API:** `fetch(url, { credentials: 'include' });`\n\n## 💡 Next Steps\n\n- **Add Rate Limiting:** Implement a rate limiter (e.g., `nestjs-rate-limiter`) on sensitive endpoints like `/login` and `/register` to prevent brute-force attacks.\n- **Implement Email Verification:** Add a flow where users must verify their email address after registration.\n- **Add \"Forgot Password\" Flow:** Implement a secure password reset mechanism using signed URLs or one-time codes sent via email.\n- **Switch to a Production Database:** Update the `mikro-orm.config.ts` to use PostgreSQL or MySQL for production deployments.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmuhammad4dev%2Fauth-nest","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmuhammad4dev%2Fauth-nest","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmuhammad4dev%2Fauth-nest/lists"}