{"id":31322763,"url":"https://github.com/jonace-mpelule/cauth-express","last_synced_at":"2026-05-05T04:05:43.540Z","repository":{"id":315828937,"uuid":"1060961099","full_name":"jonace-mpelule/cauth-express","owner":"jonace-mpelule","description":"Custom Auth 'aka' CAuth for nodejs is a lightweight authentication tool to help work on the important things that Authentication. We handle everything out of box","archived":false,"fork":false,"pushed_at":"2025-09-21T00:42:30.000Z","size":10449,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-09-21T02:37:15.235Z","etag":null,"topics":["authentication","express","jwt","nodejs","postgres","prisma"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/jonace-mpelule.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","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,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-09-21T00:25:30.000Z","updated_at":"2025-09-21T00:57:01.000Z","dependencies_parsed_at":"2025-09-21T02:47:52.572Z","dependency_job_id":null,"html_url":"https://github.com/jonace-mpelule/cauth-express","commit_stats":null,"previous_names":["jonace-mpelule/cauth-express"],"tags_count":null,"template":false,"template_full_name":null,"purl":"pkg:github/jonace-mpelule/cauth-express","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jonace-mpelule%2Fcauth-express","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jonace-mpelule%2Fcauth-express/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jonace-mpelule%2Fcauth-express/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jonace-mpelule%2Fcauth-express/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/jonace-mpelule","download_url":"https://codeload.github.com/jonace-mpelule/cauth-express/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jonace-mpelule%2Fcauth-express/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":276966636,"owners_count":25736829,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-09-25T02:00:09.612Z","response_time":80,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"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":["authentication","express","jwt","nodejs","postgres","prisma"],"created_at":"2025-09-25T19:13:08.827Z","updated_at":"2025-09-25T19:13:10.147Z","avatar_url":"https://github.com/jonace-mpelule.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# 🔐 CAuth - Custom Authentication for Node.js\n\n[![npm version](https://badge.fury.io/js/%40cauth%2Fexpress.svg)](https://badge.fury.io/js/%40cauth%2Fexpress)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n[![TypeScript](https://img.shields.io/badge/%3C%2F%3E-TypeScript-%230074c1.svg)](http://www.typescriptlang.org/)\n\n\u003e **The Complete Authentication Solution for Modern Node.js Applications**\n\nCAuth (Custom Auth) is a powerful, flexible, and secure authentication library designed to handle all your authentication needs with minimal configuration. Built with TypeScript and following industry standards, CAuth provides JWT management, role-based access control, password security, and much more.\n\n## ✨ Features\n\n- 🔑 **JWT Token Management** - Access \u0026 Refresh token handling\n- 👥 **Role-Based Access Control** - Flexible role management with type safety\n- 🔄 **Automatic Token Refresh** - Seamless token renewal\n- 📱 **Flexible Authentication** - Email OR Phone Number (login), Email AND/OR Phone (registration)\n- 🛡️ **Security First** - Industry-standard security practices\n- 🎯 **Zero Configuration** - Works out of the box\n- 📦 **Framework Agnostic** - Works with Express, Fastify, and more\n- 🔧 **TypeScript Ready** - Full type safety and IntelliSense\n- 🚀 **Performance Optimized** - Built for production environments\n- 🔐 **2FA Ready** - Two-factor authentication support (coming soon)\n- ⚡ **Function-based API** - Simple, clean API design\n\n## 🚀 Quick Start\n\n### Installation\n\n```bash\n# Using pnpm (recommended)\npnpm add @cauth/express\n\n# Using npm\nnpm install @cauth/express\n\n# Using yarn\nyarn add @cauth/express\n```\n\n### Key Features\n\n- 🎯 **Function-based API** - Simple function call instead of class instantiation\n- 📱 **Flexible Registration** - Support for email, phone, or both simultaneously\n- 🔒 **Type-safe Configuration** - Full TypeScript support with compile-time validation\n\n### Database Schema\n\nCAuth requires a simple database schema. Here's the Prisma model:\n\n```prisma\nmodel Auth {\n  id            String    @id @default(uuid())\n  phoneNumber   String?   @unique\n  email         String?   @unique\n  passwordHash  String\n  role          String\n  lastLogin     DateTime\n  refreshTokens String[]\n  createdAt     DateTime  @default(now())\n  updatedAt     DateTime  @updatedAt\n}\n```\n\n### Basic Setup\n\n```typescript\nimport { CAuth, PrismaProvider } from '@cauth/express';\nimport { PrismaClient } from '@prisma/client';\n\n// Initialize your database client\nconst prisma = new PrismaClient();\n\n// Create CAuth instance\nconst auth = CAuth({\n  dbProvider: new PrismaProvider(prisma),\n  roles: ['user', 'admin', 'moderator'],\n  accessTokenSecret: process.env.ACCESS_TOKEN_SECRET!,\n  refreshTokenSecret: process.env.REFRESH_TOKEN_SECRET!,\n  jwtConfig: {\n    accessTokenLifeSpan: '15m',\n    refreshTokenLifeSpan: '7d',\n  },\n});\n\nexport default auth;\n```\n\n## 📖 Documentation\n\n### 🏗️ Architecture\n\nCAuth follows a modular architecture that separates concerns:\n\n- **Routes** - Ready-to-use Express route handlers\n- **Functions** - Core authentication logic\n- **Middleware** - Authentication guards and protection\n- **Providers** - Database abstraction layer\n- **Tokens** - JWT management utilities\n\n### 🔧 Configuration\n\nCAuth uses a simple configuration object called `CAuthOptions`:\n\n```typescript\ninterface CAuthOptions {\n  dbProvider: DbProvider;           // Database provider instance\n  roles: string[];                  // Available roles in your system\n  accessTokenSecret: string;        // Secret for access tokens\n  refreshTokenSecret: string;       // Secret for refresh tokens\n  jwtConfig?: {                     // Optional JWT configuration\n    accessTokenLifeSpan?: string;   // Default: '15m'\n    refreshTokenLifeSpan?: string;  // Default: '7d'\n  };\n}\n```\n\n### 🛡️ Middleware\n\n#### AuthGuard\n\nProtect routes with role-based access control:\n\n```typescript\nimport auth from './auth.config';\n\n// Protect route for any authenticated user\napp.get('/profile', auth.Guard(), (req, res) =\u003e {\n  res.json({ user: req.cauth });\n});\n\n// Protect route for specific roles\napp.get('/admin', auth.Guard(['admin']), (req, res) =\u003e {\n  res.json({ message: 'Admin only content' });\n});\n\n// Multiple roles allowed\napp.get('/moderate', auth.Guard(['admin', 'moderator']), (req, res) =\u003e {\n  res.json({ message: 'Moderator or admin content' });\n});\n```\n\n### 🛠️ Routes\n\nCAuth provides ready-to-use route handlers:\n\n```typescript\nimport auth from './auth.config';\n\n// Authentication routes\napp.post('/auth/register', auth.Routes.Register());\napp.post('/auth/login', auth.Routes.Login());\napp.post('/auth/refresh', auth.Routes.Refresh());\napp.post('/auth/logout', auth.Routes.Logout());\napp.post('/auth/change-password', auth.Routes.ChangePassword());\n```\n\n### 🔨 Functions\n\nUse CAuth functions for custom implementations:\n\n```typescript\nimport auth from './auth.config';\n\n// Custom registration endpoint\napp.post('/custom/register', async (req, res) =\u003e {\n  try {\n    const result = await auth.FN.Register({\n      email: req.body.email,\n      password: req.body.password,\n      role: 'user',\n    });\n\n    if (result.success) {\n      res.status(201).json({\n        message: 'User registered successfully',\n        userId: result.data.id,\n      });\n    } else {\n      res.status(400).json({\n        error: result.error,\n      });\n    }\n  } catch (error) {\n    res.status(500).json({ error: 'Internal server error' });\n  }\n});\n```\n\n### 🔑 Token Management\n\nCAuth handles JWT tokens automatically:\n\n```typescript\n// Generate token pairs\nconst tokens = await auth.Tokens.GenerateTokenPairs({\n  id: user.id,\n  role: user.role,\n});\n\n// Verify access token\nconst payload = await auth.Tokens.VerifyAccessToken\u003c{ id: string; role: string }\u003e(\n  accessToken\n);\n\n// Verify refresh token\nconst refreshPayload = await auth.Tokens.VerifyRefreshToken\u003c{ id: string }\u003e(\n  refreshToken\n);\n```\n\n## 📋 API Reference\n\n### Registration\n\nRegister a new user with email, phone number, or both:\n\n```typescript\n// Email registration\nawait auth.FN.Register({\n  email: 'user@example.com',\n  password: 'securePassword123',\n  role: 'user',\n});\n\n// Phone registration\nawait auth.FN.Register({\n  phoneNumber: '+1234567890',\n  password: 'securePassword123',\n  role: 'user',\n});\n\n// Both email and phone (recommended for better UX)\nawait auth.FN.Register({\n  email: 'user@example.com',\n  phoneNumber: '+1234567890',\n  password: 'securePassword123',\n  role: 'user',\n});\n```\n\n### Login\n\nAuthenticate users with email OR phone (one at a time):\n\n```typescript\n// Email login\nconst result = await auth.FN.Login({\n  email: 'user@example.com',\n  password: 'securePassword123',\n});\n\n// Phone login\nconst result = await auth.FN.Login({\n  phoneNumber: '+1234567890',\n  password: 'securePassword123',\n});\n```\n\n### Password Management\n\n```typescript\n// Change password (requires authentication)\nawait auth.FN.ChangePassword({\n  accountId: userId,\n  oldPassword: 'oldPassword',\n  newPassword: 'newSecurePassword',\n});\n```\n\n### Token Refresh\n\n```typescript\n// Refresh tokens\nconst result = await auth.FN.Refresh({\n  refreshToken: 'your-refresh-token',\n});\n```\n\n### Logout\n\n```typescript\n// Logout user\nawait auth.FN.Logout({\n  refreshToken: 'your-refresh-token',\n});\n```\n\n## 🔒 Security Features\n\n### Password Security\n- **Bcrypt Hashing** - Industry-standard password hashing\n- **Salt Rounds** - Configurable salt rounds (default: 10)\n- **Password Validation** - Built-in password strength requirements\n\n### JWT Security\n- **Separate Secrets** - Different secrets for access and refresh tokens\n- **Short-lived Access Tokens** - Default 15 minutes\n- **Long-lived Refresh Tokens** - Default 7 days\n- **Token Rotation** - Automatic refresh token rotation\n\n### Role-Based Access Control\n- **Flexible Roles** - Define custom roles for your application\n- **Middleware Protection** - Easy route protection\n- **Permission Validation** - Server-side role validation\n\n## 🎯 Use Cases\n\n### E-commerce Platform\n```typescript\n// Customer registration (supports email, phone, or both)\napp.post('/customers/register', auth.Routes.Register());\n\n// Admin panel protection\napp.use('/admin', auth.Guard(['admin']));\n\n// Customer profile protection\napp.use('/profile', auth.Guard(['customer', 'admin']));\n```\n\n### SaaS Application\n```typescript\n// Multi-tenant with roles\nconst roles = ['user', 'admin', 'owner', 'billing'];\n\n// Protect billing routes\napp.use('/billing', auth.Guard(['owner', 'billing']));\n\n// Protect admin features\napp.use('/admin', auth.Guard(['admin', 'owner']));\n```\n\n### Mobile App Backend\n```typescript\n// Login with email OR phone\napp.post('/auth/login', auth.Routes.Login());\n\n// Registration with both email and phone for better UX\napp.post('/auth/register', auth.Routes.Register());\n\n// Token refresh for mobile\napp.post('/auth/refresh', auth.Routes.Refresh());\n```\n\n## 🚀 Advanced Usage\n\n### Custom Database Provider\n\n```typescript\nimport { DbProvider } from '@cauth/express';\n\nclass CustomDbProvider implements DbProvider {\n  async findAccountWithCredential({ email, phoneNumber }) {\n    // Your custom database logic\n  }\n\n  async createAccount({ data }) {\n    // Your custom database logic\n  }\n\n  // ... implement other required methods\n}\n\nconst auth = CAuth({\n  dbProvider: new CustomDbProvider(),\n  roles: ['user', 'admin'],\n  accessTokenSecret: process.env.ACCESS_TOKEN_SECRET!,\n  refreshTokenSecret: process.env.REFRESH_TOKEN_SECRET!,\n});\n```\n\n### Custom Error Handling\n\n```typescript\napp.use((error, req, res, next) =\u003e {\n  if (error.code === 'invalid-credentials') {\n    return res.status(401).json({\n      error: 'Invalid email or password',\n    });\n  }\n  \n  if (error.code === 'account-exists') {\n    return res.status(409).json({\n      error: 'Account already exists',\n    });\n  }\n  \n  next(error);\n});\n```\n\n### Environment Configuration\n\n```typescript\n// .env\nACCESS_TOKEN_SECRET=your-super-secret-access-token-key\nREFRESH_TOKEN_SECRET=your-super-secret-refresh-token-key\nJWT_ACCESS_LIFESPAN=15m\nJWT_REFRESH_LIFESPAN=7d\n\n// auth.config.ts\nconst auth = CAuth({\n  dbProvider: new PrismaProvider(prisma),\n  roles: process.env.ROLES?.split(',') || ['user', 'admin'],\n  accessTokenSecret: process.env.ACCESS_TOKEN_SECRET!,\n  refreshTokenSecret: process.env.REFRESH_TOKEN_SECRET!,\n  jwtConfig: {\n    accessTokenLifeSpan: process.env.JWT_ACCESS_LIFESPAN,\n    refreshTokenLifeSpan: process.env.JWT_REFRESH_LIFESPAN,\n  },\n});\n```\n\n## 🧪 Testing\n\nCAuth is designed to be easily testable:\n\n```typescript\nimport { describe, it, expect } from 'vitest';\nimport { CAuth } from '@cauth/express';\n\ndescribe('Authentication', () =\u003e {\n  const auth = CAuth({\n    dbProvider: mockDbProvider,\n    roles: ['user', 'admin'],\n    accessTokenSecret: 'test-secret',\n    refreshTokenSecret: 'test-refresh-secret',\n  });\n\n  it('should register a new user', async () =\u003e {\n    const result = await auth.FN.Register({\n      email: 'test@example.com',\n      password: 'testPassword123',\n      role: 'user',\n    });\n\n    expect(result.success).toBe(true);\n    expect(result.data).toHaveProperty('id');\n  });\n\n  it('should login with valid credentials', async () =\u003e {\n    const result = await auth.FN.Login({\n      email: 'test@example.com',\n      password: 'testPassword123',\n    });\n\n    expect(result.success).toBe(true);\n    expect(result.data).toHaveProperty('tokens');\n  });\n});\n```\n\n## 🤝 Contributing\n\nWe welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.\n\n### Development Setup\n\n```bash\n# Clone the repository\ngit clone https://github.com/jonace-mpelule/cauth-express.git\n\n# Install dependencies\npnpm install\n\n# Run tests\npnpm test\n\n# Build the project\npnpm tsdown\n```\n\n## 📄 License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n## 🆘 Support\n\n- 📖 [Documentation](https://cauth.dev/docs)\n- 🐛 [Issue Tracker](https://github.com/jonace-mpelule/cauth-express/issues)\n\u003c!-- - 💬 [Discord Community](https://discord.gg/cauth) --\u003e\n- 📧 [Email Support](mailto:support@cauth.dev)\n\n## 🗺️ Roadmap\n\n- [ ] **Multi Database Support** - Support Multiple Databases\n- [ ] **2FA Support** - Two-factor authentication\n- [ ] **OAuth Integration** - Google, GitHub, etc.\n- [ ] **Rate Limiting** - Built-in rate limiting\n- [ ] **Session Management** - Advanced session handling\n- [ ] **Audit Logging** - Security event logging\n- [ ] **Frontend SDK** - React, Vue, Angular support\n- [ ] **GraphQL Support** - GraphQL integration\n- [ ] **Microservices** - Distributed authentication\n\n## 🙏 Acknowledgments\n\n- [Prisma](https://prisma.io/) - Database toolkit\n- [JWT](https://jwt.io/) - JSON Web Tokens\n- [bcrypt](https://github.com/kelektiv/node.bcrypt.js) - Password hashing\n- [Express](https://expressjs.com/) - Web framework\n\n---\n\n\u003cdiv align=\"center\"\u003e\n\n**Made with ❤️ by Jonace Mpelule (The Halftone Company)**\n\n[⭐ Star us on GitHub](https://github.com/jonace-mpelule/cauth-express/) | [📖 Read the Docs](https://cauth.dev) | [🐛 Report Issues](https://github.com/jonace-mpelule/cauth-express/issues)\n\n\u003c/div\u003e\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjonace-mpelule%2Fcauth-express","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjonace-mpelule%2Fcauth-express","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjonace-mpelule%2Fcauth-express/lists"}