Web Design AI Logo

Lesson 3: Testing, Debugging & Authentication Implementation

Test Flask application locally, debug common errors with AI assistance, fix modal jumping issues, implement employee login/logout system with session management, create dashboard, and secure routes with authentication decorators.

Lesson Objectives

  • Change Flask development server port to resolve conflicts
  • Test and debug blueprint errors using AI error analysis
  • Fix modal jumping issues by moving modals outside loops
  • Implement employee login/logout system with Flask-Login
  • Create dashboard page with authentication redirect
  • Add login_required decorators to protect routes
  • Prevent back button navigation after logout with cache control

Watch: Testing, Debugging & Authentication Implementation

Testing, Debugging & Authentication Implementation - Notes

Changing Flask Development Server Port

Resolve port conflicts by changing the Flask development server port when port 5000 is already in use by another process.

Port conflict resolution with AI:

# Issue: Port 5000 is already in use
# Instead of restarting computer, change port with AI

# AI prompt:
"Change the port to 5010 that this is going to run on locally"

# Claude will automatically:
# 1. Locate app.py file
# 2. Add port configuration
# 3. Update Flask run command

Updated app.py configuration:

# Claude adds to app.py:
if __name__ == '__main__':
app.run(debug=True, port=5010)

# Run Flask application:
python app.py

# Server will start on port 5010:
# * Running on http://127.0.0.1:5010

Testing the application:

# In browser, navigate to:
http://localhost:5010

# Application should load on new port
# Avoid port conflicts without system restart

Debugging Blueprint Errors with AI

Use AI-assisted error analysis to quickly identify and fix blueprint errors in Flask applications.

First error: Missing navigation link

# Error appears when accessing home page
# Copy entire error message from browser or console

# AI debugging prompt:
"Check this error" + [paste error message]

# Common issue: Template references non-existent route
# Claude will:
# 1. Search through template files
# 2. Locate error in index.html or base.html
# 3. Identify incorrect href or route reference
# 4. Fix the template automatically

Second error: DateTime import missing

# Error appears when accessing Orders page
# Symptom: Orders route throws import error

# Copy error line (stays highlighted even when scrolling)
# Ctrl+C to copy highlighted error
# Paste into Claude prompt

# AI prompt:
"When I click on the orders page" + [paste error]

# Claude diagnoses:
# - Missing datetime import in orders.py
# - Adds: from datetime import datetime
# - Updates date handling in routes

# Refresh browser - error resolved

This AI-assisted debugging approach saves significant troubleshooting time compared to manual error investigation.

Fixing Modal Jumping Issues

Resolve modal placement issues that cause modals to jump around the screen when triggered from table rows.

Problem identification:

# Test each blueprint's modals:
# Pizzas - Add modal: Works correctly
# Pizzas - Edit modal: Works correctly
# Pizzas - Delete modal: Works correctly
# Orders - Add item modal: JUMPS around screen

# Modal jumping indicates incorrect placement in HTML

AI prompt for fixing modal issues:

# Tell Claude:
"When I click to add an item to an order,
the modal jumps all over the place.
Use the modals from add pizza and edit and delete pizza
as an example to fix the jumping modals."

Root cause and solution:

# Problem: Modals placed inside table loops
# When modal is inside <tr> or card loop:
# - Modal tries to render within table row
# - Causes positioning conflicts
# - Results in jumping/flickering behavior

# Solution: Move modals outside container
# Claude will:
# 1. Identify modals placed inside loops
# 2. Move all modals outside main container
# 3. Update modal triggers to reference external modals

# Result:
# - Modals load on top of entire page
# - No jumping or positioning issues
# - Consistent behavior across all CRUD operations

This fix was discovered by a student in class and demonstrates proper modal placement outside iteration loops.

Implementing Employee Login System

Build a complete authentication system using the employee table from the database schema with Flask-Login integration.

AI prompt for authentication implementation:

# Tell Claude:
"I want employees to log in to use the system.
Use the employee database in the schema
to build the login and logout routes and blueprints and templates."

# Claude will:
# 1. Read schema.sql to find employee table structure
# 2. Identify fields: user_id, username, first_name, last_name, password
# 3. Check seed.sql for existing employee records (4 employees seeded)
# 4. Generate authentication blueprint
# 5. Create login template
# 6. Register blueprint in app.py

Authentication components created:

# File: blueprints/auth.py
# - Flask-Login setup with LoginManager
# - User loader function
# - Login route with password verification
# - Logout route with session cleanup
# - Password hashing with werkzeug.security

# File: templates/login.html
# - Bootstrap login form
# - Username and password fields
# - Error message display
# - Redirect to dashboard after login

# File: app.py updates
# - Import auth blueprint
# - Register auth blueprint
# - Configure Flask-Login
# - Set secret key for sessions

The employee table from the schema provides the foundation for the authentication system with pre-seeded employee accounts.

Creating Dashboard and Login Workflow

Build a dashboard as the landing page after login and configure the index page as the login entry point.

Dashboard creation prompt:

# Tell Claude:
"Create a dashboard for the login page to redirect to.
Use the index page as the login page."

# Claude will:
# 1. Create new dashboard route and template
# 2. Convert index.html to login page
# 3. Set login redirect to dashboard
# 4. Update navigation for authenticated users

Login credential display for development:

# Important for grading and testing:
# Tell Claude:
"Add the demo username and pass to the login page so we can see it"

# Claude adds credential display on login page
# Shows: Username: admin, Password: admin123

# Further improvement - prefill for convenience:
"Preload them into the login form to make it easy to get in"

# Claude will:
# - Add value="admin" to username input
# - Add value="admin123" to password input
# - Display credentials below form for reference
# - One-click login for testing

Troubleshooting login credentials:

# If login fails with seeded credentials:
# Tell Claude: "admin and admin123 did not work"

# Claude will:
# 1. Check seed.sql for actual passwords
# 2. Verify password hashing implementation
# 3. May need to re-run seed script
# 4. Update login page with correct credentials

# Claude may create Python script to update employee records
# with correct username/password combination

Navigation structure after login:

  • Dashboard - Landing page after login
  • Pizzas - Pizza management
  • Customers - Customer management
  • Orders - Order management
  • Admin User - Profile/settings
  • Logout - End session

Securing Routes with Login Decorators

Protect all application routes with authentication decorators and prevent unauthorized access through back button navigation after logout.

Adding login_required decorators:

# AI prompt for route protection:
"Add the decorators to all the routes to require the login.
Also prevent the back button from accessing pages
when the logout button is clicked."

# Decorator explanation:
# @login_required decorator (@ symbol)
# - Placed above route functions
# - Checks if user is authenticated
# - Redirects to login if not authenticated
# - Protects sensitive routes from unauthorized access

Implementation steps Claude performs:

# Claude automatically:
# 1. Imports login_required from Flask-Login
# 2. Adds @login_required to all protected routes:
# - Customers routes (list, add, edit, delete)
# - Pizzas routes (list, add, edit, delete)
# - Orders routes (list, add, edit, delete, view details)
# - Dashboard route
# - Admin/profile routes

# Example decorator usage:
@app.route('/customers')
@login_required
def customers():
# Route logic here
pass

Cache control for back button prevention:

# Problem: After logout, back button can access cached pages
# Solution: Add cache control headers

# Claude adds to logout route and protected routes:
@app.after_request
def add_cache_headers(response):
response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'
response.headers['Pragma'] = 'no-cache'
response.headers['Expires'] = '0'
return response

# These headers:
# - Prevent browser from caching protected pages
# - Force browser to request fresh page from server
# - Back button redirects to login instead of cached page

Testing authentication security:

# Test procedure:
# 1. Refresh browser (clears session)
# 2. Redirects to login page
# 3. Login with prefilled credentials
# 4. Access Customers, Orders, Pizzas (all work)
# 5. Click Logout
# 6. Press browser back button
# 7. Verify: Cannot access protected pages
# 8. Redirected back to login page

# Expected behavior:
# - Back button does NOT bypass logout
# - Session is properly cleared
# - All routes require fresh authentication

This security implementation ensures users cannot circumvent logout by using browser navigation buttons.

Deployment Testing and Final Verification

Push completed application to GitHub for automatic Heroku deployment and verify production functionality.

Pushing to GitHub with AI:

# AI prompt:
"Push to GitHub"

# Claude will:
# 1. Stage all changes (git add .)
# 2. Create commit message
# 3. Ask for permission to push
# 4. Execute: git push origin main

# Permission prompts:
# - First confirmation: Do you want to proceed?
# - Second confirmation: Final push confirmation
# - Click Yes/Allow for each prompt

Monitoring Heroku deployment:

# After GitHub push:
# 1. Navigate to Heroku dashboard
# 2. Click on M5-demo01 app
# 3. Go to 'Activity' tab
# 4. Watch build progress in real-time

# Build status indicators:
# - Building: Code is being deployed
# - Succeeded: Deployment complete
# - Failed: Check build logs for errors

# While building:
# - Can open app (won't load yet)
# - Will show application error initially
# - Once build completes, app becomes accessible

Production testing checklist:

  • Login page loads with prefilled credentials
  • Authentication works (login redirects to dashboard)
  • All blueprints accessible (Customers, Pizzas, Orders)
  • CRUD operations work (Add, Edit, Delete via modals)
  • Modals display correctly (no jumping)
  • Foreign key dropdowns populate correctly
  • Order details view shows proper data
  • Logout works and clears session
  • Back button after logout redirects to login
  • Database connections work in production

Lesson 3 completes the core Pizza Management System with full CRUD operations, authentication, and security features ready for production use.