Skip to content

tarinagarwal/MongoDB-Auth

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

3 Commits
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ” Auth Template - Complete Authentication System

A modern, production-ready authentication system built with React, Node.js, Express, Prisma, and MongoDB. Features a beautiful, customizable UI with enterprise-grade security and comprehensive user management.

✨ Features

πŸ”’ Authentication & Security

  • JWT-based Authentication - Secure token-based authentication system
  • Email Verification - OTP-based email verification with configurable settings
  • Password Reset - Secure password reset via email tokens
  • Password Hashing - bcrypt with salt rounds for secure password storage
  • Protected Routes - Client-side route protection with authentication guards
  • Token Refresh - Automatic token validation and refresh handling

🎨 Modern UI/UX

  • Responsive Design - Mobile-first approach with perfect cross-device compatibility
  • Customizable Theme System - Complete design system with CSS custom properties
  • Smooth Animations - Micro-interactions and transitions for enhanced UX
  • Loading States - Comprehensive loading indicators and skeleton screens
  • Error Handling - User-friendly error messages and validation feedback
  • Accessibility - WCAG compliant with proper ARIA labels and keyboard navigation

πŸ“§ Email System

  • SMTP Integration - Configurable email service with Gmail support
  • Beautiful Email Templates - HTML email templates for all communications
  • Email Types:
    • Welcome emails
    • Email verification with OTP
    • Password reset links
    • Account notifications

πŸ› οΈ Developer Experience

  • TypeScript Support - Full type safety across the entire application
  • Hot Reload - Fast development with Vite and Node.js watch mode
  • Database Management - Prisma ORM with MongoDB integration
  • Environment Configuration - Comprehensive environment variable setup
  • Error Logging - Detailed server-side error logging and debugging
  • Database Tools - Built-in database management and cleanup scripts

πŸ—οΈ Architecture

Frontend (Client)

  • React 19 with TypeScript
  • Vite for blazing-fast development and building
  • Tailwind CSS for utility-first styling
  • React Router for client-side routing
  • Axios for HTTP requests with interceptors
  • Lucide React for beautiful icons

Backend (Server)

  • Node.js with Express.js
  • Prisma ORM for database operations
  • MongoDB as the primary database
  • JWT for authentication tokens
  • Nodemailer for email services
  • bcryptjs for password hashing

πŸ“‹ Prerequisites

Before you begin, ensure you have the following installed:

  • Node.js (v18 or higher) - Download here
  • npm or yarn package manager
  • MongoDB database (local or cloud) - MongoDB Atlas
  • Git for version control
  • Gmail account (for email services) or other SMTP provider

πŸš€ Installation & Setup

1. Clone the Repository

git clone https://github.com/tarinagarwal/MongoDB-Auth
cd MongoDB-Auth

2. Install Dependencies

Install Server Dependencies

cd server
npm install

Install Client Dependencies

cd ../client
npm install

3. Environment Configuration

Server Environment Setup

Create a .env file in the server directory:

cd server
cp .env.example .env

Configure your .env file with the following variables:

# Database Configuration
DATABASE_URL="mongodb+srv://<username>:<password>@<cluster-url>/<dbname>?retryWrites=true&w=majority&appName=<clusterName>"

# JWT Configuration
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"
FROM_NAME="Your App Name"

# Server Configuration
PORT=5000
NODE_ENV=development

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

Client Environment Setup

Create a .env file in the client directory:

cd ../client
cp .env.example .env

Configure your client .env file:

# API Configuration
VITE_API_BASE_URL=http://localhost:5000/api

4. Database Setup

Generate Prisma Client

cd server
npm run db:generate

Push Database Schema

npm run db:push

(Optional) Open Prisma Studio

npm run db:studio

5. Gmail App Password Setup (for Email)

  1. Enable 2-Factor Authentication on your Gmail account
  2. Go to Google App Passwords
  3. Generate a new app password for "Mail"
  4. Use this app password in your SMTP_PASS environment variable

6. Start the Development Servers

Start the Backend Server

cd server
npm start

The server will start on http://localhost:5000

Start the Frontend Development Server

cd client
npm run dev

The client will start on http://localhost:5173

🎯 Usage Guide

🎨 Using This Template

This is a complete authentication template designed to be the foundation for your next project. Here's how to get started:

πŸ“¦ What's Included Out of the Box

βœ… Complete Authentication System

  • User registration with email verification
  • Secure login/logout functionality
  • Password reset via email
  • JWT-based session management
  • Protected route system
  • User profile management

βœ… Pre-built Pages & Components

  • Landing Page - Customizable homepage template
  • Authentication Pages - Login, Signup, Verify Email, Reset Password
  • Profile Page - User account management
  • 404 Page - Error handling
  • Responsive Navbar - With user dropdown and mobile menu
  • Protected Route Wrapper - Automatic authentication checks
  • Loading Components - Spinners and loading states
  • Scroll Components - Scroll to top functionality

βœ… App Structure Ready for Expansion

// App.tsx is already structured with:
<Routes>
  {/* Public Routes - Anyone can access */}
  <Route path="/" element={<LandingPage />} />
  <Route path="/login" element={<LoginPage />} />
  <Route path="/signup" element={<SignupPage />} />

  {/* Protected Routes - Requires authentication */}
  <Route
    path="/profile"
    element={
      <ProtectedRoute>
        <ProfilePage />
      </ProtectedRoute>
    }
  />

  {/* Add your protected routes here */}
</Routes>

βœ… Placeholder Navigation Ready

The navbar includes placeholder links that you can customize:

  • Home - Links to landing page
  • About - Ready for your about page
  • Services - Ready for your services page
  • Contact - Ready for your contact page

πŸš€ Quick Start Customization

1. Customize the Landing Page

Replace the template landing page content with your project:

// client/src/pages/LandingPage.tsx
// Replace the hero section, features, and content with your project details

2. Update Navigation Links

// client/src/components/Navbar.tsx
const navigationLinks = [
  { name: "Home", href: "/", icon: Home },
  { name: "Your Page", href: "/your-page", icon: YourIcon },
  // Add your actual navigation items
];

3. Add Your Protected Pages

// In App.tsx, add your protected routes:
<Route
  path="/dashboard"
  element={
    <ProtectedRoute>
      <YourDashboard />
    </ProtectedRoute>
  }
/>

4. Customize the Theme

// client/tailwind.config.js
colors: {
  brand: {
    500: "#your-primary-color", // Change to your brand color
    600: "#your-primary-hover",
    // ... customize all brand colors
  }
}

5. Update Branding

  • Change "Auth Template" to your project name in:
    • client/src/components/Navbar.tsx
    • client/index.html (title)
    • Email templates in server/utils/emailService.js
    • Environment variables (FROM_NAME, etc.)

πŸ—οΈ Template Architecture Benefits

  • Modular Components - Each component has a single responsibility
  • Consistent Theming - Semantic CSS classes for easy customization
  • Type Safety - Full TypeScript implementation
  • Responsive Design - Mobile-first approach
  • Security First - Enterprise-grade authentication
  • Developer Experience - Hot reload, error handling, loading states

πŸ“ Next Steps After Setup

  1. Replace Landing Page - Update with your project's value proposition
  2. Add Your Pages - Create pages specific to your application
  3. Update Navigation - Replace placeholder links with real ones
  4. Customize Theme - Match your brand colors and styling
  5. Configure Email - Update email templates with your branding
  6. Add Features - Build your core application features
  7. Deploy - Use the included deployment guides

This template gives you a production-ready foundation so you can focus on building your unique features instead of authentication boilerplate!


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

🎨 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").

πŸ›‘οΈ 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

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 MongoDB connection string in .env
  • Ensure database is running and accessible
  • Check network connectivity for cloud databases

Email Not Sending

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

Build Errors

  • Clear node_modules and reinstall dependencies
  • Ensure Node.js version compatibility (v18+)
  • Check for TypeScript errors in the console

Authentication Issues

  • Verify JWT_SECRET is set in server .env
  • Check token expiration settings
  • Clear localStorage and try logging in again

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. Reach me out at tarinagarwal@gmail.com

Built with ❀️ for the developer community

Happy coding! πŸš€

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors