A comprehensive, production-ready authentication system built with Node.js, TypeScript, Express.js, Prisma, and Redis. This system provides multiple authentication methods including email/password, phone OTP, and Google OAuth, along with robust security features and email services.
- Email + Password Authentication with secure password hashing
- Phone Number Authentication with OTP verification
- Google OAuth 2.0 Integration with Passport.js
- Multi-channel OTP Support (Email & SMS)
- JWT-based Authentication with access and refresh tokens
- Password Security: bcrypt hashing with salt rounds
- JWT Token Management: Separate access and refresh tokens
- Session Management: Secure session handling with Redis
- Rate Limiting: Built-in OTP request rate limiting
- CORS Protection: Configurable CORS settings
- Cookie Security: HTTPOnly, Secure, and SameSite cookies
Support for multiple email providers:
- SendGrid - Production email service
- Mailgun - Alternative email service
- Resend - Modern email API
- Gmail - Gmail SMTP integration
- Custom SMTP - Nodemailer with custom SMTP
- Welcome Email - User onboarding
- OTP Verification - Account verification emails
- Password Reset - Secure password reset links
- Password Changed - Security notifications
- Profile Management - Update user profiles
- Account Verification - Email and phone verification
- Password Management - Change and reset passwords
- Role-based Access - User roles and permissions
- Admin Panel - Administrative functions
- Backend: Node.js, Express.js, TypeScript
- Database: PostgreSQL with Prisma ORM
- Cache/Session Store: Redis
- Authentication: JWT, Passport.js
- Validation: Zod schemas
- Email: Multiple provider support
- Security: bcryptjs, CORS
- Development: Nodemon, ts-node
Before you begin, ensure you have the following installed:
- Node.js (v18 or higher)
- pnpm (v8 or higher) -
npm install -g pnpm - PostgreSQL (v13 or higher)
- Redis (v6 or higher)
- Docker & Docker Compose (optional, for containerized setup)
git clone https://github.com/<your-username>/secure-auth.git
cd secure-authpnpm installCreate a .env file in the root directory:
# Database Configuration
DATABASE_URL="postgresql://your_username:your_password@localhost:5432/your_database"
# Redis Configuration
REDIS_URL="redis://localhost:6379"
# JWT Secrets (Generate secure random strings)
JWT_ACCESS_SECRET="your-super-secret-access-key-min-32-chars"
JWT_REFRESH_SECRET="your-super-secret-refresh-key-min-32-chars"
# Token Expiration
ACCESS_TOKEN_EXPIRES_IN="15m"
REFRESH_TOKEN_EXPIRES_IN="7d"
# Server Configuration
PORT=5000
NODE_ENV="development"
# CORS Configuration
CLIENT_REDIRECT_URL="http://localhost:3000/dashboard"
# Email Service Configuration (Choose one)
EMAIL_PROVIDER="nodemailer" # Options: nodemailer, sendgrid, mailgun, resend, gmail
FROM_EMAIL="Secure Auth <[email protected]>"
# SendGrid (if using SendGrid)
SENDGRID_API_KEY="your-sendgrid-api-key"
# Mailgun (if using Mailgun)
MAILGUN_API_KEY="your-mailgun-api-key"
MAILGUN_DOMAIN="your-mailgun-domain"
# Resend (if using Resend)
RESEND_API_KEY="your-resend-api-key"
# Gmail (if using Gmail)
GMAIL_USER="[email protected]"
GMAIL_APP_PASSWORD="your-gmail-app-password"
# Custom SMTP (if using Nodemailer with custom SMTP)
SMTP_HOST="your-smtp-host"
SMTP_PORT=587
SMTP_USER="your-smtp-username"
SMTP_PASS="your-smtp-password"
# Google OAuth (if using Google authentication)
GOOGLE_CLIENT_ID="your-google-client-id"
GOOGLE_CLIENT_SECRET="your-google-client-secret"
GOOGLE_REDIRECT_URI="http://localhost:5000/api/v1/auth/google/callback"
# SMS Service (for phone OTP - implement as needed)
# TWILIO_ACCOUNT_SID="your-twilio-account-sid"
# TWILIO_AUTH_TOKEN="your-twilio-auth-token"
# TWILIO_PHONE_NUMBER="your-twilio-phone-number"Start PostgreSQL and Redis with Docker Compose:
# Update docker-compose.yml with your credentials first
docker-compose up -dInstall PostgreSQL and Redis locally, then create a database:
CREATE DATABASE your_database;
CREATE USER your_username WITH ENCRYPTED PASSWORD 'your_password';
GRANT ALL PRIVILEGES ON DATABASE your_database TO your_username;# Generate Prisma client
pnpm generate
# Run database migrations
pnpm migrate
# (Optional) Open Prisma Studio to view data
pnpm studiopnpm devThe server will start on http://localhost:5000
secure-auth/
├── prisma/
│ ├── schema.prisma # Database schema
│ └── migrations/ # Database migrations
├── src/
│ ├── controllers/ # Route controllers
│ │ ├── auth.controller.ts
│ │ ├── admin.controller.ts
│ │ └── oauth.controller.ts
│ ├── lib/ # Core libraries
│ │ ├── prisma.ts # Database client
│ │ ├── redis.ts # Redis client
│ │ └── passport.ts # Passport configuration
│ ├── middlewares/ # Express middlewares
│ │ ├── auth.middleware.ts # Authentication middleware
│ │ └── role.middleware.ts # Role-based middleware
│ ├── routes/ # API routes
│ │ ├── auth.route.ts # Authentication routes
│ │ ├── profile.route.ts # Profile management
│ │ └── admin.route.ts # Admin routes
│ ├── services/ # Business logic services
│ │ ├── otpService.ts # OTP generation/verification
│ │ ├── sessionService.ts # Session management
│ │ ├── passwordResetService.ts
│ │ └── emailService/ # Email service providers
│ │ ├── index.ts # Email service factory
│ │ ├── sendTemplatedEmail.ts
│ │ ├── providers/ # Email provider implementations
│ │ ├── templates/ # Email templates
│ │ └── utils/ # Email utilities
│ ├── types/ # TypeScript type definitions
│ │ └── express.d.ts # Express type extensions
│ ├── utils/ # Utility functions
│ │ ├── cookies.ts # Cookie utilities
│ │ ├── crypto.ts # Cryptographic utilities
│ │ └── jwt.ts # JWT utilities
│ ├── validators/ # Zod validation schemas
│ │ ├── authSchema.ts # Authentication validation
│ │ └── adminSchema.ts # Admin validation
│ └── index.ts # Application entry point
├── docker-compose.yml # Docker services
├── package.json # Dependencies and scripts
├── tsconfig.json # TypeScript configuration
└── README.md # This file
Register a new user with email/phone and password.
Request Body:
{
"email": "[email protected]", // Optional (either email or phone required)
"phone": "+1234567890", // Optional (either email or phone required)
"password": "SecurePass123!", // Required for email signup
"name": "John Doe" // Optional
}Response:
{
"message": "OTP sent to your email: [email protected], Please verify your account using the OTP delivered to you.",
"userId": "uuid-here"
}Verify OTP for registration or login.
Request Body:
{
"userId": "uuid-here",
"otp": "123456",
"channel": "email", // "email" or "phone"
"purpose": "REGISTER" // "REGISTER" or "LOGIN"
}Login with email/password or phone (OTP will be sent).
Email + Password:
{
"email": "[email protected]",
"password": "SecurePass123!"
}Phone (OTP):
{
"phone": "+1234567890"
}Resend OTP for verification.
Request Body:
{
"userId": "uuid-here",
"channel": "email", // "email" or "phone"
"purpose": "REGISTER" // "REGISTER" or "LOGIN"
}Request password reset email.
Request Body:
{
"email": "[email protected]"
}Reset password using token from email.
Request Body:
{
"userId": "uuid-here",
"token": "reset-token-here",
"newPassword": "NewSecurePass123!"
}Change password (requires authentication).
Request Body:
{
"currentPassword": "CurrentPass123!",
"newPassword": "NewSecurePass123!"
}Refresh access token using refresh token.
Logout and invalidate tokens.
Redirect to Google OAuth consent screen.
Handle Google OAuth callback.
Get user profile information.
Update user profile.
Request Body:
{
"name": "Updated Name",
"avatarUrl": "https://example.com/avatar.jpg",
"bio": "User bio",
"dateOfBirth": "1990-01-01",
"gender": "MALE", // "MALE", "FEMALE", "OTHER"
"address": "123 Main St",
"phone": "+1234567890"
}Get all users (admin access required).
Choose your preferred email service provider by setting the EMAIL_PROVIDER environment variable:
- Sign up at SendGrid
- Create an API key
- Set environment variables:
EMAIL_PROVIDER="sendgrid"
SENDGRID_API_KEY="your-sendgrid-api-key"
FROM_EMAIL="Your App <[email protected]>"- Sign up at Mailgun
- Get your API key and domain
- Set environment variables:
EMAIL_PROVIDER="mailgun"
MAILGUN_API_KEY="your-mailgun-api-key"
MAILGUN_DOMAIN="your-mailgun-domain"
FROM_EMAIL="Your App <[email protected]>"- Sign up at Resend
- Create an API key
- Set environment variables:
EMAIL_PROVIDER="resend"
RESEND_API_KEY="your-resend-api-key"
FROM_EMAIL="Your App <[email protected]>"- Enable 2-factor authentication on your Gmail account
- Generate an app password
- Set environment variables:
EMAIL_PROVIDER="gmail"
GMAIL_USER="[email protected]"
GMAIL_APP_PASSWORD="your-16-character-app-password"
FROM_EMAIL="Your App <[email protected]>"EMAIL_PROVIDER="nodemailer"
SMTP_HOST="your-smtp-server.com"
SMTP_PORT=587
SMTP_USER="your-smtp-username"
SMTP_PASS="your-smtp-password"
FROM_EMAIL="Your App <[email protected]>"- Go to Google Cloud Console
- Create a new project or select existing
- Enable Google+ API
- Create OAuth 2.0 credentials
- Add authorized redirect URIs:
- Development:
http://localhost:5000/api/v1/auth/google/callback - Production:
https://yourdomain.com/api/v1/auth/google/callback
- Development:
- Set environment variables:
GOOGLE_CLIENT_ID="your-google-client-id"
GOOGLE_CLIENT_SECRET="your-google-client-secret"
GOOGLE_REDIRECT_URI="http://localhost:5000/api/v1/auth/google/callback"The application uses the following main database models:
- User: Core user information and credentials
- Session: JWT refresh token sessions
- Account: OAuth account linking
- VerificationToken: Email/phone verification tokens
- PasswordResetToken: Password reset tokens
- OtpRequest: OTP verification requests
This application implements several security measures:
- Password Security: bcrypt with salt rounds
- JWT Security: Short-lived access tokens, long-lived refresh tokens
- Rate Limiting: OTP request rate limiting
- CORS Protection: Configurable CORS policies
- Input Validation: Zod schema validation
- Cookie Security: HTTPOnly, Secure, SameSite attributes
- Session Management: Redis-based session storage
# Start development server with hot reload
pnpm dev
# Build for production
pnpm build
# Start production server
pnpm start
# Run database migrations
pnpm migrate
# Open Prisma Studio
pnpm studio
# Generate Prisma client
pnpm generate- OTP in Development: In development mode, OTPs are logged to console instead of being sent via email/SMS
- Email in Development: Emails are logged to console with full HTML content for testing
- Hot Reload: The development server uses nodemon for automatic restarts
- Database Changes: Run
pnpm migrateafter schema changes
NODE_ENV="production"
DATABASE_URL="your-production-database-url"
REDIS_URL="your-production-redis-url"
# Use strong, unique secrets
JWT_ACCESS_SECRET="your-production-access-secret"
JWT_REFRESH_SECRET="your-production-refresh-secret"
# Configure your production email provider
EMAIL_PROVIDER="sendgrid"
SENDGRID_API_KEY="your-production-sendgrid-key"
# Production domain
CLIENT_REDIRECT_URL="https://yourdomain.com/dashboard"- Build the application:
pnpm build-
Set production environment variables
-
Run database migrations:
pnpm migrate- Start the production server:
pnpm startBuild and run with Docker:
# Build Docker image
docker build -t secure-auth .
# Run with Docker Compose
docker-compose -f docker-compose.prod.yml up -d- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature - Commit your changes:
git commit -m 'Add amazing feature' - Push to the branch:
git push origin feature/amazing-feature - Open a Pull Request
This project is licensed under the ISC License - see the LICENSE file for details.
-
Database Connection Error
- Verify PostgreSQL is running
- Check DATABASE_URL format
- Ensure database exists
-
Redis Connection Error
- Verify Redis is running
- Check REDIS_URL format
-
Email Not Sending
- Verify email provider credentials
- Check FROM_EMAIL format
- Ensure provider-specific environment variables are set
-
Google OAuth Not Working
- Verify redirect URIs in Google Console
- Check Google Client ID and Secret
- Ensure Google+ API is enabled
-
OTP Not Received
- In development, check console logs
- Verify email provider configuration
- Check spam folder
Enable debug logging by setting:
DEBUG="*"
NODE_ENV="development"For support and questions:
- Create an issue in the GitHub repository
- Check the documentation
- Review existing issues
Built with ❤️ by csfahad