{"id":19326187,"url":"https://github.com/marlinsk/nodejs-authentication-backend","last_synced_at":"2026-05-06T04:06:46.743Z","repository":{"id":39158986,"uuid":"492096204","full_name":"Marlinsk/nodejs-authentication-backend","owner":"Marlinsk","description":"User authentication backend application with JWT and refresh token. ","archived":false,"fork":false,"pushed_at":"2023-12-28T02:47:59.000Z","size":369,"stargazers_count":0,"open_issues_count":0,"forks_count":1,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-06-05T06:45:52.004Z","etag":null,"topics":["autentication","express","jwt-token","login-system","middleware","nodejs","prisma","refresh-token","rest-api","sqlite","typescript"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Marlinsk.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2022-05-14T02:51:28.000Z","updated_at":"2023-12-28T02:47:41.000Z","dependencies_parsed_at":"2022-08-09T11:34:44.935Z","dependency_job_id":"426cfc01-8c56-42c3-b68e-031bfec38b00","html_url":"https://github.com/Marlinsk/nodejs-authentication-backend","commit_stats":null,"previous_names":["marlinsk/nodejs-authentication-backend"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/Marlinsk/nodejs-authentication-backend","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Marlinsk%2Fnodejs-authentication-backend","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Marlinsk%2Fnodejs-authentication-backend/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Marlinsk%2Fnodejs-authentication-backend/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Marlinsk%2Fnodejs-authentication-backend/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Marlinsk","download_url":"https://codeload.github.com/Marlinsk/nodejs-authentication-backend/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Marlinsk%2Fnodejs-authentication-backend/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":32677951,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-06T02:33:58.958Z","status":"ssl_error","status_checked_at":"2026-05-06T02:33:39.611Z","response_time":117,"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":["autentication","express","jwt-token","login-system","middleware","nodejs","prisma","refresh-token","rest-api","sqlite","typescript"],"created_at":"2024-11-10T02:12:44.255Z","updated_at":"2026-05-06T04:06:46.468Z","avatar_url":"https://github.com/Marlinsk.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# \u003cimg src=\"https://github.com/Marlinsk/node-authentication-backend/blob/main/.github/key.png\" width=\"48px\" height=\"48px\"\u003e Node.js Authentication Backend Application\n\nA production-ready authentication backend built with **Clean Architecture**, **Domain-Driven Design (DDD)**, and **Test-Driven Development (TDD)** principles, featuring JWT authentication, two-factor authentication, password recovery, and comprehensive logging.\n\n## Description\n\nThis project demonstrates modern software architecture patterns and security best practices for authentication systems. It implements a complete authentication backend with advanced features like two-factor authentication, password recovery, health monitoring, and structured logging.\n\n**Note:** This project serves as a comprehensive reference implementation. While production-ready in architecture, evaluate and adapt the patterns to your specific use case rather than copying directly.\n\n## ✨ Features\n\n### Authentication \u0026 Security\n- ✅ **JWT-based authentication** with access and refresh tokens\n- ✅ **Two-Factor Authentication (2FA)** with TOTP (Google Authenticator compatible)\n- ✅ **Password recovery** with time-limited, single-use tokens\n- ✅ **Email and SMS verification** (adapter pattern for multiple providers)\n- ✅ **Backup codes** for 2FA recovery\n- ✅ **Password hashing** with bcrypt\n\n### System Features\n- ✅ **Health check endpoint** with database connectivity monitoring\n- ✅ **Comprehensive logging system** with Winston (HTTP requests, errors, debug)\n- ✅ **Clean Architecture** with dependency injection\n- ✅ **Database abstraction layer** (supports SQL, NoSQL, In-Memory)\n- ✅ **ULID-based IDs** (sortable, timestamp-based)\n- ✅ **Automated testing** with 95+ unit and integration tests\n- ✅ **Daily log rotation** with 30-day retention\n\n### Developer Experience\n- ✅ TypeScript with strict typing\n- ✅ Path aliases for clean imports\n- ✅ Hot reload in development\n- ✅ Comprehensive API documentation\n- ✅ Test coverage reporting\n\n## 🏗️ Architecture\n\nThis project follows **Clean Architecture** principles with clear separation of concerns:\n\n```\nsrc/\n├── domain/                # Business logic (entities, value objects, repository interfaces)\n├── application/           # Use cases, DTOs, provider interfaces\n├── infrastructure/        # External concerns (database, HTTP, providers)\n│   ├── database/          # Database adapters and repositories\n│   ├── http/              # Controllers, routes, middlewares\n│   └── providers/         # Token, hash, email, SMS, TOTP, logging\n└── shared/                # Shared constants and utilities\n```\n\n**Key Principles:**\n- Dependencies flow inward (Infrastructure → Application → Domain)\n- Domain layer has zero dependencies on outer layers\n- Interfaces defined by inner layers, implemented by outer layers\n- Easy to swap implementations (e.g., in-memory DB for testing)\n\n## 🚀 Getting Started\n\n### Prerequisites\n- Node.js 16+\n- pnpm (recommended) or npm\n- Git\n\n### Install pnpm (if not already installed)\n```bash\nnpm install -g pnpm\n```\n\nOr using corepack (Node.js 16.13+):\n```bash\ncorepack enable\ncorepack prepare pnpm@latest --activate\n```\n\n### Clone the Repository\n```bash\ngit clone https://github.com/Marlinsk/node-authentication-backend.git\ncd node-authentication-backend\n```\n\n### Install Dependencies\n```bash\npnpm install\n```\n\n## ⚙️ Environment Setup\n\nCreate a `.env` file in the project root by copying the example:\n\n```bash\ncp .env.example .env\n```\n\n### Required Variables\n\n#### Core Configuration\n```env\nDATABASE_URL=\"file:./dev.db\"\nJWT_SECRET_KEY=\"your-secret-key-change-in-production\"\n```\n\n#### Password Reset\n```env\nPASSWORD_RESET_URL=\"http://localhost:3000/reset-password\"\nPASSWORD_RESET_TOKEN_EXPIRATION_HOURS=1\n```\n\n#### Two-Factor Authentication\n```env\nTOTP_ISSUER=\"NodeJS Authentication Backend\"\nTOTP_BACKUP_CODES_COUNT=10\n```\n\n#### Email and SMS Providers\n```env\nEMAIL_PROVIDER=\"console\"\nSMS_PROVIDER=\"console\"\nEMAIL_SERVICE_API_KEY=\"\"\nEMAIL_FROM=\"noreply@example.com\"\nSMS_SERVICE_API_KEY=\"\"\nSMS_FROM=\"\"\n```\n\n**Provider Options:**\n- `console` - Development mode (logs to console)\n- `sendgrid` - Production email service\n- `twilio` - Production SMS service\n\n#### Logging Configuration\n```env\nNODE_ENV=\"development\"\nLOG_LEVEL=\"info\"\nLOG_DIR=\"logs\"\nLOG_TO_FILE=\"false\"\n```\n\n**Log Levels:** `error`, `warn`, `info`, `http`, `debug`\n\n## 🏃 Running the Application\n\n### Development Mode\n```bash\npnpm dev\n```\nServer starts at `http://localhost:5500`\n\n### Production Build\n```bash\npnpm build\npnpm start\n```\n\n### Testing\n```bash\npnpm test                # Run all tests\npnpm test:watch          # Watch mode\npnpm test:coverage       # Coverage report\n```\n\n## 🛣️ API Endpoints\n\n### Health Check\n- `GET /health` - Application health status (public)\n\n### User Management\n- `POST /` - Create user account\n- `POST /login` - User authentication\n- `GET /` - List all users (protected)\n- `GET /:id` - Get user by ID (protected)\n- `PUT /:id` - Update user (protected)\n- `DELETE /:id` - Delete user (protected)\n\n### Password Reset\n- `POST /password/request` - Request password reset\n- `POST /password/reset` - Reset password with token\n\n### Two-Factor Authentication\n- `POST /2fa/enable` - Enable 2FA (protected)\n- `POST /2fa/verify` - Verify 2FA token (protected)\n- `POST /2fa/verify-backup` - Verify backup code (protected)\n- `DELETE /2fa/disable` - Disable 2FA (protected)\n\n### Request Examples\n\n#### Create User\n```bash\nPOST http://localhost:5500/\nContent-Type: application/json\n\n{\n  \"name\": \"Andre Haskell\",\n  \"username\": \"haskell\",\n  \"email\": \"andhaskell@gmail.com\",\n  \"password\": \"SecurePass123\"\n}\n```\n\n#### Login\n```bash\nPOST http://localhost:5500/login\nContent-Type: application/json\n\n{\n  \"username\": \"haskell\",\n  \"password\": \"SecurePass123\"\n}\n```\n\n#### Enable 2FA\n```bash\nPOST http://localhost:5500/2fa/enable\nAuthorization: Bearer \u003cyour-token\u003e\nContent-Type: application/json\n\n{\n  \"method\": \"totp\"\n}\n```\n\n#### Request Password Reset\n```bash\nPOST http://localhost:5500/password/request\nContent-Type: application/json\n\n{\n  \"email\": \"andhaskell@gmail.com\"\n}\n```\n\nFor complete API documentation, see [API_DOCUMENTATION.md](API_DOCUMENTATION.md)\n\n## 🧪 Testing\n\nThe project includes comprehensive test coverage:\n\n```bash\npnpm test                # Run all tests (95+ tests)\npnpm test:watch          # Watch mode for TDD\npnpm test:coverage       # Generate coverage report\n```\n\n**Test Structure:**\n- **Unit tests:** Domain entities, value objects, use cases\n- **Integration tests:** Repository implementations, database operations\n- **E2E tests:** HTTP endpoints (planned)\n\n## 🏦 Database Management\n\n### Access Database Editor\n```bash\npnpm prisma:studio\n```\n\n### Database Commands\n```bash\npnpm prisma:migrate      # Create and apply migrations\npnpm prisma:generate     # Regenerate Prisma Client\npnpm prisma:push         # Push schema changes\npnpm prisma:seed         # Run database seeds\n```\n\n### Supported Databases\nThe application uses an adapter pattern supporting:\n- **In-Memory** (default for development/testing)\n- **SQL databases** (PostgreSQL, MySQL, SQLite)\n- **NoSQL databases** (MongoDB)\n\nConfigure via `DATABASE_TYPE` in database config.\n\n## 📊 Logging System\n\nThe application includes a comprehensive logging system powered by Winston:\n\n### Features\n- **Automatic HTTP request logging** (method, URL, status, duration, IP)\n- **Error tracking** with stack traces\n- **Daily log rotation** (30-day retention, 20MB per file)\n- **Separate error and combined logs**\n- **Colorized console output** in development\n- **JSON format** for log aggregation tools\n\n### Log Files (when enabled)\n```\nlogs/\n├── error/\n│   └── error-2025-12-05.log\n└── combined/\n    └── combined-2025-12-05.log\n```\n\n### Configuration\nSet `LOG_TO_FILE=\"true\"` in `.env` to enable file logging in development.\n\nIn production (`NODE_ENV=\"production\"`), logs are automatically saved to files.\n\n## 📁 Project Structure\n\n```\nnode-authentication-backend/\n├── src/\n│   ├── domain/                         # Core business logic\n│   │   ├── user/\n│   │   │   ├── entities/               # User, RefreshToken, PasswordResetToken, TwoFactorAuth\n│   │   │   └── repositories/           # Repository interfaces\n│   │   └── shared/\n│   │       ├── errors/                 # Domain errors\n│   │       └── value-objects/          # Email, Password, EntityId\n│   │\n│   ├── application/                    # Application services\n│   │   ├── use-cases/                  # Business workflows\n│   │   │   ├── user/                   # CRUD, authentication\n│   │   │   ├── password-reset/         # Password recovery\n│   │   │   ├── two-factor/             # 2FA operations\n│   │   │   └── health/                 # Health check\n│   │   ├── dtos/                       # Data transfer objects\n│   │   └── providers/                  # Provider interfaces\n│   │\n│   ├── infrastructure/                 # Technical implementation\n│   │   ├── database/\n│   │   │   ├── adapters/               # SQL, NoSQL, In-Memory\n│   │   │   ├── repositories/           # Concrete implementations\n│   │   │   └── connection/             # Database factory\n│   │   ├── http/\n│   │   │   ├── controllers/            # HTTP handlers\n│   │   │   ├── middlewares/            # Auth, error, logger\n│   │   │   ├── routes/                 # Route definitions\n│   │   │   └── factories/              # Dependency injection\n│   │   └── providers/\n│   │       ├── token/                  # JWT, bcrypt\n│   │       ├── email/                  # Console, SendGrid\n│   │       ├── sms/                    # Console, Twilio\n│   │       ├── totp/                   # Speakeasy TOTP\n│   │       └── logger/                 # Winston\n│   │\n│   ├── shared/                         # Shared resources\n│   │   └── constants/                  # HTTP status codes\n│   │\n│   └── tests/                          # Test suites\n│       ├── unit/                       # Isolated tests\n│       └── integration/                # Database tests\n│\n├── .env.example                        # Environment template\n├── API_DOCUMENTATION.md                # Complete API docs\n├── CLAUDE.md                           # Project guide\n└── README.md                           # This file\n```\n\n## 🛠️ Technologies\n\n### Core\n- **Node.js** - Runtime environment\n- **TypeScript** - Type safety and developer experience\n- **Express** - HTTP server framework\n\n### Architecture \u0026 Patterns\n- **Clean Architecture** - Separation of concerns\n- **DDD** - Domain-driven design principles\n- **TDD** - Test-driven development\n- **Dependency Injection** - Loose coupling\n\n### Authentication \u0026 Security\n- **JWT** - JSON Web Tokens (jsonwebtoken)\n- **bcrypt** - Password hashing\n- **Speakeasy** - TOTP for 2FA\n- **ULID** - Unique ID generation\n\n### Database \u0026 Storage\n- **Prisma** - ORM (optional)\n- **Adapter pattern** - Database abstraction\n\n### Logging \u0026 Monitoring\n- **Winston** - Structured logging\n- **winston-daily-rotate-file** - Log rotation\n\n### Testing\n- **Jest** - Test framework\n- **95+ tests** - Unit and integration coverage\n\n### Development\n- **Babel** - TypeScript compilation\n- **Nodemon** - Hot reload\n- **ESLint** - Code linting (optional)\n\n## 📚 Additional Documentation\n\n- [API_DOCUMENTATION.md](API_DOCUMENTATION.md) - Complete API reference with examples\n- [CLAUDE.md](CLAUDE.md) - Detailed architecture guide and development instructions\n\n## 🤝 Contributing\n\nContributions are welcome! This project serves as a learning resource, and improvements are encouraged.\n\n### Areas for Contribution\n- Rate limiting implementation\n- Real email/SMS provider implementations\n- Additional test coverage\n- Performance optimizations\n- Documentation improvements\n\n## 📝 License\n\nThis project is open source and available for educational purposes.\n\n## 🎯 Learning Objectives\n\nThis project demonstrates:\n- Clean Architecture implementation in Node.js\n- Domain-Driven Design patterns\n- Test-Driven Development workflow\n- Security best practices (JWT, 2FA, password reset)\n- Logging and monitoring strategies\n- Database abstraction and dependency injection\n- TypeScript advanced features\n\n## 🔒 Security Notes\n\n- Always change default JWT secret in production\n- Use strong password policies\n- Enable 2FA for sensitive operations\n- Keep dependencies updated\n- Review logs regularly for suspicious activity\n- Use HTTPS in production\n- Implement rate limiting for authentication endpoints\n\n## 🚀 Production Checklist\n\nBefore deploying to production:\n- [ ] Change `JWT_SECRET_KEY` to a strong secret\n- [ ] Set `NODE_ENV=\"production\"`\n- [ ] Configure real email provider (SendGrid)\n- [ ] Configure real SMS provider (Twilio)\n- [ ] Set up database migrations\n- [ ] Enable `LOG_TO_FILE=\"true\"`\n- [ ] Configure log aggregation (ELK, CloudWatch, etc.)\n- [ ] Implement rate limiting\n- [ ] Set up SSL/TLS certificates\n- [ ] Configure CORS properly\n- [ ] Review and test health check integration\n- [ ] Set up monitoring and alerts\n\n---\n\n**Built with ❤️ using Clean Architecture principles**\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmarlinsk%2Fnodejs-authentication-backend","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmarlinsk%2Fnodejs-authentication-backend","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmarlinsk%2Fnodejs-authentication-backend/lists"}