Skip to content

angular for the frontend - add authentication - crud operations adonis js for backend - postgres as database docker

License

Notifications You must be signed in to change notification settings

log1cakez/todo_list_angular

Repository files navigation

Todo List App

A full-stack todo list application with JWT authentication, built with AngularJS frontend, AdonisJS backend, and PostgreSQL database, all containerized with Docker.

✨ Features

  • πŸ” JWT Authentication: Secure register, login, and logout functionality
  • πŸ“ CRUD Operations: Create, read, update, and delete todos
  • ⚑ Real-time Updates: Update todos with optimistic UI feedback
  • πŸ” Search & Filter: Search todos and filter by completion status
  • πŸ“Š Statistics: View total, completed, and pending todo counts
  • πŸ“± Responsive Design: Modern UI with Bootstrap 5
  • 🐳 Docker Ready: Complete containerization setup
  • πŸ’Ύ Database Persistence: PostgreSQL with proper migrations
  • πŸ›‘οΈ Route Protection: Secure frontend routing with authentication guards
  • ⏰ Timestamps: Display creation and update times for todos

πŸ› οΈ Tech Stack

Frontend

  • AngularJS 1.8.3: Single-page application framework
  • Bootstrap 5: Responsive UI framework
  • Font Awesome: Icons
  • Nginx: Web server for production
  • JWT Authentication: Secure token-based authentication

Backend

  • AdonisJS 6: Node.js web framework
  • TypeScript: Type-safe JavaScript
  • Lucid ORM: Database ORM
  • JWT Authentication: Secure token-based authentication
  • Custom JWT Middleware: Token validation and user context

Database

  • PostgreSQL 15: Relational database
  • Migrations: Database schema management

Infrastructure

  • Docker: Containerization
  • Docker Compose: Multi-container orchestration

πŸ“ Project Structure

todo_list_angular/
β”œβ”€β”€ backend/                 # AdonisJS backend
β”‚   β”œβ”€β”€ app/
β”‚   β”‚   β”œβ”€β”€ controllers/     # API controllers (Auth, Todos)
β”‚   β”‚   β”œβ”€β”€ models/          # Database models (User, Todo)
β”‚   β”‚   β”œβ”€β”€ middleware/      # Custom middleware (JWT, Auth)
β”‚   β”‚   β”œβ”€β”€ services/        # Business logic (JWT Service)
β”‚   β”‚   └── validators/      # Request validators
β”‚   β”œβ”€β”€ config/              # Configuration files
β”‚   β”œβ”€β”€ database/
β”‚   β”‚   └── migrations/      # Database migrations
β”‚   β”œβ”€β”€ start/
β”‚   β”‚   β”œβ”€β”€ routes.ts        # API routes
β”‚   β”‚   └── kernel.ts        # Middleware configuration
β”‚   └── Dockerfile
β”œβ”€β”€ frontend/                # AngularJS frontend
β”‚   β”œβ”€β”€ app/
β”‚   β”‚   └── views/           # HTML templates (Login, Register, Todos)
β”‚   β”œβ”€β”€ js/
β”‚   β”‚   β”œβ”€β”€ controllers/     # AngularJS controllers
β”‚   β”‚   └── services/        # API services (Auth, Todo, Test)
β”‚   β”œβ”€β”€ css/                 # Custom styles
β”‚   β”œβ”€β”€ index.html           # Main application entry point
β”‚   └── Dockerfile
β”œβ”€β”€ docker-compose.yml       # Docker orchestration
β”œβ”€β”€ docker-compose.prod.yml  # Production Docker configuration
β”œβ”€β”€ docker-restart.bat       # Windows Docker restart script
β”œβ”€β”€ docker-restart.sh        # Linux/Mac Docker restart script
β”œβ”€β”€ start.bat               # Windows startup script
β”œβ”€β”€ start.sh                # Linux/Mac startup script
└── README.md

πŸš€ Quick Start

Prerequisites

  • Docker and Docker Compose installed
  • Git

Installation

  1. Clone the repository

    git clone <repository-url>
    cd todo_list_angular
  2. Start the application

    # Windows
    start.bat
    
    # Linux/Mac
    ./start.sh
    
    # Or manually
    docker-compose up --build
  3. Access the application

First Time Setup

  1. Register a new account at http://localhost:8080/register
  2. Login with your credentials
  3. Start creating todos!

πŸ”§ Development

Backend Development

  1. Navigate to backend directory

    cd backend
  2. Install dependencies

    npm install
  3. Set up environment

    cp .env.example .env
    # Edit .env with your database credentials
  4. Generate APP_KEY (if not already done)

    node ace generate:key
  5. Run migrations

    node ace migration:run
  6. Start development server

    npm run dev

Available AdonisJS Commands

  • node ace migration:run - Run pending migrations
  • node ace migration:rollback - Rollback last migration
  • node ace migration:status - Check migration status
  • node ace make:controller <name> - Create new controller
  • node ace make:model <name> - Create new model
  • node ace make:migration <name> - Create new migration
  • node ace make:validator <name> - Create new validator
  • npm run dev - Start development server with hot reload
  • npm run build - Build for production

Frontend Development

  1. Navigate to frontend directory

    cd frontend
  2. Install dependencies

    npm install
  3. Start development server

    npm start

πŸ”Œ API Endpoints

Authentication

  • POST /api/auth/register - Register new user
  • POST /api/auth/login - Login user (returns JWT token)
  • POST /api/auth/logout - Logout user
  • GET /api/auth/me - Get current user info

Todos (Protected Routes - Requires JWT)

  • GET /api/todos - Get all todos for authenticated user
  • POST /api/todos - Create new todo
  • GET /api/todos/:id - Get specific todo
  • PUT /api/todos/:id - Update todo
  • DELETE /api/todos/:id - Delete todo

Health Check

  • GET / - API health check
  • GET /api/test - Backend connectivity test

πŸ—„οΈ Database Schema

Users Table

  • id (Primary Key)
  • fullName (String)
  • email (String, Unique)
  • password (String, Hashed)
  • created_at (Timestamp)
  • updated_at (Timestamp)

Todos Table

  • id (Primary Key)
  • title (String)
  • description (Text, Optional)
  • completed (Boolean)
  • user_id (Foreign Key to Users)
  • created_at (Timestamp)
  • updated_at (Timestamp)

🐳 Docker Setup

Prerequisites

  • Docker Desktop (Windows/Mac) or Docker Engine (Linux)
  • Docker Compose
  • Node.js 20+ (for local development)

Quick Start

Option 1: Using Setup Scripts (Recommended)

Windows:

# Start development environment
docker-setup.bat dev

# Start production environment
docker-setup.bat prod

# Stop all containers
docker-setup.bat stop

# View logs
docker-setup.bat logs

# Run database migrations
docker-setup.bat migrate

# Clean up everything
docker-setup.bat cleanup

Linux/Mac:

# Make script executable (first time only)
chmod +x docker-setup.sh

# Start development environment
./docker-setup.sh dev

# Start production environment
./docker-setup.sh prod

# Stop all containers
./docker-setup.sh stop

# View logs
./docker-setup.sh logs

# Run database migrations
./docker-setup.sh migrate

# Clean up everything
./docker-setup.sh cleanup

Option 2: Manual Docker Commands

Development Environment:

# Start all services
docker-compose up --build -d

# View logs
docker-compose logs -f

# Stop services
docker-compose down

Production Environment:

# Start production services
docker-compose -f docker-compose.prod.yml up --build -d

# View logs
docker-compose -f docker-compose.prod.yml logs -f

# Stop services
docker-compose -f docker-compose.prod.yml down

Services

Development Environment

Production Environment

  • Application: http://localhost (Nginx)
  • Backend API: Internal (via Nginx proxy)
  • Database: Internal (PostgreSQL)

Environment Configuration

  1. Backend Environment: Copy backend/.env.example to backend/.env and update the values:

    cp backend/.env.example backend/.env
  2. Important: Update the APP_KEY in backend/.env with a secure random string:

    # Generate a secure key
    node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"

Database Setup

The database will be automatically created and migrations will run on first startup. The Docker containers now include automatic migration execution:

# Automatic migrations (recommended)
# Migrations run automatically when containers start

# Manual migration execution (if needed)
# Development
docker-compose exec backend node ace migration:run

# Production
docker-compose -f docker-compose.prod.yml exec backend node ace migration:run

# Force rebuild with fresh migrations
docker-restart.bat  # Windows
./docker-restart.sh  # Linux/Mac

Health Checks

All services include health checks:

  • PostgreSQL: Checks database connectivity
  • Backend: Checks AdonisJS health endpoint
  • Frontend: Checks Nginx response

Troubleshooting

  1. Database Migration Issues: If you see "relation does not exist" errors:

    # Use the restart script to rebuild with migrations
    docker-restart.bat  # Windows
    ./docker-restart.sh  # Linux/Mac
    
    # Or manually rebuild
    docker-compose down
    docker-compose build --no-cache
    docker-compose up -d
  2. Port Conflicts: If ports 80, 8080, 3333, or 5432 are in use, modify the port mappings in docker-compose.yml

  3. Database Connection Issues: Ensure PostgreSQL is healthy before starting the backend:

    docker-compose ps
  4. Build Issues: Clean up and rebuild:

    docker-compose down -v
    docker system prune -f
    docker-compose up --build
  5. View Service Logs:

    # All services
    docker-compose logs -f
    
    # Specific service
    docker-compose logs -f backend
    docker-compose logs -f frontend
    docker-compose logs -f postgres
  6. Node.js Version Issues: If you see "Invalid regular expression flags" errors:

    # Ensure you're using Node.js 20+
    node --version
    
    # The Docker setup uses Node.js 20 automatically
    # For local development, upgrade to Node.js 20+

πŸ” Authentication Flow

  1. Registration/Login β†’ Backend validates credentials
  2. JWT Token Generated β†’ Secure token with user info
  3. Token Stored β†’ Frontend stores token in cookies
  4. API Requests β†’ Token sent in Authorization header
  5. Middleware Validation β†’ Backend validates token on protected routes
  6. User Context β†’ Authenticated user available in controllers

🌍 Environment Variables

Backend (.env)

PORT=3333
HOST=0.0.0.0
NODE_ENV=development
DB_CONNECTION=pg
DB_HOST=postgres
DB_PORT=5432
DB_USER=todo_user
DB_PASSWORD=todo_password
DB_DATABASE=todo_db
APP_KEY=your-secret-app-key-here
SESSION_DRIVER=cookie

πŸš€ Production Deployment

  1. Update environment variables for production

  2. Build and start containers

    docker-compose -f docker-compose.yml up --build -d
  3. Set up reverse proxy (Nginx/Apache) for SSL and domain routing

πŸ› Troubleshooting

Common Issues

  1. Database connection errors

    • Ensure PostgreSQL container is running: docker-compose up postgres -d
    • Check database credentials in .env file
    • Verify database exists: docker-compose exec postgres psql -U todo_user -d todo_db
  2. Migration errors

    • Make sure database is running first
    • Check if migrations are pending: node ace migration:status
    • Run migrations: node ace migration:run
  3. Frontend not loading

    • Verify backend API is accessible at http://localhost:3333
    • Check browser console for errors
    • Ensure CORS is properly configured
  4. Authentication issues

    • Clear browser cookies
    • Check JWT token in browser dev tools
    • Verify APP_KEY is set in .env file
    • Check backend console for JWT middleware logs
  5. 401 Unauthorized errors

    • Verify JWT token is being sent in Authorization header
    • Check if token is expired
    • Ensure user exists in database
    • Check backend JWT middleware logs
  6. Time not displaying

    • Check browser console for date formatting errors
    • Verify todo data structure in network tab
    • Check if created_at field is present in API response

Logs

# View all logs
docker-compose logs

# View specific service logs
docker-compose logs backend
docker-compose logs frontend
docker-compose logs postgres

# Follow logs in real-time
docker-compose logs -f backend

πŸ§ͺ Testing

Backend Testing

cd backend
npm test

Frontend Testing

cd frontend
npm test

Manual Testing

  1. Authentication Flow

    • Register new user
    • Login with credentials
    • Verify JWT token is stored
    • Test logout functionality
  2. Todo Operations

    • Create new todos
    • Edit existing todos
    • Update todo completion status
    • Delete todos
    • Test search and filtering
  3. Route Protection

    • Try accessing todos without authentication
    • Verify redirect to login page
    • Test authenticated access to todos

πŸ“ˆ Performance Features

  • Optimistic Updates: Immediate UI feedback for better UX
  • JWT Token Caching: Efficient authentication state management
  • Database Indexing: Optimized queries for user-specific todos
  • Responsive Design: Works on all device sizes
  • Error Handling: Comprehensive error management and user feedback

πŸ”’ Security Features

  • JWT Authentication: Secure token-based authentication
  • Password Hashing: Bcrypt password encryption
  • Route Protection: Frontend and backend route guards
  • CORS Configuration: Proper cross-origin resource sharing
  • Input Validation: Request validation on all endpoints
  • SQL Injection Protection: ORM-based database queries

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Test thoroughly
  5. Submit a pull request

πŸ“„ License

This project is licensed under the ISC License - see the LICENSE file for details.

πŸ†˜ Support

For support and questions, please open an issue in the repository.

🎯 Recent Updates

  • βœ… Fixed JWT authentication flow
  • βœ… Resolved 401 Unauthorized errors
  • βœ… Fixed "Loading application..." issue
  • βœ… Implemented proper time display
  • βœ… Added comprehensive error handling
  • βœ… Improved route protection
  • βœ… Enhanced debugging and logging
  • βœ… Optimized authentication state management
  • βœ… Fixed Docker database migration issues
  • βœ… Added automatic migration execution on container startup
  • βœ… Created Docker restart scripts for easier troubleshooting
  • βœ… Removed checkbox UI element from todo items
  • βœ… Streamlined todo completion status management

About

angular for the frontend - add authentication - crud operations adonis js for backend - postgres as database docker

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published