---
phase: 01-setup-and-authentication
plan: 03
type: execute
wave: 1
depends_on: []
files_modified: 
  - src/app/api/auth/verify-email/route.ts
  - src/app/api/auth/send-verification-email/route.ts
  - src/middleware.ts
  - src/components/EmailVerificationForm.tsx
  - src/lib/email-service.ts
autonomous: true
must_haves:
  truths:
    - User can resend email verification if needed
    - User session persists across browser refresh
    - Protected routes are properly secured
    - Authentication middleware works correctly
  artifacts:
    - path: "src/app/api/auth/send-verification-email/route.ts"
      provides: "POST endpoint for resending email verification"
      exports: ["POST"]
    - path: "src/middleware.ts"
      provides: "Authentication middleware for protecting routes"
      min_lines: 30
    - path: "src/lib/email-service.ts"
      provides: "Email service utility for sending emails"
      min_lines: 20
  key_links:
    - from: "src/app/api/auth/send-verification-email/route.ts"
      to: "src/lib/email-service.ts"
      via: "email sending functionality"
      pattern: "emailService\\.(sendEmail)"
    - from: "src/middleware.ts"
      to: "src/app/api/auth/verify-email/route.ts"
      via: "session validation"
      pattern: "middleware.*verify.*email"
    - from: "src/app/auth/signup/page.tsx"
      to: "src/app/api/auth/send-verification-email/route.ts"
      via: "resend verification"
      pattern: "fetch.*api/auth/send-verification-email"
---

# Phase 1, Plan 3: Email Verification & Middleware Protection

## Objective

Implement complete email verification and password reset functionality to complete the authentication system along with middleware protection for authenticated routes.

## Purpose

This final plan ensures the authentication system is fully complete by implementing email verification resending, proper middleware protection, and a complete email service integration. These features provide robust user management capabilities and enhance security.

## Output

- Complete email verification resending functionality
- Authentication middleware for protecting routes  
- Email service integration for sending emails
- Improved email verification flow

## Context

The previous plans have established core authentication flows. This plan focuses on completing the user experience with:
- Resending verification emails
- Implementing authentication middleware 
- Creating reusable email service utilities
- Ensuring all flows are properly integrated

## Tasks

<task type="auto">
  <name>Implement Email Verification Resend Endpoint</name>
  <files>src/app/api/auth/send-verification-email/route.ts</files>
  <action>
    Implement the POST endpoint for resending email verification:
    - Add validation for email field
    - Look up user by email in database using Prisma
    - Generate a new email verification token with expiration (e.g., 24 hours)
    - Store the new token and expiration in the user record
    - Send verification email with new link containing token
    - Return appropriate response indicating email sent
    
    The implementation should:
    - Only allow resending if user exists and hasn't verified email yet
    - Regenerate a new verification token each time
    - Set appropriate expiration time (e.g., 24 hours)
    - Send email using configured email service (details in infrastructure)
    - Return clear success/failure messages
  </action>
  <verify>Run `curl -X POST http://localhost:3001/api/auth/send-verification-email -H "Content-Type: application/json" -d '{"email":"test@example.com"}'` and verify behavior</verify>
  <done>User can request verification email to be resent and receive confirmation</done>
</task>

<task type="auto">
  <name>Implement Authentication Middleware</name>
  <files>src/middleware.ts</files>
  <action>
    Create authentication middleware to protect routes:
    - Check for presence of valid authentication cookie
    - Validate the JWT token in the cookie using jose library
    - Extract user session information from the token
    - Allow access to public routes (login, signup, forgot password, etc.) 
    - Redirect unauthorized users to login page for protected routes
    - Set user session information in request object for downstream use
    - Handle expired or invalid tokens appropriately
    
    The middleware should:
    - Be applied at the application level
    - Protect routes that require authentication
    - Redirect properly for unauthorized access
    - Provide user session data to protected routes
    - Be secure and prevent bypass attempts
  </action>
  <verify>Try accessing a protected route without authentication and verify redirection</verify>
  <done>Authentication middleware properly protects routes and redirects unauthorized users</done>
</task>

<task type="auto">
  <name>Create Email Service Utility</name>
  <files>src/lib/email-service.ts</files>
  <action>
    Create a utility module for sending emails:
    - Configure email transport using nodemailer or equivalent
    - Implement sendEmail function with parameters for recipient, subject, and content
    - Handle environment variables for email configuration
    - Implement proper error handling and logging
    - Support both text and HTML email formats
    - Add retry mechanisms if needed
    
    The utility should:
    - Follow the infrastructure configuration provided
    - Be reusable across different email sending contexts
    - Handle configuration in a secure way
    - Provide clear error messages for debugging
    - Support sending of verification and reset emails
  </action>
  <verify>Run a test sendEmail call and verify it executes without error</verify>
  <done>Email service utility is configured and functional</done>
</task>

<task type="auto">
  <name>Integrate Email Service with Verification</name>
  <files>src/app/api/auth/verify-email/route.ts</files>
  <action>
    Update the verification endpoint to use the email service:
    - Import and use the email service utility for sending verification emails
    - Ensure email sending is handled properly in the resend flow
    - Add error handling for email sending failures
    - Log any email sending issues for debugging
    
    The integration should:
    - Ensure verification emails are sent properly
    - Handle failures gracefully
    - Log any issues for debugging purposes
  </action>
  <verify>Verify that verification emails are sent when calling verification endpoint</verify>
  <done>Email service is properly integrated with verification flows</done>
</task>

<task type="auto">
  <name>Enhance Email Verification Form Component</name>
  <files>src/components/EmailVerificationForm.tsx</files>
  <action>
    Create or enhance an email verification form component:
    - Add UI for showing verification status (pending, successful, failed)
    - Include options for resending verification email 
    - Display clear user instructions
    - Handle loading states appropriately
    - Provide visual feedback for user actions
    
    The component should:
    - Be responsive and accessible
    - Provide clear feedback during verification process
    - Allow users to resend verification emails
    - Be styled consistently with other UI components
  </action>
  <verify>Verify the component renders correctly and handles verification states</verify>
  <done>Email verification form component is accessible, functional, and consistent with UI</done>
</task>

<task type="auto">
  <name>Update Authentication Flow Documentation</name>
  <files>src/app/auth/signup/page.tsx</files>
  <action>
    Update the signup page to include verification information:
    - Add messaging about email verification requirement
    - Include instructions for checking spam/junk folder
    - Add option to resend verification email
    - Provide clearer success feedback after signup
    
    The updates should:
    - Inform users about next steps after signup
    - Provide clear instructions on verification process
    - Allow for easy resending of verification emails
    - Help users understand what to expect
  </action>
  <verify>Verify that the updated signup page provides clear verification instructions</verify>
  <done>Signup page provides comprehensive verification information to users</done>
</task>

<verification>
- Email verification resending works properly
- Authentication middleware effectively protects routes
- Email service is properly implemented and integrated
- All verification flows are complete and functional
- User experience is improved with better messaging
</verification>

<success_criteria>
- User can resend email verification if needed
- User session persists across browser refresh
- Protected routes are properly secured
- Authentication middleware works correctly
</success_criteria>

<output>
After completion, create `.planning/phases/01-setup-and-authentication/01-03-SUMMARY.md`
</output>