# Authentication System Implementation Plan

## Current State Analysis

The application is a Flask-based email organizer with the following current state:

- **Models**: [`User`](app/models.py:10) and [`Folder`](app/models.py:18) models exist, but User model only has `id`, `email`, `password_hash`, and `imap_config` fields
- **Routes**: Currently uses a hardcoded [`MOCK_USER_ID`](app/routes.py:10) for all operations
- **UI**: Shows "User Name" as a placeholder in the top-right corner
- **Authentication**: No authentication system currently implemented
- **Tests**: Basic tests exist but don't account for authentication

## Authentication System Architecture

### System Overview

```mermaid
graph TD
    A[User Request] --> B{Authenticated?}
    B -->|No| C[Redirect to Login]
    B -->|Yes| D[Process Request]
    C --> E[Login Page]
    F[New User] --> G[Signup Page]
    G --> H[Create User]
    H --> I[Login]
    I --> D
    E --> J[Validate Credentials]
    J -->|Valid| K[Create Session]
    K --> D
    J -->|Invalid| E
```

### Key Components

1. **Authentication Blueprint**: Separate blueprint for auth routes
2. **Session Management**: Flask-Login for session handling
3. **Password Hashing**: Werkzeug security utilities
4. **Route Protection**: Decorators for requiring authentication
5. **User Context**: Current user available in all templates

### Database Schema Updates

The [`User`](app/models.py:10) model needs the following changes:

```python
class User(Base):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    first_name = db.Column(db.String(255), nullable=False)
    last_name = db.Column(db.String(255), nullable=False)
    email = db.Column(db.String(255), unique=True, nullable=False)
    password_hash = db.Column(db.LargeBinary, nullable=False)
    imap_config = db.Column(db.JSON)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
```

### Authentication Flow

```mermaid
sequenceDiagram
    participant U as User
    participant L as Login Page
    participant S as Server
    participant DB as Database
    
    U->>L: Navigate to /login
    L->>U: Show login form
    U->>S: POST /login with credentials
    S->>DB: Query user by email
    DB-->>S: Return user if found
    S->>S: Verify password hash
    S->>S: Create user session
    S-->>U: Redirect to / with session cookie
```

## Implementation Plan

### Phase 1: Core Authentication Infrastructure

1. **Update Dependencies** ([`requirements.txt`](requirements.txt:1))
   - Add Flask-Login for session management
   - Add Werkzeug for password hashing (already included with Flask)

2. **Update User Model** ([`app/models.py`](app/models.py:10))
   - Add `first_name` and `last_name` fields
   - Add `created_at` and `updated_at` timestamps
   - Add password hashing methods
   - Implement `__repr__` method for better debugging

3. **Create Authentication Blueprint** ([`app/auth.py`](app/auth.py:1))
   - Login route (`/login`)
   - Signup route (`/signup`)
   - Logout route (`/logout`)
   - Authentication utilities

4. **Update Application Factory** ([`app/__init__.py`](app/__init__.py:9))
   - Initialize Flask-Login
   - Register authentication blueprint
   - Configure user loader callback

### Phase 2: User Interface

1. **Create Login Template** ([`app/templates/auth/login.html`](app/templates/auth/login.html:1))
   - Email and password fields
   - Remember me checkbox
   - Links to signup and password reset
   - Error message display

2. **Create Signup Template** ([`app/templates/auth/signup.html`](app/templates/auth/signup.html:1))
   - First name, last name, email, password fields
   - Password confirmation field
   - Terms of service checkbox
   - Error message display

3. **Update Main Layout** ([`app/templates/base.html`](app/templates/base.html:1))
   - Conditional authentication links
   - User display in top-right corner
   - Flash message support

4. **Update Index Template** ([`app/templates/index.html`](app/templates/index.html:1))
   - Show actual user name instead of "User Name"
   - Update logout functionality
   - Add user dropdown menu

### Phase 3: Route Protection and Integration

1. **Create Authentication Middleware** ([`app/auth.py`](app/auth.py:1))
   - `@login_required` decorator
   - Anonymous user handling
   - Session validation

2. **Update Main Routes** ([`app/routes.py`](app/routes.py:1))
   - Replace `MOCK_USER_ID` with authenticated user
   - Add user context to all routes
   - Update folder operations to use real user

3. **Create Database Migration** ([`migrations/`](migrations/:1))
   - Generate migration for User model changes
   - Apply migration to database

### Phase 4: Testing

1. **Update Test Configuration** ([`tests/conftest.py`](tests/conftest.py:1))
   - Add authentication fixtures
   - Create test users with hashed passwords
   - Session management for tests

2. **Create Authentication Tests** ([`tests/test_auth.py`](tests/test_auth.py:1))
   - User registration tests
   - Login/logout tests
   - Password validation tests
   - Session management tests

3. **Update Existing Tests** ([`tests/test_routes.py`](tests/test_routes.py:1))
   - Add authentication requirements
   - Update to use authenticated test users
   - Test route protection

### Phase 5: Security and Error Handling

1. **Password Security** ([`app/auth.py`](app/auth.py:1))
   - Password strength validation
   - Secure password hashing
   - Password reset functionality (future)

2. **Error Handling** ([`app/errors.py`](app/errors.py:1))
   - Authentication error handlers
   - Validation error responses
   - Security-related error logging

3. **Session Security** ([`app/__init__.py`](app/__init__.py:1))
   - Secure session configuration
   - CSRF protection
   - Session timeout handling

## File Structure Changes

```
app/
├── auth.py                 # Authentication blueprint and utilities
├── models.py              # Updated User model
├── routes.py              # Updated main routes
├── __init__.py            # Updated app factory
├── templates/
│   ├── auth/
│   │   ├── login.html     # Login page template
│   │   └── signup.html    # Signup page template
│   ├── base.html          # Updated base template
│   └── index.html         # Updated main page
tests/
├── test_auth.py           # Authentication tests
├── conftest.py            # Updated test fixtures
└── test_routes.py         # Updated route tests
migrations/
└── versions/
    └── [timestamp]_add_user_fields.py  # User model migration
requirements.txt           # Updated dependencies
```

## Acceptance Criteria

1. **User Registration**: Users can create accounts with first name, last name, email, and password
2. **User Login**: Users can log in using email and password
3. **Session Management**: Users remain logged across requests
4. **Route Protection**: Only authenticated users can access the main application
5. **User Display**: User's name is displayed in the top-right corner
6. **Logout**: Users can log out and clear their session
7. **Password Security**: Passwords are properly hashed and verified
8. **Test Coverage**: All authentication flows are tested
9. **Integration**: Existing functionality works with authenticated users

## Implementation Dependencies

- Flask-Login: Session management
- Werkzeug: Password hashing utilities
- Flask-WTF: Form validation (optional but recommended)
- pytest: Testing framework

## Risk Assessment

**Low Risk Items:**
- Basic authentication implementation
- Template updates for user display
- Test updates for authenticated users

**Medium Risk Items:**
- Database migration for existing data
- Session management configuration
- Route protection integration

**High Risk Items:**
- Password security implementation
- Session security configuration
- Cross-site scripting protection

## Success Metrics

1. **Functional**: All authentication features work as specified
2. **Security**: Passwords are properly hashed and sessions are secure
3. **Performance**: Authentication adds minimal overhead to application
4. **Maintainability**: Code is well-structured and easy to extend
5. **Test Coverage**: 90%+ test coverage for authentication features

## Requirements Fulfillment

This plan addresses all the specified requirements:

1. ✅ **A user can only view the current app if they are logged in**
   - Route protection middleware ensures only authenticated users can access the main application

2. ✅ **The user's name is shown in the top right instead of the temporary name that is visible**
   - User templates will display `{{ current_user.first_name }} {{ current_user.last_name }}` instead of "User Name"

3. ✅ **A user can logout**
   - Logout route will clear the session and redirect to login page

4. ✅ **Only the following are required to create an account: first name, last name, email, password**
   - Signup form will collect exactly these four fields with proper validation

5. ✅ **The password should be hashed when it's stored**
   - Werkzeug's `generate_password_hash` and `check_password_hash` will be used for secure password handling

6. ✅ **A user can log back in using their email and password**
   - Login form will accept email and password, with proper verification against the hashed password

7. ✅ **Tests are updated to be signed in as a user**
   - Test fixtures will create authenticated users for all existing tests

8. ✅ **Tests are updated to test creating a user**
   - New test suite will cover user registration, login, and session management

This plan provides a comprehensive approach to implementing authentication in the email organizer application while maintaining the existing functionality and ensuring security best practices.