Skip to content

tarinagarwal/CockroachDB-Auth

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 

Repository files navigation

🔐 Authentication Template with Admin Panel

A complete, production-ready authentication system built with React, Node.js, CockroachDB, Prisma, and AdminJS. Features a comprehensive admin panel, enterprise-grade database, and Redis session management.

✨ Features

🔐 Complete Authentication System

  • User registration with email verification (OTP-based)
  • Secure login/logout with JWT tokens
  • Password reset functionality via email
  • Protected routes and middleware
  • Input validation and sanitization
  • bcrypt password hashing

🛠️ Comprehensive Admin Panel

  • AdminJS Integration - Full-featured admin interface
  • Dynamic Model Discovery - Automatically detects new Prisma models
  • User Management - View, edit, and manage user accounts
  • Data Operations - Complete CRUD operations for all models
  • Security Controls - Role-based access and data protection
  • Redis Sessions - Persistent session management
  • Custom Branding - Configurable admin panel appearance

🗄️ Enterprise Database & Infrastructure

  • CockroachDB - Distributed SQL database with automatic scaling
  • Prisma ORM - Type-safe database operations
  • Redis Cloud - Session storage and caching
  • Email Service - SMTP integration for notifications
  • Environment Configuration - Secure credential management

🎨 Modern Frontend

  • React 18 with TypeScript
  • Tailwind CSS with custom theme system
  • Responsive design (mobile-first)
  • Loading states and error handling
  • Form validation with real-time feedback
  • Modern UI components and animations

🚀 Quick Start

Prerequisites

1. Clone and Install

git clone <your-repo-url>
cd auth-template

# Install server dependencies
cd server
npm install

# Install client dependencies
cd ../client
npm install

2. Database Setup (CockroachDB)

  1. Create CockroachDB Cluster:

    • Go to CockroachDB Cloud
    • Create a new cluster (free tier available)
    • Download the connection certificate
    • Get your connection string
  2. Setup Environment Variables:

    cd server
    cp .env.example .env
  3. Configure Database URL in .env:

    DATABASE_URL="postgresql://username:password@host:port/database?sslmode=require"
  4. Initialize Database:

    npm run db:push
    npm run db:generate

3. Redis Setup (Session Storage)

  1. Create Redis Database:

    • Go to Redis Cloud
    • Create a new database
    • Get your connection URL
  2. Add Redis URL to .env:

    REDIS_URL="redis://username:password@host:port"

4. Email Configuration

  1. Setup Gmail App Password:

    • Enable 2FA on your Gmail account
    • Generate an App Password
    • Use this password (not your regular Gmail password)
  2. Configure Email in .env:

    SMTP_HOST="smtp.gmail.com"
    SMTP_PORT=587
    SMTP_USER="your-email@gmail.com"
    SMTP_PASS="your-app-password"
    FROM_EMAIL="your-email@gmail.com"
    FROM_NAME="Your App Name"

5. Complete Server Configuration

Update your server/.env file with all required variables:

# Database
DATABASE_URL="postgresql://username:password@host:port/database?sslmode=require"

# JWT
JWT_SECRET="your-super-secret-jwt-key-change-this-in-production"
JWT_EXPIRES_IN="7d"

# Email Configuration
EMAIL_VERIFICATION_ENABLED=true
SMTP_HOST="smtp.gmail.com"
SMTP_PORT=587
SMTP_USER="your-email@gmail.com"
SMTP_PASS="your-app-password"
FROM_EMAIL="your-email@gmail.com"
FROM_NAME="Your App Name"

# Server
PORT=5000
NODE_ENV=development

# Frontend URL (for email links)
FRONTEND_URL="http://localhost:5173"

# Redis Configuration
REDIS_URL="redis://username:password@host:port"

# AdminJS
ADMIN_EMAIL="admin@example.com"
ADMIN_PASSWORD="admin123"

6. Client Configuration

cd client
cp .env.example .env

Update client/.env:

VITE_API_BASE_URL=http://localhost:5000/api

7. Start the Application

# Start server (from server directory)
npm run dev

# Start client (from client directory, in new terminal)
npm run dev

🔧 Admin Panel Usage

Accessing the Admin Panel

  1. Start your server (npm run dev in server directory)
  2. Navigate to http://localhost:5000/admin
  3. Login with admin credentials:

⚠️ Important: Change these default credentials in production!

Admin Panel Features

User Management

  • View all registered users
  • Edit user profiles and verification status
  • Monitor user activity and registration dates
  • Bulk operations and filtering

Dynamic Model Management

  • Auto-Discovery: New Prisma models appear automatically
  • CRUD Operations: Create, read, update, delete for all models
  • Relationship Handling: Manage model relationships
  • Data Validation: Built-in validation for all fields

Security Features

  • Protected Fields: Sensitive data (passwords, tokens) are hidden
  • Role-Based Access: Configurable admin permissions
  • Session Management: Redis-powered persistent sessions
  • Audit Trail: Track data changes and admin actions

Adding New Models

To add a new model to your application:

  1. Update Prisma Schema (server/prisma/schema.prisma):

    model Product {
      id          String   @id @default(uuid())
      name        String
      description String?
      price       Float
      createdAt   DateTime @default(now())
      updatedAt   DateTime @updatedAt
    }
  2. Push to Database:

    npm run db:push
    npm run db:generate
  3. Restart Server - The new model automatically appears in AdminJS!

🎯 Usage Guide

User Registration Flow

  1. User visits /signup and fills out the registration form
  2. If email verification is enabled:
    • User receives a 6-digit OTP via email
    • User enters OTP on /verify-email page
    • Account is activated after successful verification
  3. If email verification is disabled:
    • User is automatically logged in after registration

Authentication Flow

  1. User logs in via /login with email/username and password
  2. Server validates credentials and returns JWT token
  3. Token is stored in localStorage and used for authenticated requests
  4. Protected routes automatically redirect unauthenticated users to login

Password Reset Flow

  1. User clicks "Forgot Password" on login page
  2. User enters email address on /forgot-password
  3. System sends password reset email with secure token
  4. User clicks email link and is redirected to /reset-password/:token
  5. User enters new password and account is updated

Admin Panel Usage

  1. Navigate to /admin on your server URL
  2. Login with admin credentials
  3. Manage users, view data, and perform CRUD operations
  4. All Prisma models are automatically available in the admin panel
  5. Add new models to your schema and they'll appear automatically
  6. Run this whenever you change anything in your schema to update your admin panel automatically
npx prisma generate

🎨 Customization

Theme Customization

The application uses a comprehensive theme system built with Tailwind CSS. You can customize the entire appearance by modifying the theme configuration:

1. Color Scheme

Edit client/tailwind.config.js to change the color palette:

colors: {
  brand: {
    500: "#your-primary-color", // Main brand color
    600: "#your-primary-hover", // Primary hover color
    // ... other shades
  },
  // ... other color configurations
}

2. Typography

Modify font families and sizes in the same config file:

fontFamily: {
  primary: ["Your-Font", "system-ui", "sans-serif"],
},

3. Component Styling

The theme system uses semantic CSS classes in client/src/index.css. Modify these classes to change component appearances:

.theme-btn-primary {
  /* Your custom button styles */
}

.theme-card {
  /* Your custom card styles */
}

Email Template Customization

Email templates are located in server/utils/emailService.js. Each email function contains HTML templates that you can customize:

  • sendVerificationEmail() - Email verification template
  • sendWelcomeEmail() - Welcome email template
  • sendPasswordResetEmail() - Password reset template

Feature Configuration

Disable Email Verification

Set EMAIL_VERIFICATION_ENABLED=false in your server .env file to allow immediate login after registration.

Customize Token Expiration

Modify JWT_EXPIRES_IN in your server .env file (e.g., "1d", "7d", "30d").

Customize Admin Panel

  • Change Branding: Modify the branding object in server/admin.js
  • Add Custom Actions: Extend model configurations in getDefaultModelOptions()
  • Custom Pages: Add custom pages and components to AdminJS
  • Security: Update admin credentials in your .env file

🛡️ Security Features

Password Security

  • bcrypt Hashing - Passwords are hashed with salt rounds
  • Minimum Length - 6 character minimum password requirement
  • Secure Reset - Time-limited password reset tokens

Token Security

  • JWT Tokens - Stateless authentication with configurable expiration
  • Secure Storage - Tokens stored in localStorage with automatic cleanup
  • Token Validation - Server-side token verification on protected routes

Email Security

  • OTP Verification - 6-digit one-time passwords for email verification
  • Time-Limited Tokens - All email tokens expire after set time periods
  • Secure Links - Password reset links contain cryptographically secure tokens

Admin Panel Security

  • Separate Authentication - Admin panel has its own authentication system
  • Session Management - Redis-based session storage for production
  • Role-Based Access - Configurable admin access controls
  • Data Protection - Sensitive fields (passwords, tokens) are hidden by default

Input Validation

  • Client-Side Validation - Real-time form validation with user feedback
  • Server-Side Validation - Comprehensive input sanitization and validation
  • SQL Injection Protection - Prisma ORM provides built-in protection

🤝 Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

🆘 Troubleshooting

Common Issues

Database Connection Issues

  • Verify CockroachDB connection string in .env
  • Ensure database cluster is running and accessible
  • Check network connectivity for cloud databases
  • Verify SSL certificates are properly configured

Admin Panel Issues

  • Verify Redis connection if using Redis Cloud
  • Check admin credentials in .env file
  • Ensure server is running on correct port
  • Clear browser cache and cookies
  • Check console for JavaScript errors

Email Not Sending

  • Verify SMTP credentials in .env
  • Check Gmail app password setup
  • Ensure 2FA is enabled on Gmail account
  • Check spam/junk folders
  • Verify SMTP host and port settings

Build Errors

  • Clear node_modules and reinstall dependencies
  • Ensure Node.js version compatibility (v18+)
  • Check for TypeScript errors in the console
  • Verify all environment variables are set

Authentication Issues

  • Verify JWT_SECRET is set in server .env
  • Check token expiration settings
  • Clear localStorage and try logging in again
  • Ensure database is accessible and user exists

Getting Help

If you encounter issues:

  1. Check the troubleshooting section above
  2. Review server logs for error messages
  3. Verify all environment variables are set correctly
  4. Ensure all dependencies are installed
  5. Check database connectivity and admin panel access
  6. Reach me out at tarinagarwal@gmail.com

For additional support, please open an issue in the repository with:

  • Error messages from console/logs
  • Steps to reproduce the issue
  • Environment details (Node.js version, OS, etc.)

Built with ❤️ for the developer community

Happy coding! 🚀

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published