9.7 KiB
Authentication System Implementation Plan
Current State Analysis
The application is a Flask-based email organizer with the following current state:
- Models:
UserandFoldermodels exist, but User model only hasid,email,password_hash, andimap_configfields - Routes: Currently uses a hardcoded
MOCK_USER_IDfor 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
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
- Authentication Blueprint: Separate blueprint for auth routes
- Session Management: Flask-Login for session handling
- Password Hashing: Werkzeug security utilities
- Route Protection: Decorators for requiring authentication
- User Context: Current user available in all templates
Database Schema Updates
The User model needs the following changes:
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
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
-
Update Dependencies (
requirements.txt)- Add Flask-Login for session management
- Add Werkzeug for password hashing (already included with Flask)
-
Update User Model (
app/models.py)- Add
first_nameandlast_namefields - Add
created_atandupdated_attimestamps - Add password hashing methods
- Implement
__repr__method for better debugging
- Add
-
Create Authentication Blueprint (
app/auth.py)- Login route (
/login) - Signup route (
/signup) - Logout route (
/logout) - Authentication utilities
- Login route (
-
Update Application Factory (
app/__init__.py)- Initialize Flask-Login
- Register authentication blueprint
- Configure user loader callback
Phase 2: User Interface
-
Create Login Template (
app/templates/auth/login.html)- Email and password fields
- Remember me checkbox
- Links to signup and password reset
- Error message display
-
Create Signup Template (
app/templates/auth/signup.html)- First name, last name, email, password fields
- Password confirmation field
- Terms of service checkbox
- Error message display
-
Update Main Layout (
app/templates/base.html)- Conditional authentication links
- User display in top-right corner
- Flash message support
-
Update Index Template (
app/templates/index.html)- Show actual user name instead of "User Name"
- Update logout functionality
- Add user dropdown menu
Phase 3: Route Protection and Integration
-
Create Authentication Middleware (
app/auth.py)@login_requireddecorator- Anonymous user handling
- Session validation
-
Update Main Routes (
app/routes.py)- Replace
MOCK_USER_IDwith authenticated user - Add user context to all routes
- Update folder operations to use real user
- Replace
-
Create Database Migration (
migrations/)- Generate migration for User model changes
- Apply migration to database
Phase 4: Testing
-
Update Test Configuration (
tests/conftest.py)- Add authentication fixtures
- Create test users with hashed passwords
- Session management for tests
-
Create Authentication Tests (
tests/test_auth.py)- User registration tests
- Login/logout tests
- Password validation tests
- Session management tests
-
Update Existing Tests (
tests/test_routes.py)- Add authentication requirements
- Update to use authenticated test users
- Test route protection
Phase 5: Security and Error Handling
-
Password Security (
app/auth.py)- Password strength validation
- Secure password hashing
- Password reset functionality (future)
-
Error Handling (
app/errors.py)- Authentication error handlers
- Validation error responses
- Security-related error logging
-
Session Security (
app/__init__.py)- 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
- User Registration: Users can create accounts with first name, last name, email, and password
- User Login: Users can log in using email and password
- Session Management: Users remain logged across requests
- Route Protection: Only authenticated users can access the main application
- User Display: User's name is displayed in the top-right corner
- Logout: Users can log out and clear their session
- Password Security: Passwords are properly hashed and verified
- Test Coverage: All authentication flows are tested
- 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
- Functional: All authentication features work as specified
- Security: Passwords are properly hashed and sessions are secure
- Performance: Authentication adds minimal overhead to application
- Maintainability: Code is well-structured and easy to extend
- Test Coverage: 90%+ test coverage for authentication features
Requirements Fulfillment
This plan addresses all the specified requirements:
-
✅ 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
-
✅ 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"
- User templates will display
-
✅ A user can logout
- Logout route will clear the session and redirect to login page
-
✅ 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
-
✅ The password should be hashed when it's stored
- Werkzeug's
generate_password_hashandcheck_password_hashwill be used for secure password handling
- Werkzeug's
-
✅ 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
-
✅ Tests are updated to be signed in as a user
- Test fixtures will create authenticated users for all existing tests
-
✅ 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.