3 Commits

Author SHA1 Message Date
Yanis
886c204fa5 Add auth test suite, API tests and database migration tests 2026-05-27 16:27:42 +02:00
Jürg Hallenbarter
deba81fadb added migration seeders models and test script 2026-04-29 14:20:41 +02:00
Cametendo
b2dab73f17 Made sure, env files aren't tracked 2026-04-22 16:25:08 +02:00
50 changed files with 5183 additions and 2 deletions

2
.gitignore vendored
View File

@@ -124,3 +124,5 @@ _modules/*
/results/ /results/
/phpunit*.xml /phpunit*.xml
.env
env

189
AUTO_LOGGING_GUIDE.md Normal file
View File

@@ -0,0 +1,189 @@
# Automatic Activity Logging Guide
## Overview
The Todo App Backend now includes automatic activity logging for all CRUD operations (Create, Read, Update, Delete) on key entities. This is implemented using a PHP trait that can be easily added to any model.
## How It Works
### LoggableTrait
The `LoggableTrait` in `app/Models/LoggableTrait.php` provides automatic logging functionality by hooking into CodeIgniter 4's model lifecycle events:
- **afterInsert**: Logs when a new record is created
- **afterUpdate**: Logs when a record is updated
- **afterDelete**: Logs when a record is deleted
### Enabled Models
The following models now have automatic logging enabled:
1. **UserModel** - Logs user creation, updates, and deletion
2. **TodoModel** - Logs todo creation, updates, and deletion
3. **CategoryModel** - Logs category creation, updates, and deletion
4. **ProjectModel** - Logs project creation, updates, and deletion
5. **RecurringTaskModel** - Logs recurring task creation, updates, and deletion
### What Gets Logged
Each log entry includes:
- **user_id**: The ID of the user performing the action (from the record or session)
- **action**: Formatted action name (e.g., "todo_created", "user_updated", "category_deleted")
- **entity_type**: The type of entity (e.g., "todo", "user", "category")
- **entity_id**: The ID of the affected entity
- **details**: JSON object with relevant fields (title, name, email, etc.)
- **ip_address**: Client IP address
- **user_agent**: Browser user agent string
- **created_at**: Timestamp of the action
### Example Log Entries
**Creating a todo:**
```json
{
"user_id": "550e8400-e29b-41d4-a716-446655440000",
"action": "todo_created",
"entity_type": "todo",
"entity_id": "550e8400-e29b-41d4-a716-446655440001",
"details": {
"action": "created",
"title": "Complete project documentation"
},
"ip_address": "192.168.1.100",
"user_agent": "Mozilla/5.0...",
"created_at": "2026-04-29 13:42:00"
}
```
**Updating a user:**
```json
{
"user_id": "550e8400-e29b-41d4-a716-446655440000",
"action": "user_updated",
"entity_type": "user",
"entity_id": "550e8400-e29b-41d4-a716-446655440000",
"details": {
"action": "updated",
"name": "John Doe",
"email": "john@example.com"
},
"ip_address": "192.168.1.100",
"user_agent": "Mozilla/5.0...",
"created_at": "2026-04-29 13:45:00"
}
```
**Deleting a category:**
```json
{
"user_id": "550e8400-e29b-41d4-a716-446655440000",
"action": "category_deleted",
"entity_type": "category",
"entity_id": "550e8400-e29b-41d4-a716-446655440002",
"details": {
"action": "deleted",
"name": "Work"
},
"ip_address": "192.168.1.100",
"user_agent": "Mozilla/5.0...",
"created_at": "2026-04-29 13:50:00"
}
```
## Adding Logging to Other Models
To add automatic logging to a new model:
1. Add the `use LoggableTrait;` statement to your model class
2. Override the `getEntityType()` method to return the entity type name
Example:
```php
<?php
namespace App\Models;
use CodeIgniter\Model;
class MarketplaceThemeModel extends Model
{
use LoggableTrait;
protected $table = 'marketplace_themes';
// ... other model properties ...
protected function getEntityType(): string
{
return 'marketplace_theme';
}
}
```
## Customizing Log Details
You can customize what details are logged by overriding the `getLogDetails()` method in your model:
```php
protected function getLogDetails($action, $data): array
{
$details = parent::getLogDetails($action, $data);
// Add custom fields
if (isset($data['price'])) {
$details['price'] = $data['price'];
}
if (isset($data['is_published'])) {
$details['is_published'] = $data['is_published'];
}
return $details;
}
```
## Querying Activity Logs
Use the `ActivityLogModel` to query logs:
```php
$activityLogModel = new ActivityLogModel();
// Get logs for a specific user
$logs = $activityLogModel->getByUser($userId);
// Get logs for a specific entity
$logs = $activityLogModel->getByEntity('todo', $todoId);
// Get logs by action type
$logs = $activityLogModel->getByAction('todo_created');
// Custom query
$logs = $activityLogModel
->where('user_id', $userId)
->where('entity_type', 'todo')
->orderBy('created_at', 'DESC')
->limit(20)
->get()
->getResultArray();
```
## Session Requirement
The logging system attempts to get the user ID from:
1. The data being inserted/updated (e.g., `user_id` field in the record)
2. The session (`session()->get('user_id')`)
Make sure your authentication system sets the user ID in the session for proper logging.
## Disabling Logging
To disable automatic logging for a specific operation, you can temporarily disable the model events:
```php
$todoModel = new TodoModel();
$todoModel->disableEvents();
$todoModel->insert($data);
$todoModel->enableEvents();
```
Or remove the `use LoggableTrait;` from the model class entirely.

548
DATABASE_DOCUMENTATION.md Normal file
View File

@@ -0,0 +1,548 @@
# Todo App Backend - Database Documentation
## Overview
This document describes the database schema for the Todo App Backend, built with CodeIgniter 4 and MySQL. The database supports user accounts, todo management, recurring tasks, activity logging, theme marketplace, and AI-powered chat features.
## Database Schema
### Core Tables
#### 1. users
Stores user account information and application settings.
| Column | Type | Nullable | Description |
|--------|------|----------|-------------|
| id | CHAR(36) | NO | Primary key (UUID) |
| email | VARCHAR(255) | NO | User email (unique) |
| password_hash | VARCHAR(255) | NO | Bcrypt hashed password |
| name | VARCHAR(255) | YES | Display name |
| avatar_url | TEXT | YES | Profile image URL |
| settings | JSON | YES | App preferences (language, default view, etc.) |
| created_at | DATETIME | YES | Creation timestamp |
| updated_at | DATETIME | YES | Last update timestamp |
**Indexes:**
- PRIMARY KEY (id)
- UNIQUE KEY (email)
---
#### 2. categories
Per-user categories for organizing todos.
| Column | Type | Nullable | Description |
|--------|------|----------|-------------|
| id | CHAR(36) | NO | Primary key (UUID) |
| user_id | CHAR(36) | NO | Foreign key to users |
| name | VARCHAR(255) | NO | Category name |
| color | VARCHAR(7) | YES | Hex color code for UI |
| favorite | BOOLEAN | NO | Mark as favorite |
| created_at | DATETIME | YES | Creation timestamp |
**Indexes:**
- PRIMARY KEY (id)
- KEY (user_id)
- UNIQUE KEY (user_id, name)
**Foreign Keys:**
- user_id → users(id) ON DELETE CASCADE
---
#### 3. projects
Optional project grouping for todos.
| Column | Type | Nullable | Description |
|--------|------|----------|-------------|
| id | CHAR(36) | NO | Primary key (UUID) |
| user_id | CHAR(36) | NO | Foreign key to users |
| name | VARCHAR(255) | NO | Project name |
| description | TEXT | YES | Project description |
| color | VARCHAR(7) | YES | Hex color code for UI |
| created_at | DATETIME | YES | Creation timestamp |
**Indexes:**
- PRIMARY KEY (id)
- KEY (user_id)
**Foreign Keys:**
- user_id → users(id) ON DELETE CASCADE
---
#### 4. todos
Main todo items.
| Column | Type | Nullable | Description |
|--------|------|----------|-------------|
| id | CHAR(36) | NO | Primary key (UUID) |
| user_id | CHAR(36) | NO | Foreign key to users |
| title | VARCHAR(255) | NO | Todo title |
| description | TEXT | YES | Detailed description |
| status | ENUM | NO | open, in_progress, completed, archived |
| due_date | DATE | YES | Due date |
| due_time | TIME | YES | Due time |
| sync_enabled | BOOLEAN | NO | Sync with external services |
| reminder_enabled | BOOLEAN | NO | Enable reminders |
| recurring_enabled | BOOLEAN | NO | Mark as recurring |
| project_id | CHAR(36) | YES | Foreign key to projects |
| created_at | DATETIME | YES | Creation timestamp |
| updated_at | DATETIME | YES | Last update timestamp |
**Indexes:**
- PRIMARY KEY (id)
- KEY (user_id)
- KEY (due_date)
- KEY (status)
**Foreign Keys:**
- user_id → users(id) ON DELETE CASCADE
- project_id → projects(id) ON DELETE SET NULL
---
#### 5. todo_categories (Junction Table)
Many-to-many relationship between todos and categories.
| Column | Type | Nullable | Description |
|--------|------|----------|-------------|
| todo_id | CHAR(36) | NO | Foreign key to todos |
| category_id | CHAR(36) | NO | Foreign key to categories |
**Indexes:**
- PRIMARY KEY (todo_id, category_id)
**Foreign Keys:**
- todo_id → todos(id) ON DELETE CASCADE
- category_id → categories(id) ON DELETE CASCADE
---
#### 6. recurring_tasks
Templates for recurring todo items.
| Column | Type | Nullable | Description |
|--------|------|----------|-------------|
| id | CHAR(36) | NO | Primary key (UUID) |
| user_id | CHAR(36) | NO | Foreign key to users |
| title | VARCHAR(255) | NO | Task title |
| description | TEXT | YES | Task description |
| schedule | ENUM | NO | daily, weekly, monthly, custom |
| custom_days | JSON | YES | Array of days (e.g., ["mon","wed","fri"]) |
| favorite | BOOLEAN | NO | Mark as favorite |
| created_at | DATETIME | YES | Creation timestamp |
| updated_at | DATETIME | YES | Last update timestamp |
**Indexes:**
- PRIMARY KEY (id)
- KEY (user_id)
**Foreign Keys:**
- user_id → users(id) ON DELETE CASCADE
---
#### 7. recurring_task_categories (Junction Table)
Many-to-many relationship between recurring tasks and categories.
| Column | Type | Nullable | Description |
|--------|------|----------|-------------|
| recurring_task_id | CHAR(36) | NO | Foreign key to recurring_tasks |
| category_id | CHAR(36) | NO | Foreign key to categories |
**Indexes:**
- PRIMARY KEY (recurring_task_id, category_id)
**Foreign Keys:**
- recurring_task_id → recurring_tasks(id) ON DELETE CASCADE
- category_id → categories(id) ON DELETE CASCADE
---
### Activity Logging
#### 8. activity_logs
Audit trail for user actions and system events.
| Column | Type | Nullable | Description |
|--------|------|----------|-------------|
| id | CHAR(36) | NO | Primary key (UUID) |
| user_id | CHAR(36) | YES | Foreign key to users (nullable for anonymous) |
| action | VARCHAR(255) | NO | Action type (e.g., todo_created, login) |
| entity_type | VARCHAR(100) | YES | Entity type (todo, category, project, etc.) |
| entity_id | CHAR(36) | YES | Entity ID |
| details | JSON | YES | Additional metadata (before/after values) |
| ip_address | VARCHAR(45) | YES | User IP address |
| user_agent | TEXT | YES | Browser user agent |
| created_at | DATETIME | YES | Creation timestamp |
**Indexes:**
- PRIMARY KEY (id)
- KEY (user_id)
- KEY (created_at)
- KEY (action)
- KEY (entity_type, entity_id)
**Foreign Keys:**
- user_id → users(id) ON DELETE SET NULL
---
### Theme Marketplace
#### 9. marketplace_themes
Master list of available themes in the marketplace.
| Column | Type | Nullable | Description |
|--------|------|----------|-------------|
| id | CHAR(36) | NO | Primary key (UUID) |
| name | VARCHAR(255) | NO | Theme identifier (unique) |
| display_name | VARCHAR(255) | NO | Human-readable name |
| description | TEXT | YES | Theme description |
| author | VARCHAR(255) | YES | Theme author |
| version | VARCHAR(50) | YES | Theme version |
| thumbnail_url | TEXT | YES | Preview image URL |
| download_url | TEXT | NO | Download URL |
| price | DECIMAL(10,2) | NO | Theme price (0 = free) |
| is_published | BOOLEAN | NO | Published status |
| metadata | JSON | YES | Tags, screenshots, etc. |
| created_at | DATETIME | YES | Creation timestamp |
| updated_at | DATETIME | YES | Last update timestamp |
**Indexes:**
- PRIMARY KEY (id)
- UNIQUE KEY (name)
---
#### 10. user_themes
Themes installed by users.
| Column | Type | Nullable | Description |
|--------|------|----------|-------------|
| id | CHAR(36) | NO | Primary key (UUID) |
| user_id | CHAR(36) | NO | Foreign key to users |
| theme_id | CHAR(36) | NO | Foreign key to marketplace_themes |
| installed_at | DATETIME | YES | Installation timestamp |
| active | BOOLEAN | NO | Currently active theme |
| custom_settings | JSON | YES | User theme overrides |
**Indexes:**
- PRIMARY KEY (id)
- UNIQUE KEY (user_id, theme_id)
**Foreign Keys:**
- user_id → users(id) ON DELETE CASCADE
- theme_id → marketplace_themes(id) ON DELETE CASCADE
---
### AI Features
#### 11. ai_providers
Supported AI providers (OpenAI, Anthropic, Google, etc.).
| Column | Type | Nullable | Description |
|--------|------|----------|-------------|
| id | CHAR(36) | NO | Primary key (UUID) |
| name | VARCHAR(100) | NO | Provider identifier (unique) |
| display_name | VARCHAR(255) | NO | Human-readable name |
| base_url | TEXT | YES | API endpoint override |
| is_builtin | BOOLEAN | NO | System vs custom provider |
| created_at | DATETIME | YES | Creation timestamp |
**Indexes:**
- PRIMARY KEY (id)
- UNIQUE KEY (name)
---
#### 12. user_api_keys
Encrypted API keys for each provider per user.
| Column | Type | Nullable | Description |
|--------|------|----------|-------------|
| id | CHAR(36) | NO | Primary key (UUID) |
| user_id | CHAR(36) | NO | Foreign key to users |
| provider_id | CHAR(36) | NO | Foreign key to ai_providers |
| api_key_encrypted | TEXT | NO | Encrypted API key |
| label | VARCHAR(255) | YES | Key label (e.g., "Work Key") |
| is_active | BOOLEAN | NO | Active status |
| created_at | DATETIME | YES | Creation timestamp |
| last_used_at | DATETIME | YES | Last usage timestamp |
**Indexes:**
- PRIMARY KEY (id)
- UNIQUE KEY (user_id, provider_id)
**Foreign Keys:**
- user_id → users(id) ON DELETE CASCADE
- provider_id → ai_providers(id) ON DELETE CASCADE
---
#### 13. user_ai_settings
Per-user AI preferences.
| Column | Type | Nullable | Description |
|--------|------|----------|-------------|
| user_id | CHAR(36) | NO | Primary key, Foreign key to users |
| default_provider_id | CHAR(36) | YES | Foreign key to ai_providers |
| default_model | VARCHAR(100) | YES | Default model (e.g., gpt-4) |
| max_tokens | INT | NO | Maximum tokens (default: 2048) |
| temperature | FLOAT | NO | Temperature (default: 0.7) |
| updated_at | DATETIME | YES | Last update timestamp |
**Indexes:**
- PRIMARY KEY (user_id)
**Foreign Keys:**
- user_id → users(id) ON DELETE CASCADE
- default_provider_id → ai_providers(id) ON DELETE SET NULL
---
#### 14. ai_chats
AI conversation threads.
| Column | Type | Nullable | Description |
|--------|------|----------|-------------|
| id | CHAR(36) | NO | Primary key (UUID) |
| user_id | CHAR(36) | NO | Foreign key to users |
| title | VARCHAR(255) | YES | Chat title |
| provider_id | CHAR(36) | YES | Foreign key to ai_providers |
| model_used | VARCHAR(100) | YES | Model snapshot |
| system_prompt | TEXT | YES | Custom system prompt |
| created_at | DATETIME | YES | Creation timestamp |
| updated_at | DATETIME | YES | Last update timestamp |
**Indexes:**
- PRIMARY KEY (id)
- KEY (user_id)
- KEY (updated_at)
**Foreign Keys:**
- user_id → users(id) ON DELETE CASCADE
- provider_id → ai_providers(id) ON DELETE SET NULL
---
#### 15. ai_messages
Individual messages in AI chats.
| Column | Type | Nullable | Description |
|--------|------|----------|-------------|
| id | CHAR(36) | NO | Primary key (UUID) |
| chat_id | CHAR(36) | NO | Foreign key to ai_chats |
| role | ENUM | NO | user, assistant, system |
| content | TEXT | NO | Message content |
| tokens_used | INT | YES | Token count for billing |
| created_at | DATETIME | YES | Creation timestamp |
**Indexes:**
- PRIMARY KEY (id)
- KEY (chat_id)
**Foreign Keys:**
- chat_id → ai_chats(id) ON DELETE CASCADE
---
## Entity Relationship Diagram (ERD)
```
┌─────────────────┐
│ users │
├─────────────────┤
│ id (PK) │◄────────┐
│ email │ │
│ password_hash │ │
│ name │ │
│ settings │ │
│ created_at │ │
│ updated_at │ │
└─────────────────┘ │
┌───────────────────┼───────────────────┐
│ │ │
│ │ │
┌───────────────┐ ┌───────────────┐ ┌───────────────┐
│ categories │ │ projects │ │ activity_logs │
├───────────────┤ ├───────────────┤ ├───────────────┤
│ id (PK) │ │ id (PK) │ │ id (PK) │
│ user_id (FK) │ │ user_id (FK) │ │ user_id (FK) │
│ name │ │ name │ │ action │
│ color │ │ description │ │ entity_type │
│ favorite │ │ color │ │ entity_id │
│ created_at │ │ created_at │ │ details │
└───────────────┘ └───────────────┘ │ ip_address │
│ │ │ user_agent │
│ │ │ created_at │
│ │ └───────────────┘
│ │
│ │
│ │
┌───────────────┐ ┌───────────────┐
│ todos │ │recurring_tasks│
├───────────────┤ ├───────────────┤
│ id (PK) │ │ id (PK) │
│ user_id (FK) │ │ user_id (FK) │
│ title │ │ title │
│ description │ │ description │
│ status │ │ schedule │
│ due_date │ │ custom_days │
│ due_time │ │ favorite │
│ project_id(FK)│ │ created_at │
│ created_at │ │ updated_at │
│ updated_at │ └───────────────┘
└───────────────┘ │
│ │
│ │
│ │
┌──────────────────┐ │
│ todo_categories │◄───────┘
├──────────────────┤
│ todo_id (PK,FK) │
│ category_id(PK,FK)│
└──────────────────┘
┌──────────────────────────┐
│recurring_task_categories │
├──────────────────────────┤
│ recurring_task_id (PK,FK) │
│ category_id (PK,FK) │
└──────────────────────────┘
┌─────────────────┐
│marketplace_themes│
├─────────────────┤
│ id (PK) │◄────────┐
│ name │ │
│ display_name │ │
│ description │ │
│ download_url │ │
│ price │ │
│ is_published │ │
└─────────────────┘ │
┌─────────┴─────────┐
│ user_themes │
├──────────────────┤
│ id (PK) │
│ user_id (FK) │
│ theme_id (FK) │
│ active │
│ custom_settings │
└──────────────────┘
┌─────────────┐
│ai_providers │
├─────────────┤
│ id (PK) │◄────────┐
│ name │ │
│ display_name│ │
│ base_url │ │
│ is_builtin │ │
└─────────────┘ │
┌───────────────┼──────────────┐
│ │ │
┌────────────────┐ ┌──────────────┐ ┌─────────────────┐
│ user_api_keys │ │user_ai_settin│ │ ai_chats │
├────────────────┤ ├──────────────┤ ├─────────────────┤
│ id (PK) │ │user_id (PK) │ │ id (PK) │
│ user_id (FK) │ │default_prv(FK)│ │ user_id (FK) │
│ provider_id(FK) │ │default_model │ │ provider_id(FK) │
│ api_key_enc │ │max_tokens │ │ title │
│ label │ │temperature │ │ model_used │
│ is_active │ │updated_at │ │ system_prompt │
│ last_used_at │ └──────────────┘ │ created_at │
└────────────────┘ │ updated_at │
└─────────────────┘
┌────────────────┐
│ ai_messages │
├────────────────┤
│ id (PK) │
│ chat_id (FK) │
│ role │
│ content │
│ tokens_used │
│ created_at │
└────────────────┘
```
## Relationships Summary
| Entity | Relations |
|--------|-----------|
| **users** | Has many: todos, categories, projects, recurring_tasks, activity_logs, user_themes, user_api_keys, ai_chats, user_ai_settings |
| **todos** | Belongs to: user, project (optional). Many-to-many with categories via todo_categories |
| **recurring_tasks** | Belongs to: user. Many-to-many with categories via recurring_task_categories |
| **categories** | Linked to: todos, recurring_tasks |
| **marketplace_themes** | Installed by users via user_themes |
| **ai_providers** | Referenced by: user_api_keys, ai_chats, user_ai_settings |
| **ai_chats** | Belongs to: user, provider (optional). Has many: ai_messages |
| **ai_messages** | Belongs to: chat |
## Key Design Decisions
1. **UUID Primary Keys**: Using CHAR(36) for UUIDs to support distributed systems and prevent ID enumeration attacks.
2. **Foreign Key Cascades**:
- CASCADE DELETE for user-owned entities to clean up data when users are deleted
- SET NULL for optional references (e.g., project_id in todos)
3. **JSON Fields**: Used for flexible data like settings, custom_days, and metadata.
4. **Junction Tables**: Proper normalization for many-to-many relationships (todo-categories, recurring_task-categories).
5. **Activity Logging**: Nullable user_id allows for anonymous/system events.
6. **Theme Marketplace**: Separation of global theme catalog and user installations.
7. **AI Multi-Provider**: Support for multiple AI providers with per-user encrypted API keys.
## Migration and Seeding
To set up the database:
```bash
# Run all migrations
php spark migrate
# Run seeders
php spark db:seed AiProvidersSeeder
php spark db:seed MarketplaceThemesSeeder
php spark db:seed SampleDataSeeder
```
## Model Files
All tables have corresponding CodeIgniter 4 models in `app/Models/`:
- UserModel
- CategoryModel
- ProjectModel
- TodoModel
- TodoCategoryModel
- RecurringTaskModel
- RecurringTaskCategoryModel
- ActivityLogModel
- MarketplaceThemeModel
- UserThemeModel
- AiProviderModel
- UserApiKeyModel
- UserAiSettingsModel
- AiChatModel
- AiMessageModel
Each model includes:
- Validation rules
- Timestamp handling
- Custom query methods for common operations
- Relationship helpers

335
TESTING_GUIDE.md Normal file
View File

@@ -0,0 +1,335 @@
# Test-Suite Dokumentation
## Übersicht
Diese Test-Suite bietet umfassende Tests für die Todo-App Backend Applikation. Sie besteht aus Unit Tests, Feature Tests und Database Tests.
## Test-Struktur
```
tests/
├── unit/
│ ├── Controllers/
│ │ └── AuthControllerTest.php # Auth Controller Tests
│ ├── Models/
│ │ └── UserModelTest.php # User Model Tests
│ └── HealthTest.php # Basis-Health Checks
├── feature/
│ └── AuthApiTest.php # API Integration Tests
├── database/
│ ├── MigrationTest.php # Database Migration Tests
│ └── ExampleDatabaseTest.php # Example Tests
├── _support/ # Test Support Files
│ ├── Database/
│ ├── Libraries/
│ └── Models/
└── session/ # Session Tests
```
## Tests ausführen
### Alle Tests ausführen
```bash
cd /Users/yanis/BFOTodo/Todo-App-Backend
php vendor/bin/phpunit
```
### Nur Auth Controller Tests
```bash
php vendor/bin/phpunit tests/unit/Controllers/AuthControllerTest.php
```
### Nur User Model Tests
```bash
php vendor/bin/phpunit tests/unit/Models/UserModelTest.php
```
### Nur API Tests
```bash
php vendor/bin/phpunit tests/feature/AuthApiTest.php
```
### Nur Database Migration Tests
```bash
php vendor/bin/phpunit tests/database/MigrationTest.php
```
### Mit Coverage Report
```bash
php vendor/bin/phpunit --coverage-html build/logs/coverage
```
## Test-Kategorien
### 1. Unit Tests - Auth Controller (`tests/unit/Controllers/AuthControllerTest.php`)
Testet die Core-Logik des Auth Controllers:
**Tests:**
-`testLoginPageLoads` - Login Seite wird angezeigt
-`testLoginWithValidCredentials` - Login mit korrekten Daten
-`testLoginWithInvalidCredentials` - Login mit falschen Daten
-`testRegisterWithValidData` - Registrierung mit gültigen Daten
-`testRegisterWithDuplicateEmail` - Doppelte Email wird verhindert
-`testLogout` - Logout Funktionalität
-`testPasswordIsHashed` - Passwort wird gehasht
-`testLoginRequiresEmail` - Email ist erforderlich
-`testRegisterRequiresEmail` - Email bei Registrierung erforderlich
-`testLoginWithInvalidEmail` - Ungültiges Email Format
**Beispiel Ausführung:**
```bash
php vendor/bin/phpunit tests/unit/Controllers/AuthControllerTest.php::AuthControllerTest::testLoginWithValidCredentials
```
### 2. Unit Tests - User Model (`tests/unit/Models/UserModelTest.php`)
Testet die Benutzermodell-Operationen:
**Tests:**
-`testUserCanBeCreated` - Benutzer erstellen
-`testUserCanBeFoundByEmail` - Benutzer nach Email finden
-`testDuplicateEmailIsRejected` - Doppelte Email ablehnen
-`testUserCanBeUpdated` - Benutzer aktualisieren
-`testUserCanBeDeleted` - Benutzer löschen
-`testAllUsersCanBeRetrieved` - Alle Benutzer abrufen
-`testPasswordHashIsValid` - Passwort Hash Validierung
**Beispiel Ausführung:**
```bash
php vendor/bin/phpunit tests/unit/Models/UserModelTest.php
```
### 3. Feature Tests - Auth API (`tests/feature/AuthApiTest.php`)
Testet API Endpoints und HTTP Responses:
**Tests:**
-`testGetLoginPageReturns200` - Login Seite Status Code
-`testLoginWithValidDataReturns302` - Login Redirect
-`testRegisterApiCreatesNewUser` - Registrierung erstellt Benutzer
-`testLoginWithInvalidDataReturns302` - Fehlerhafte Login Redirect
-`testLogoutApiReturns302` - Logout Redirect
-`testLoginWithMissingEmailField` - Fehlende Email Feld
-`testLoginWithMissingPasswordField` - Fehlende Password Feld
-`testRegisterWithMissingNameField` - Fehlende Name Feld
-`testLoginPageContentType` - Content-Type Header
-`testRegisterValidatesEmailFormat` - Email Format Validierung
-`testLoginPageIncludesSecurityHeaders` - Sicherheits-Header
-`testRegisterSetsUserIdInSession` - Session User ID
-`testMultipleLoginAttempts` - Mehrfache Login Versuche
**Beispiel Ausführung:**
```bash
php vendor/bin/phpunit tests/feature/AuthApiTest.php::AuthApiTest::testLoginWithValidDataReturns302
```
### 4. Database Tests - Migrations (`tests/database/MigrationTest.php`)
Testet Datenbankmigrationen und Schema:
**Tests:**
-`testUsersTableExists` - Users Tabelle existiert
-`testUsersTableHasRequiredColumns` - Erforderliche Spalten vorhanden
-`testEmailIsUnique` - Email Unique Constraint
-`testCategoriesTableExists` - Categories Tabelle
-`testProjectsTableExists` - Projects Tabelle
-`testTodosTableExists` - Todos Tabelle
-`testTodoCategoriesTableExists` - TodoCategories Tabelle
-`testTodosTableHasRequiredColumns` - Todos Spalten
-`testDatabaseConnectionWorks` - DB Verbindung
-`testTableCountIsCorrect` - Tabellenzahl
-`testUserSettingsIsJson` - Settings JSON Type
-`testTimestampsAreCorrectType` - Timestamp Spalten
**Beispiel Ausführung:**
```bash
php vendor/bin/phpunit tests/database/MigrationTest.php
```
## Test-Konventionen
### Naming Konvention
- Test-Klassen: `{Feature}Test.php` (z.B. `AuthControllerTest.php`)
- Test-Methoden: `test{Scenario}` (z.B. `testLoginWithValidCredentials`)
- Namespace: `Tests\{Category}\{Feature}` (z.B. `Tests\Unit\Controllers`)
### Struktur
```php
/**
* Test: Beschreibung was getestet wird
*/
public function testFeatureName(): void
{
// Arrange - Setup Daten
$userData = ['email' => 'test@example.com', ...];
// Act - Aktion ausführen
$response = $this->post('/auth/login', $userData);
// Assert - Ergebnis verifizieren
$this->assertTrue($response->getStatusCode() === 302);
}
```
## Test-Traits
### DatabaseTestTrait
Ermöglicht Datenbankzugriff in Tests:
```php
use DatabaseTestTrait;
protected $seed = UserSeeder::class; // Optional: Daten seeden
```
### FeatureTestTrait
Ermöglicht HTTP Requests in Tests:
```php
use FeatureTestTrait;
$response = $this->get('/path');
$response = $this->post('/path', $data);
$response = $this->put('/path', $data);
$response = $this->delete('/path');
```
## Datenbank in Tests
### Automatisches Rollback
Tests verwenden automatisch Transaktionen, die nach jedem Test gerollt werden:
```php
class AuthControllerTest extends CIUnitTestCase
{
use DatabaseTestTrait;
// Daten werden automatisch nach jedem Test gelöscht
}
```
### Daten Seeding
```php
class MigrationTest extends CIUnitTestCase
{
use DatabaseTestTrait;
protected $seed = UserSeeder::class; // Lädt vor jedem Test
}
```
## Assertions häufig verwendet
```php
// Grundlegende Assertions
$this->assertTrue($condition);
$this->assertFalse($condition);
$this->assertNull($value);
$this->assertNotNull($value);
// Vergleiche
$this->assertEquals($expected, $actual);
$this->assertNotEquals($expected, $actual);
// Collections
$this->assertCount($count, $array);
$this->assertContains($needle, $haystack);
// Strings
$this->assertStringContainsString($needle, $haystack);
$this->assertStringStartsWith($prefix, $string);
// Response
$this->assertTrue($response->getStatusCode() === 200);
```
## Fehlerbehandlung in Tests
### Datenbank Fehler
```php
try {
// Operation die Fehler verursachen könnte
$this->post('/auth/attemptRegister', $data);
} catch (\Exception $e) {
$this->assertTrue(true); // Expected Error
}
```
### HTTP Status Codes
```php
$this->assertTrue($response->getStatusCode() === 302); // Redirect
$this->assertTrue($response->getStatusCode() === 200); // OK
$this->assertTrue($response->getStatusCode() === 400); // Bad Request
$this->assertTrue($response->getStatusCode() === 404); // Not Found
$this->assertTrue($response->getStatusCode() === 500); // Server Error
```
## Best Practices
### ✅ Do's
- ✅ Tests sollten unabhängig voneinander sein
- ✅ Verwende aussagekräftige Test-Namen
- ✅ Ein Test pro Scenario/Feature
- ✅ Verwende Arrange-Act-Assert Pattern
- ✅ Test Edge Cases und Error Conditions
- ✅ Verwende Fixtures/Seeders für Testdaten
### ❌ Dont's
- ❌ Tests sollten nicht voneinander abhängig sein
- ❌ Keine Tests mit zufälligen Daten
- ❌ Keine Long-Running Tests (< 1 Sekunde pro Test)
- ❌ Keine Tests die externe APIs aufrufen
- ❌ Keine Tests die Datei-Operationen durchführen
## Continuous Integration
Tests können in CI/CD Pipelines integriert werden:
```yaml
# .github/workflows/tests.yml
name: Tests
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Run Tests
run: php vendor/bin/phpunit
```
## Performance
**Aktuelle Test-Zusammenfassung:**
- Gesamt Tests: ~40 Tests
- Durchschnittliche Dauer: < 5 Sekunden
- Coverage Ziel: > 80%
## Troubleshooting
### Tests schlagen fehl mit "Database not found"
```bash
# Stelle sicher dass .env konfiguriert ist
cp env.example .env
# Führe Migrationen aus
php spark migrate
```
### CSRF Token Fehler
Tests werden automatisch mit CSRF Protection gehändelt durch `FeatureTestTrait`
### Session wird nicht persistent
Sessions werden zwischen Requests in Feature Tests automatisch beibehalten
## Zukünftige Verbesserungen
- [ ] API Response Body Assertions
- [ ] Performance Benchmarks
- [ ] Integration Tests für komplexe Workflows
- [ ] E2E Tests mit Selenium
- [ ] Load Tests
- [ ] Security Tests
---
**Für weitere Fragen oder Probleme:**
Dokumentation: [CodeIgniter Testing Guide](https://codeigniter.com/user_guide/testing/)

402
TEST_EXAMPLES.md Normal file
View File

@@ -0,0 +1,402 @@
# Test Examples - Praktische Beispiele
## Quick Start
### 1. Erstes Test ausführen
```bash
cd /Users/yanis/BFOTodo/Todo-App-Backend
# Alle Tests ausführen
php vendor/bin/phpunit
# Nur einen Test ausführen
php vendor/bin/phpunit tests/unit/Controllers/AuthControllerTest.php::AuthControllerTest::testLoginPageLoads
```
### 2. Einzelnen Test ausführen
```bash
# Login Test
php vendor/bin/phpunit tests/unit/Controllers/AuthControllerTest.php::AuthControllerTest::testLoginWithValidCredentials
# Registration Test
php vendor/bin/phpunit tests/unit/Controllers/AuthControllerTest.php::AuthControllerTest::testRegisterWithValidData
```
## Beispiel Unit Tests
### Test: Benutzer Login
```php
public function testLoginWithValidCredentials(): void
{
// 1. Arrange - Testdaten vorbereiten
$userModel = new UserModel();
$userData = [
'email' => 'test@example.com',
'password_hash' => password_hash('password123', PASSWORD_DEFAULT),
'name' => 'Test User',
];
$userModel->insert($userData);
// 2. Act - Login durchführen
$response = $this->post('/auth/attemptLogin', [
'email' => 'test@example.com',
'password' => 'password123',
]);
// 3. Assert - Ergebnis überprüfen
$this->assertTrue($response->getStatusCode() === 302); // Redirect
}
```
**Ausführen:**
```bash
php vendor/bin/phpunit tests/unit/Controllers/AuthControllerTest.php::AuthControllerTest::testLoginWithValidCredentials
```
### Test: Benutzer Registrierung
```php
public function testRegisterWithValidData(): void
{
// 1. Arrange
$newUserData = [
'name' => 'Neuer User',
'email' => 'newuser@example.com',
'password' => 'password123',
];
// 2. Act - Registrierung durchführen
$response = $this->post('/auth/attemptRegister', $newUserData);
// 3. Assert - Überprüfungen
$this->assertTrue($response->getStatusCode() === 302);
// Benutzer in DB existiert
$userModel = new UserModel();
$user = $userModel->where('email', 'newuser@example.com')->first();
$this->assertNotNull($user);
$this->assertEquals('Neuer User', $user['name']);
}
```
**Ausführen:**
```bash
php vendor/bin/phpunit tests/unit/Controllers/AuthControllerTest.php::AuthControllerTest::testRegisterWithValidData
```
### Test: Doppelte Email ablehnen
```php
public function testRegisterWithDuplicateEmail(): void
{
// 1. Arrange - Erstes Konto
$this->post('/auth/attemptRegister', [
'name' => 'User One',
'email' => 'duplicate@example.com',
'password' => 'password123',
]);
// 2. Act - Zweites Konto mit gleicher Email
$response = $this->post('/auth/attemptRegister', [
'name' => 'User Two',
'email' => 'duplicate@example.com',
'password' => 'password456',
]);
// 3. Assert - Sollte fehlschlagen
$this->assertTrue($response->getStatusCode() === 302);
}
```
**Ausführen:**
```bash
php vendor/bin/phpunit tests/unit/Controllers/AuthControllerTest.php::AuthControllerTest::testRegisterWithDuplicateEmail
```
## Beispiel Model Tests
### Test: Benutzer erstellen
```php
public function testUserCanBeCreated(): void
{
$userModel = new UserModel();
$data = [
'email' => 'create@example.com',
'password_hash' => password_hash('password123', PASSWORD_DEFAULT),
'name' => 'Create Test',
];
$id = $userModel->insert($data);
$this->assertIsNotNull($id);
$this->assertNotEmpty($id);
}
```
### Test: Passwort wird korrekt gehasht
```php
public function testPasswordHashIsValid(): void
{
$userModel = new UserModel();
$password = 'mypassword123';
$data = [
'email' => 'hash@example.com',
'password_hash' => password_hash($password, PASSWORD_DEFAULT),
'name' => 'Hash Test',
];
$userModel->insert($data);
$user = $userModel->where('email', 'hash@example.com')->first();
// Korrekt Passwort sollte matchen
$this->assertTrue(password_verify($password, $user['password_hash']));
// Falsches Passwort sollte nicht matchen
$this->assertFalse(password_verify('wrongpassword', $user['password_hash']));
}
```
## Beispiel API Tests
### Test: Login API Response
```php
public function testGetLoginPageReturns200(): void
{
// 1. Act - GET Request
$response = $this->get('/auth/login');
// 2. Assert - Status Code und Content
$this->assertTrue($response->getStatusCode() === 200);
$this->assertStringContainsString('form', (string)$response);
$this->assertStringContainsString('email', (string)$response);
}
```
**Ausführen:**
```bash
php vendor/bin/phpunit tests/feature/AuthApiTest.php::AuthApiTest::testGetLoginPageReturns200
```
### Test: API mit mehreren Requests
```php
public function testMultipleLoginAttempts(): void
{
// 1. Arrange
$userModel = new UserModel();
$userModel->insert([
'email' => 'multi@example.com',
'password_hash' => password_hash('correct', PASSWORD_DEFAULT),
'name' => 'Multi Test',
]);
// 2. Act - Erster Versuch (falsch)
$response1 = $this->post('/auth/attemptLogin', [
'email' => 'multi@example.com',
'password' => 'wrong',
]);
// 3. Act - Zweiter Versuch (korrekt)
$response2 = $this->post('/auth/attemptLogin', [
'email' => 'multi@example.com',
'password' => 'correct',
]);
// 4. Assert - Beide sollten redirecten
$this->assertTrue($response1->getStatusCode() === 302);
$this->assertTrue($response2->getStatusCode() === 302);
}
```
## Beispiel Database Migration Tests
### Test: Tabelle existiert
```php
public function testUsersTableExists(): void
{
$db = \Config\Database::connect();
$this->assertTrue($db->tableExists('users'));
}
```
### Test: Spalten existieren
```php
public function testUsersTableHasRequiredColumns(): void
{
$db = \Config\Database::connect();
$fields = $db->getFieldData('users');
$fieldNames = array_map(function ($field) {
return $field->name;
}, $fields);
// Diese Spalten sollten alle existieren
$this->assertContains('id', $fieldNames);
$this->assertContains('email', $fieldNames);
$this->assertContains('password_hash', $fieldNames);
$this->assertContains('name', $fieldNames);
$this->assertContains('created_at', $fieldNames);
$this->assertContains('updated_at', $fieldNames);
}
```
**Ausführen:**
```bash
php vendor/bin/phpunit tests/database/MigrationTest.php::MigrationTest::testUsersTableHasRequiredColumns
```
## Test Output Beispiele
### Erfolgreiche Tests
```bash
$ php vendor/bin/phpunit tests/unit/Controllers/AuthControllerTest.php
PHPUnit 10.5.63 by Sebastian Bergmann and contributors.
...................... 20 / 20 (100%)
Time: 00:02.345, Memory: 8.00 MB
OK (20 tests, 40 assertions)
```
### Test mit Fehler
```bash
$ php vendor/bin/phpunit tests/unit/Controllers/AuthControllerTest.php::AuthControllerTest::testLoginWithValidCredentials
PHPUnit 10.5.63 by Sebastian Bergmann and contributors.
F 1 / 1 (100%)
Time: 00:00.512, Memory: 6.00 MB
FAILURES!
Tests: 1, Assertions: 1, Failures: 1
FAIL: AuthControllerTest::testLoginWithValidCredentials
Expected Status Code 302 but got 200
```
## Häufige Assertions in Tests
### HTTP Status Codes prüfen
```php
$this->assertTrue($response->getStatusCode() === 200); // OK
$this->assertTrue($response->getStatusCode() === 302); // Redirect
$this->assertTrue($response->getStatusCode() === 400); // Bad Request
$this->assertTrue($response->getStatusCode() === 404); // Not Found
$this->assertTrue($response->getStatusCode() === 500); // Server Error
```
### Datenbank Assertions
```php
$this->assertNotNull($user); // Benutzer existiert
$this->assertEquals('test@example.com', $user['email']); // Email stimmt
$this->assertCount(5, $users); // 5 Benutzer
```
### String Assertions
```php
$this->assertStringContainsString('form', (string)$response); // Enthält
$this->assertStringStartsWith('Hello', 'Hello World'); // Beginnt mit
$this->assertStringEndsWith('World', 'Hello World'); // Endet mit
```
## Test Patterns
### Pattern 1: Arrange-Act-Assert
```php
public function testFeature(): void
{
// ARRANGE - Setup
$data = ['email' => 'test@example.com'];
// ACT - Aktion
$result = $this->post('/path', $data);
// ASSERT - Überprüfung
$this->assertTrue($result->getStatusCode() === 302);
}
```
### Pattern 2: Given-When-Then
```php
public function testFeature(): void
{
// GIVEN - Initial State
$user = $this->createUser('test@example.com');
// WHEN - Action
$response = $this->loginUser($user);
// THEN - Verify
$this->assertTrue($response->getStatusCode() === 302);
}
```
### Pattern 3: Setup-Exercise-Verify
```php
public function testFeature(): void
{
// SETUP - Prepare
$userModel = new UserModel();
// EXERCISE - Execute
$id = $userModel->insert($userData);
// VERIFY - Assert
$this->assertNotNull($id);
}
```
## Debugging Tests
### Verbose Output
```bash
php vendor/bin/phpunit -v tests/unit/Controllers/AuthControllerTest.php
```
### Mit Debug Output
```php
public function testLoginWithValidCredentials(): void
{
// ... test code ...
echo "Response Status: " . $response->getStatusCode();
var_dump($response->getBody());
}
```
### Mit xdebug
```bash
XDEBUG_CONFIG="idekey=xdebug" php vendor/bin/phpunit tests/unit/Controllers/AuthControllerTest.php
```
## Nächste Schritte
1. **Coverage Report generieren:**
```bash
php vendor/bin/phpunit --coverage-html build/logs/coverage
```
2. **Tests mit CI/CD integrieren**
3. **Mehr Tests hinzufügen für:**
- Task Management Features
- Category Management
- Project Management
- Recurring Tasks
4. **Performance Tests**
5. **Security Tests**

View File

@@ -0,0 +1,93 @@
<?php
namespace App\Commands;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use App\Models\UserModel;
use App\Models\CategoryModel;
use App\Models\ProjectModel;
use App\Models\TodoModel;
use App\Models\RecurringTaskModel;
use App\Models\ActivityLogModel;
class TestModels extends BaseCommand
{
protected $group = 'Development';
protected $name = 'test:models';
protected $description = 'Test the database models and automatic logging';
public function run(array $params)
{
CLI::write('=== Testing Todo App Models ===', 'green');
CLI::newLine();
// Get the seeded user
CLI::write('Test 1: Getting seeded user...', 'yellow');
$userModel = new UserModel();
$user = $userModel->where('email', 'demo@example.com')->first();
if (!$user) {
CLI::write('✗ No demo user found. Please run seeders first.', 'red');
return;
}
$userId = $user['id'];
CLI::write("✓ Using user: {$user['name']} ({$userId})", 'green');
CLI::newLine();
// Test 2: Query categories
CLI::write('Test 2: Querying categories...', 'yellow');
$categoryModel = new CategoryModel();
$categories = $categoryModel->where('user_id', $userId)->findAll();
CLI::write("✓ Found " . count($categories) . " categories for user", 'green');
foreach ($categories as $cat) {
CLI::write(" - {$cat['name']} ({$cat['color']})", 'light_gray');
}
CLI::newLine();
// Test 3: Query projects
CLI::write('Test 3: Querying projects...', 'yellow');
$projectModel = new ProjectModel();
$projects = $projectModel->where('user_id', $userId)->findAll();
CLI::write("✓ Found " . count($projects) . " projects for user", 'green');
foreach ($projects as $proj) {
CLI::write(" - {$proj['name']}", 'light_gray');
}
CLI::newLine();
// Test 4: Query todos
CLI::write('Test 4: Querying todos...', 'yellow');
$todoModel = new TodoModel();
$todos = $todoModel->getByUserWithCategories($userId);
CLI::write("✓ Found " . count($todos) . " todos for user", 'green');
foreach ($todos as $todo) {
CLI::write(" - {$todo['title']} ({$todo['status']})", 'light_gray');
}
CLI::newLine();
// Test 5: Query recurring tasks
CLI::write('Test 5: Querying recurring tasks...', 'yellow');
$recurringTaskModel = new RecurringTaskModel();
$recurringTasks = $recurringTaskModel->getByUserWithCategories($userId);
CLI::write("✓ Found " . count($recurringTasks) . " recurring tasks for user", 'green');
foreach ($recurringTasks as $task) {
CLI::write(" - {$task['title']} ({$task['schedule']})", 'light_gray');
}
CLI::newLine();
CLI::write('=== All Tests Completed Successfully ===', 'green');
CLI::write("Test User ID: {$userId}", 'light_gray');
CLI::write('Models are working correctly. You can now use them in your controllers.', 'light_gray');
}
private function generateUuid()
{
return sprintf(
'%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand(0, 0xffff), mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0x0fff) | 0x4000,
mt_rand(0, 0x3fff) | 0x8000,
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
);
}
}

View File

@@ -6,3 +6,8 @@ use CodeIgniter\Router\RouteCollection;
* @var RouteCollection $routes * @var RouteCollection $routes
*/ */
$routes->get('/', 'Home::index'); $routes->get('/', 'Home::index');
$routes->get('/auth/login', 'Auth::login');
$routes->post('/auth/attemptLogin', 'Auth::attemptLogin');
$routes->post('/auth/attemptRegister', 'Auth::attemptRegister');
$routes->get('/auth/logout', 'Auth::logout');

62
app/Controllers/Auth.php Normal file
View File

@@ -0,0 +1,62 @@
<?php
namespace App\Controllers;
use App\Models\UserModel;
use CodeIgniter\HTTP\ResponseInterface;
class Auth extends BaseController
{
public function login()
{
return view('auth/login_register');
}
public function attemptLogin()
{
$email = $this->request->getPost('email');
$password = $this->request->getPost('password');
$userModel = new UserModel();
$user = $userModel->where('email', $email)->first();
if ($user && password_verify($password, $user['password_hash'])) {
// Login successful
session()->set('user_id', $user['id']);
session()->set('user_email', $user['email']);
return redirect()->to('/dashboard'); // or wherever
} else {
return redirect()->back()->with('error', 'Invalid credentials');
}
}
public function attemptRegister()
{
$email = $this->request->getPost('email');
$password = $this->request->getPost('password');
$name = $this->request->getPost('name');
$userModel = new UserModel();
$data = [
'email' => $email,
'password_hash' => password_hash($password, PASSWORD_DEFAULT),
'name' => $name,
];
if ($userModel->insert($data)) {
// Registration successful, auto login
$user = $userModel->where('email', $email)->first();
session()->set('user_id', $user['id']);
session()->set('user_email', $user['email']);
return redirect()->to('/dashboard');
} else {
return redirect()->back()->with('error', $userModel->errors());
}
}
public function logout()
{
session()->destroy();
return redirect()->to('/auth/login');
}
}

View File

@@ -34,12 +34,12 @@ abstract class BaseController extends Controller
{ {
// Load here all helpers you want to be available in your controllers that extend BaseController. // Load here all helpers you want to be available in your controllers that extend BaseController.
// Caution: Do not put the this below the parent::initController() call below. // Caution: Do not put the this below the parent::initController() call below.
// $this->helpers = ['form', 'url']; $this->helpers = ['form', 'url'];
// Caution: Do not edit this line. // Caution: Do not edit this line.
parent::initController($request, $response, $logger); parent::initController($request, $response, $logger);
// Preload any models, libraries, etc, here. // Preload any models, libraries, etc, here.
// $this->session = service('session'); $this->session = service('session');
} }
} }

View File

@@ -0,0 +1,59 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateUsersTable extends Migration
{
public function up()
{
$this->forge->addField([
'id' => [
'type' => 'CHAR',
'constraint' => 36,
'null' => false,
],
'email' => [
'type' => 'VARCHAR',
'constraint' => 255,
'null' => false,
],
'password_hash' => [
'type' => 'VARCHAR',
'constraint' => 255,
'null' => false,
],
'name' => [
'type' => 'VARCHAR',
'constraint' => 255,
'null' => true,
],
'avatar_url' => [
'type' => 'TEXT',
'null' => true,
],
'settings' => [
'type' => 'JSON',
'null' => true,
'default' => '{}',
],
'created_at' => [
'type' => 'DATETIME',
'null' => true,
],
'updated_at' => [
'type' => 'DATETIME',
'null' => true,
],
]);
$this->forge->addKey('id', true);
$this->forge->addUniqueKey('email');
$this->forge->createTable('users');
}
public function down()
{
$this->forge->dropTable('users');
}
}

View File

@@ -0,0 +1,53 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateCategoriesTable extends Migration
{
public function up()
{
$this->forge->addField([
'id' => [
'type' => 'CHAR',
'constraint' => 36,
'null' => false,
],
'user_id' => [
'type' => 'CHAR',
'constraint' => 36,
'null' => false,
],
'name' => [
'type' => 'VARCHAR',
'constraint' => 255,
'null' => false,
],
'color' => [
'type' => 'VARCHAR',
'constraint' => 7,
'null' => true,
'comment' => 'Hex color for UI',
],
'favorite' => [
'type' => 'BOOLEAN',
'default' => false,
],
'created_at' => [
'type' => 'DATETIME',
'null' => true,
],
]);
$this->forge->addKey('id', true);
$this->forge->addKey('user_id');
$this->forge->addUniqueKey(['user_id', 'name']);
$this->forge->addForeignKey('user_id', 'users', 'id', 'CASCADE', 'CASCADE');
$this->forge->createTable('categories');
}
public function down()
{
$this->forge->dropTable('categories');
}
}

View File

@@ -0,0 +1,52 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateProjectsTable extends Migration
{
public function up()
{
$this->forge->addField([
'id' => [
'type' => 'CHAR',
'constraint' => 36,
'null' => false,
],
'user_id' => [
'type' => 'CHAR',
'constraint' => 36,
'null' => false,
],
'name' => [
'type' => 'VARCHAR',
'constraint' => 255,
'null' => false,
],
'description' => [
'type' => 'TEXT',
'null' => true,
],
'color' => [
'type' => 'VARCHAR',
'constraint' => 7,
'null' => true,
'comment' => 'Hex color for UI',
],
'created_at' => [
'type' => 'DATETIME',
'null' => true,
],
]);
$this->forge->addKey('id', true);
$this->forge->addKey('user_id');
$this->forge->addForeignKey('user_id', 'users', 'id', 'CASCADE', 'CASCADE');
$this->forge->createTable('projects');
}
public function down()
{
$this->forge->dropTable('projects');
}
}

View File

@@ -0,0 +1,83 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateTodosTable extends Migration
{
public function up()
{
$this->forge->addField([
'id' => [
'type' => 'CHAR',
'constraint' => 36,
'null' => false,
],
'user_id' => [
'type' => 'CHAR',
'constraint' => 36,
'null' => false,
],
'title' => [
'type' => 'VARCHAR',
'constraint' => 255,
'null' => false,
],
'description' => [
'type' => 'TEXT',
'null' => true,
],
'status' => [
'type' => 'ENUM',
'constraint' => ['open', 'in_progress', 'completed', 'archived'],
'default' => 'open',
],
'due_date' => [
'type' => 'DATE',
'null' => true,
],
'due_time' => [
'type' => 'TIME',
'null' => true,
],
'sync_enabled' => [
'type' => 'BOOLEAN',
'default' => true,
],
'reminder_enabled' => [
'type' => 'BOOLEAN',
'default' => false,
],
'recurring_enabled' => [
'type' => 'BOOLEAN',
'default' => false,
],
'project_id' => [
'type' => 'CHAR',
'constraint' => 36,
'null' => true,
],
'created_at' => [
'type' => 'DATETIME',
'null' => true,
],
'updated_at' => [
'type' => 'DATETIME',
'null' => true,
],
]);
$this->forge->addKey('id', true);
$this->forge->addKey('user_id');
$this->forge->addKey('due_date');
$this->forge->addKey('status');
$this->forge->addForeignKey('user_id', 'users', 'id', 'CASCADE', 'CASCADE');
$this->forge->addForeignKey('project_id', 'projects', 'id', 'SET NULL', 'CASCADE');
$this->forge->createTable('todos');
}
public function down()
{
$this->forge->dropTable('todos');
}
}

View File

@@ -0,0 +1,33 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateTodoCategoriesTable extends Migration
{
public function up()
{
$this->forge->addField([
'todo_id' => [
'type' => 'CHAR',
'constraint' => 36,
'null' => false,
],
'category_id' => [
'type' => 'CHAR',
'constraint' => 36,
'null' => false,
],
]);
$this->forge->addPrimaryKey(['todo_id', 'category_id']);
$this->forge->addForeignKey('todo_id', 'todos', 'id', 'CASCADE', 'CASCADE');
$this->forge->addForeignKey('category_id', 'categories', 'id', 'CASCADE', 'CASCADE');
$this->forge->createTable('todo_categories');
}
public function down()
{
$this->forge->dropTable('todo_categories');
}
}

View File

@@ -0,0 +1,64 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateRecurringTasksTable extends Migration
{
public function up()
{
$this->forge->addField([
'id' => [
'type' => 'CHAR',
'constraint' => 36,
'null' => false,
],
'user_id' => [
'type' => 'CHAR',
'constraint' => 36,
'null' => false,
],
'title' => [
'type' => 'VARCHAR',
'constraint' => 255,
'null' => false,
],
'description' => [
'type' => 'TEXT',
'null' => true,
],
'schedule' => [
'type' => 'ENUM',
'constraint' => ['daily', 'weekly', 'monthly', 'custom'],
'null' => false,
],
'custom_days' => [
'type' => 'JSON',
'null' => true,
'comment' => 'Array of days e.g., ["mon","wed","fri"] when schedule=custom',
],
'favorite' => [
'type' => 'BOOLEAN',
'default' => false,
],
'created_at' => [
'type' => 'DATETIME',
'null' => true,
],
'updated_at' => [
'type' => 'DATETIME',
'null' => true,
],
]);
$this->forge->addKey('id', true);
$this->forge->addKey('user_id');
$this->forge->addForeignKey('user_id', 'users', 'id', 'CASCADE', 'CASCADE');
$this->forge->createTable('recurring_tasks');
}
public function down()
{
$this->forge->dropTable('recurring_tasks');
}
}

View File

@@ -0,0 +1,33 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateRecurringTaskCategoriesTable extends Migration
{
public function up()
{
$this->forge->addField([
'recurring_task_id' => [
'type' => 'CHAR',
'constraint' => 36,
'null' => false,
],
'category_id' => [
'type' => 'CHAR',
'constraint' => 36,
'null' => false,
],
]);
$this->forge->addPrimaryKey(['recurring_task_id', 'category_id']);
$this->forge->addForeignKey('recurring_task_id', 'recurring_tasks', 'id', 'CASCADE', 'CASCADE');
$this->forge->addForeignKey('category_id', 'categories', 'id', 'CASCADE', 'CASCADE');
$this->forge->createTable('recurring_task_categories');
}
public function down()
{
$this->forge->dropTable('recurring_task_categories');
}
}

View File

@@ -0,0 +1,73 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateActivityLogsTable extends Migration
{
public function up()
{
$this->forge->addField([
'id' => [
'type' => 'CHAR',
'constraint' => 36,
'null' => false,
],
'user_id' => [
'type' => 'CHAR',
'constraint' => 36,
'null' => true,
'comment' => 'Nullable for anonymous events',
],
'action' => [
'type' => 'VARCHAR',
'constraint' => 255,
'null' => false,
'comment' => 'e.g., todo_created, login, theme_installed',
],
'entity_type' => [
'type' => 'VARCHAR',
'constraint' => 100,
'null' => true,
'comment' => 'todo, category, project, etc.',
],
'entity_id' => [
'type' => 'CHAR',
'constraint' => 36,
'null' => true,
],
'details' => [
'type' => 'JSON',
'null' => true,
'default' => '{}',
'comment' => 'before/after values, metadata',
],
'ip_address' => [
'type' => 'VARCHAR',
'constraint' => 45,
'null' => true,
],
'user_agent' => [
'type' => 'TEXT',
'null' => true,
],
'created_at' => [
'type' => 'DATETIME',
'null' => true,
],
]);
$this->forge->addKey('id', true);
$this->forge->addKey('user_id');
$this->forge->addKey('created_at');
$this->forge->addKey('action');
$this->forge->addKey(['entity_type', 'entity_id']);
$this->forge->addForeignKey('user_id', 'users', 'id', 'SET NULL', 'CASCADE');
$this->forge->createTable('activity_logs');
}
public function down()
{
$this->forge->dropTable('activity_logs');
}
}

View File

@@ -0,0 +1,82 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateMarketplaceThemesTable extends Migration
{
public function up()
{
$this->forge->addField([
'id' => [
'type' => 'CHAR',
'constraint' => 36,
'null' => false,
],
'name' => [
'type' => 'VARCHAR',
'constraint' => 255,
'null' => false,
],
'display_name' => [
'type' => 'VARCHAR',
'constraint' => 255,
'null' => false,
],
'description' => [
'type' => 'TEXT',
'null' => true,
],
'author' => [
'type' => 'VARCHAR',
'constraint' => 255,
'null' => true,
],
'version' => [
'type' => 'VARCHAR',
'constraint' => 50,
'null' => true,
],
'thumbnail_url' => [
'type' => 'TEXT',
'null' => true,
],
'download_url' => [
'type' => 'TEXT',
'null' => false,
],
'price' => [
'type' => 'DECIMAL',
'constraint' => '10,2',
'default' => 0,
],
'is_published' => [
'type' => 'BOOLEAN',
'default' => true,
],
'metadata' => [
'type' => 'JSON',
'null' => true,
'default' => '{}',
'comment' => 'tags, screenshots, etc.',
],
'created_at' => [
'type' => 'DATETIME',
'null' => true,
],
'updated_at' => [
'type' => 'DATETIME',
'null' => true,
],
]);
$this->forge->addKey('id', true);
$this->forge->addUniqueKey('name');
$this->forge->createTable('marketplace_themes');
}
public function down()
{
$this->forge->dropTable('marketplace_themes');
}
}

View File

@@ -0,0 +1,54 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateUserThemesTable extends Migration
{
public function up()
{
$this->forge->addField([
'id' => [
'type' => 'CHAR',
'constraint' => 36,
'null' => false,
],
'user_id' => [
'type' => 'CHAR',
'constraint' => 36,
'null' => false,
],
'theme_id' => [
'type' => 'CHAR',
'constraint' => 36,
'null' => false,
],
'installed_at' => [
'type' => 'DATETIME',
'null' => true,
],
'active' => [
'type' => 'BOOLEAN',
'default' => false,
'comment' => 'Whether this is the user\'s currently active theme',
],
'custom_settings' => [
'type' => 'JSON',
'null' => true,
'default' => '{}',
'comment' => 'User overrides for theme variables',
],
]);
$this->forge->addKey('id', true);
$this->forge->addUniqueKey(['user_id', 'theme_id']);
$this->forge->addForeignKey('user_id', 'users', 'id', 'CASCADE', 'CASCADE');
$this->forge->addForeignKey('theme_id', 'marketplace_themes', 'id', 'CASCADE', 'CASCADE');
$this->forge->createTable('user_themes');
}
public function down()
{
$this->forge->dropTable('user_themes');
}
}

View File

@@ -0,0 +1,52 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateAiProvidersTable extends Migration
{
public function up()
{
$this->forge->addField([
'id' => [
'type' => 'CHAR',
'constraint' => 36,
'null' => false,
],
'name' => [
'type' => 'VARCHAR',
'constraint' => 100,
'null' => false,
'comment' => 'openai, anthropic, google, etc.',
],
'display_name' => [
'type' => 'VARCHAR',
'constraint' => 255,
'null' => false,
],
'base_url' => [
'type' => 'TEXT',
'null' => true,
'comment' => 'Override endpoint',
],
'is_builtin' => [
'type' => 'BOOLEAN',
'default' => true,
'comment' => 'False for user-added custom providers',
],
'created_at' => [
'type' => 'DATETIME',
'null' => true,
],
]);
$this->forge->addKey('id', true);
$this->forge->addUniqueKey('name');
$this->forge->createTable('ai_providers');
}
public function down()
{
$this->forge->dropTable('ai_providers');
}
}

View File

@@ -0,0 +1,62 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateUserApiKeysTable extends Migration
{
public function up()
{
$this->forge->addField([
'id' => [
'type' => 'CHAR',
'constraint' => 36,
'null' => false,
],
'user_id' => [
'type' => 'CHAR',
'constraint' => 36,
'null' => false,
],
'provider_id' => [
'type' => 'CHAR',
'constraint' => 36,
'null' => false,
],
'api_key_encrypted' => [
'type' => 'TEXT',
'null' => false,
'comment' => 'Store encrypted API key',
],
'label' => [
'type' => 'VARCHAR',
'constraint' => 255,
'null' => true,
'comment' => 'e.g., Work OpenAI Key',
],
'is_active' => [
'type' => 'BOOLEAN',
'default' => true,
],
'created_at' => [
'type' => 'DATETIME',
'null' => true,
],
'last_used_at' => [
'type' => 'DATETIME',
'null' => true,
],
]);
$this->forge->addKey('id', true);
$this->forge->addUniqueKey(['user_id', 'provider_id']);
$this->forge->addForeignKey('user_id', 'users', 'id', 'CASCADE', 'CASCADE');
$this->forge->addForeignKey('provider_id', 'ai_providers', 'id', 'CASCADE', 'CASCADE');
$this->forge->createTable('user_api_keys');
}
public function down()
{
$this->forge->dropTable('user_api_keys');
}
}

View File

@@ -0,0 +1,52 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateUserAiSettingsTable extends Migration
{
public function up()
{
$this->forge->addField([
'user_id' => [
'type' => 'CHAR',
'constraint' => 36,
'null' => false,
],
'default_provider_id' => [
'type' => 'CHAR',
'constraint' => 36,
'null' => true,
],
'default_model' => [
'type' => 'VARCHAR',
'constraint' => 100,
'null' => true,
'comment' => 'e.g., gpt-4, claude-3-opus',
],
'max_tokens' => [
'type' => 'INT',
'constraint' => 11,
'default' => 2048,
],
'temperature' => [
'type' => 'FLOAT',
'default' => 0.7,
],
'updated_at' => [
'type' => 'DATETIME',
'null' => true,
],
]);
$this->forge->addPrimaryKey('user_id');
$this->forge->addForeignKey('user_id', 'users', 'id', 'CASCADE', 'CASCADE');
$this->forge->addForeignKey('default_provider_id', 'ai_providers', 'id', 'SET NULL', 'CASCADE');
$this->forge->createTable('user_ai_settings');
}
public function down()
{
$this->forge->dropTable('user_ai_settings');
}
}

View File

@@ -0,0 +1,65 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateAiChatsTable extends Migration
{
public function up()
{
$this->forge->addField([
'id' => [
'type' => 'CHAR',
'constraint' => 36,
'null' => false,
],
'user_id' => [
'type' => 'CHAR',
'constraint' => 36,
'null' => false,
],
'title' => [
'type' => 'VARCHAR',
'constraint' => 255,
'null' => true,
'comment' => 'Generated from first message or user-set',
],
'provider_id' => [
'type' => 'CHAR',
'constraint' => 36,
'null' => true,
],
'model_used' => [
'type' => 'VARCHAR',
'constraint' => 100,
'null' => true,
'comment' => 'Snapshot of model at chat creation',
],
'system_prompt' => [
'type' => 'TEXT',
'null' => true,
'comment' => 'Optional custom system prompt for this chat',
],
'created_at' => [
'type' => 'DATETIME',
'null' => true,
],
'updated_at' => [
'type' => 'DATETIME',
'null' => true,
],
]);
$this->forge->addKey('id', true);
$this->forge->addKey('user_id');
$this->forge->addKey('updated_at');
$this->forge->addForeignKey('user_id', 'users', 'id', 'CASCADE', 'CASCADE');
$this->forge->addForeignKey('provider_id', 'ai_providers', 'id', 'SET NULL', 'CASCADE');
$this->forge->createTable('ai_chats');
}
public function down()
{
$this->forge->dropTable('ai_chats');
}
}

View File

@@ -0,0 +1,52 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateAiMessagesTable extends Migration
{
public function up()
{
$this->forge->addField([
'id' => [
'type' => 'CHAR',
'constraint' => 36,
'null' => false,
],
'chat_id' => [
'type' => 'CHAR',
'constraint' => 36,
'null' => false,
],
'role' => [
'type' => 'ENUM',
'constraint' => ['user', 'assistant', 'system'],
'null' => false,
],
'content' => [
'type' => 'TEXT',
'null' => false,
],
'tokens_used' => [
'type' => 'INT',
'constraint' => 11,
'null' => true,
'comment' => 'Optional token count for billing/analysis',
],
'created_at' => [
'type' => 'DATETIME',
'null' => true,
],
]);
$this->forge->addKey('id', true);
$this->forge->addKey('chat_id');
$this->forge->addForeignKey('chat_id', 'ai_chats', 'id', 'CASCADE', 'CASCADE');
$this->forge->createTable('ai_messages');
}
public function down()
{
$this->forge->dropTable('ai_messages');
}
}

View File

@@ -0,0 +1,40 @@
<?php
namespace App\Database\Seeds;
use CodeIgniter\Database\Seeder;
class AiProvidersSeeder extends Seeder
{
public function run()
{
$data = [
[
'id' => '550e8400-e29b-41d4-a716-446655440001',
'name' => 'openai',
'display_name' => 'OpenAI',
'base_url' => 'https://api.openai.com/v1',
'is_builtin' => true,
'created_at' => date('Y-m-d H:i:s'),
],
[
'id' => '550e8400-e29b-41d4-a716-446655440002',
'name' => 'anthropic',
'display_name' => 'Anthropic',
'base_url' => 'https://api.anthropic.com',
'is_builtin' => true,
'created_at' => date('Y-m-d H:i:s'),
],
[
'id' => '550e8400-e29b-41d4-a716-446655440003',
'name' => 'google',
'display_name' => 'Google AI',
'base_url' => 'https://generativelanguage.googleapis.com/v1',
'is_builtin' => true,
'created_at' => date('Y-m-d H:i:s'),
],
];
$this->db->table('ai_providers')->insertBatch($data);
}
}

View File

@@ -0,0 +1,46 @@
<?php
namespace App\Database\Seeds;
use CodeIgniter\Database\Seeder;
class MarketplaceThemesSeeder extends Seeder
{
public function run()
{
$data = [
[
'id' => '550e8400-e29b-41d4-a716-446655440010',
'name' => 'default-light',
'display_name' => 'Default Light',
'description' => 'Clean and simple light theme',
'author' => 'System',
'version' => '1.0.0',
'thumbnail_url' => null,
'download_url' => '/themes/default-light.zip',
'price' => 0,
'is_published' => true,
'metadata' => json_encode(['tags' => ['light', 'clean']]),
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s'),
],
[
'id' => '550e8400-e29b-41d4-a716-446655440011',
'name' => 'default-dark',
'display_name' => 'Default Dark',
'description' => 'Dark theme for night owls',
'author' => 'System',
'version' => '1.0.0',
'thumbnail_url' => null,
'download_url' => '/themes/default-dark.zip',
'price' => 0,
'is_published' => true,
'metadata' => json_encode(['tags' => ['dark', 'night']]),
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s'),
],
];
$this->db->table('marketplace_themes')->insertBatch($data);
}
}

View File

@@ -0,0 +1,313 @@
<?php
namespace App\Database\Seeds;
use CodeIgniter\Database\Seeder;
class SampleDataSeeder extends Seeder
{
public function run()
{
// Generate a UUID helper function
$generateUuid = function() {
return sprintf(
'%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand(0, 0xffff), mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0x0fff) | 0x4000,
mt_rand(0, 0x3fff) | 0x8000,
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
);
};
// Create a sample user (or get existing one)
$existingUser = $this->db->table('users')->where('email', 'demo@example.com')->get()->getRowArray();
if ($existingUser) {
$userId = $existingUser['id'];
} else {
$userId = $generateUuid();
$this->db->table('users')->insert([
'id' => $userId,
'email' => 'demo@example.com',
'password_hash' => password_hash('password123', PASSWORD_DEFAULT),
'name' => 'Demo User',
'avatar_url' => null,
'settings' => json_encode(['language' => 'en', 'default_view' => 'list']),
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s'),
]);
}
// Create sample categories (check for existing)
$existingCategories = $this->db->table('categories')->where('user_id', $userId)->get()->getResultArray();
$existingCategoryNames = array_column($existingCategories, 'name');
$categories = [];
$categoryNames = ['Work', 'Home', 'Personal'];
$categoryColors = ['#3B82F6', '#10B981', '#F59E0B'];
$categoryFavorites = [true, false, false];
foreach ($categoryNames as $index => $name) {
if (!in_array($name, $existingCategoryNames)) {
$categories[] = [
'id' => $generateUuid(),
'user_id' => $userId,
'name' => $name,
'color' => $categoryColors[$index],
'favorite' => $categoryFavorites[$index],
'created_at' => date('Y-m-d H:i:s'),
];
}
}
if (!empty($categories)) {
$this->db->table('categories')->insertBatch($categories);
}
// Get all categories for the user (existing + newly created)
$allCategories = $this->db->table('categories')->where('user_id', $userId)->get()->getResultArray();
$categories = [];
foreach ($categoryNames as $name) {
foreach ($allCategories as $cat) {
if ($cat['name'] === $name) {
$categories[] = $cat;
break;
}
}
}
// Create sample projects (check for existing)
$existingProjects = $this->db->table('projects')->where('user_id', $userId)->get()->getResultArray();
$existingProjectNames = array_column($existingProjects, 'name');
$projects = [];
$projectData = [
['name' => 'Web Redesign', 'description' => 'Redesign the company website', 'color' => '#8B5CF6'],
['name' => 'Home Renovation', 'description' => 'Renovate the kitchen and bathroom', 'color' => '#EC4899'],
['name' => 'Learning', 'description' => 'Learn new technologies and skills', 'color' => '#14B8A6'],
];
foreach ($projectData as $proj) {
if (!in_array($proj['name'], $existingProjectNames)) {
$projects[] = [
'id' => $generateUuid(),
'user_id' => $userId,
'name' => $proj['name'],
'description' => $proj['description'],
'color' => $proj['color'],
'created_at' => date('Y-m-d H:i:s'),
];
}
}
if (!empty($projects)) {
$this->db->table('projects')->insertBatch($projects);
}
// Get all projects for the user
$allProjects = $this->db->table('projects')->where('user_id', $userId)->get()->getResultArray();
$projects = [];
foreach ($projectData as $proj) {
foreach ($allProjects as $p) {
if ($p['name'] === $proj['name']) {
$projects[] = $p;
break;
}
}
}
$webRedesignId = isset($projects[0]) ? $projects[0]['id'] : null;
$homeRenovationId = isset($projects[1]) ? $projects[1]['id'] : null;
$learningId = isset($projects[2]) ? $projects[2]['id'] : null;
// Create sample todos (check for existing)
$existingTodos = $this->db->table('todos')->where('user_id', $userId)->get()->getResultArray();
$existingTodoTitles = array_column($existingTodos, 'title');
$todos = [];
$todoData = [
[
'title' => 'Bestehende Aufgaben analysieren',
'description' => 'Aktuellen Aufbau der Todo-App sichten und Felder abstimmen.',
'status' => 'open',
'due_date' => date('Y-m-d', strtotime('+7 days')),
'due_time' => '10:30:00',
'sync_enabled' => true,
'reminder_enabled' => false,
'recurring_enabled' => false,
'project_id' => $webRedesignId,
],
[
'title' => 'Wireframes erstellen',
'description' => 'Erste Skizzen für das neue Design machen.',
'status' => 'in_progress',
'due_date' => date('Y-m-d', strtotime('+14 days')),
'sync_enabled' => true,
'reminder_enabled' => true,
'recurring_enabled' => false,
'project_id' => $webRedesignId,
],
[
'title' => 'Küche planen',
'description' => 'Neue Küche auswählen und bestellen.',
'status' => 'open',
'due_date' => date('Y-m-d', strtotime('+30 days')),
'sync_enabled' => false,
'reminder_enabled' => true,
'recurring_enabled' => false,
'project_id' => $homeRenovationId,
],
[
'title' => 'CodeIgniter lernen',
'description' => 'Offizielle Dokumentation durchgehen.',
'status' => 'completed',
'due_date' => date('Y-m-d', strtotime('-5 days')),
'sync_enabled' => true,
'reminder_enabled' => false,
'recurring_enabled' => false,
'project_id' => $learningId,
],
[
'title' => 'Einkaufen',
'description' => 'Milch, Brot, Eier, Gemüse',
'status' => 'open',
'due_date' => date('Y-m-d', strtotime('+1 day')),
'sync_enabled' => true,
'reminder_enabled' => true,
'recurring_enabled' => false,
'project_id' => null,
],
];
foreach ($todoData as $todo) {
if (!in_array($todo['title'], $existingTodoTitles)) {
$todos[] = array_merge($todo, [
'id' => $generateUuid(),
'user_id' => $userId,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s'),
]);
}
}
if (!empty($todos)) {
$this->db->table('todos')->insertBatch($todos);
}
// Get all todos for the user
$allTodos = $this->db->table('todos')->where('user_id', $userId)->get()->getResultArray();
// Link todos to categories
$workCategoryId = $categories[0]['id'];
$homeCategoryId = $categories[1]['id'];
$personalCategoryId = $categories[2]['id'];
$todoCategories = [];
$todoCategoryMap = [
'Bestehende Aufgaben analysieren' => $workCategoryId,
'Wireframes erstellen' => $workCategoryId,
'Küche planen' => $homeCategoryId,
'CodeIgniter lernen' => $workCategoryId,
'Einkaufen' => $personalCategoryId,
];
foreach ($allTodos as $todo) {
if (isset($todoCategoryMap[$todo['title']])) {
// Check if this link already exists
$existingLink = $this->db->table('todo_categories')
->where('todo_id', $todo['id'])
->where('category_id', $todoCategoryMap[$todo['title']])
->get()
->getRowArray();
if (!$existingLink) {
$todoCategories[] = [
'todo_id' => $todo['id'],
'category_id' => $todoCategoryMap[$todo['title']],
];
}
}
}
if (!empty($todoCategories)) {
$this->db->table('todo_categories')->insertBatch($todoCategories);
}
// Create sample recurring tasks (check for existing)
$existingRecurringTasks = $this->db->table('recurring_tasks')->where('user_id', $userId)->get()->getResultArray();
$existingRecurringTaskTitles = array_column($existingRecurringTasks, 'title');
$recurringTasks = [];
$recurringTaskData = [
[
'title' => 'Weekly review',
'description' => 'Plan next week\'s tasks',
'schedule' => 'weekly',
'custom_days' => json_encode([]),
'favorite' => true,
],
[
'title' => 'Clean the house',
'description' => 'Every Saturday',
'schedule' => 'custom',
'custom_days' => json_encode(['sat']),
'favorite' => false,
],
[
'title' => 'Daily standup',
'description' => 'Team meeting every morning',
'schedule' => 'daily',
'custom_days' => json_encode([]),
'favorite' => true,
],
];
foreach ($recurringTaskData as $task) {
if (!in_array($task['title'], $existingRecurringTaskTitles)) {
$recurringTasks[] = array_merge($task, [
'id' => $generateUuid(),
'user_id' => $userId,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s'),
]);
}
}
if (!empty($recurringTasks)) {
$this->db->table('recurring_tasks')->insertBatch($recurringTasks);
}
// Get all recurring tasks for the user
$allRecurringTasks = $this->db->table('recurring_tasks')->where('user_id', $userId)->get()->getResultArray();
// Link recurring tasks to categories
$recurringTaskCategories = [];
$recurringTaskCategoryMap = [
'Weekly review' => $workCategoryId,
'Clean the house' => $homeCategoryId,
'Daily standup' => $workCategoryId,
];
foreach ($allRecurringTasks as $task) {
if (isset($recurringTaskCategoryMap[$task['title']])) {
// Check if this link already exists
$existingLink = $this->db->table('recurring_task_categories')
->where('recurring_task_id', $task['id'])
->where('category_id', $recurringTaskCategoryMap[$task['title']])
->get()
->getRowArray();
if (!$existingLink) {
$recurringTaskCategories[] = [
'recurring_task_id' => $task['id'],
'category_id' => $recurringTaskCategoryMap[$task['title']],
];
}
}
}
if (!empty($recurringTaskCategories)) {
$this->db->table('recurring_task_categories')->insertBatch($recurringTaskCategories);
}
}
}

View File

@@ -0,0 +1,97 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class ActivityLogModel extends Model
{
protected $table = 'activity_logs';
protected $primaryKey = 'id';
protected $useAutoIncrement = false;
protected $returnType = 'array';
protected $useSoftDeletes = false;
protected $allowedFields = [
'id',
'user_id',
'action',
'entity_type',
'entity_id',
'details',
'ip_address',
'user_agent',
'created_at',
];
protected $useTimestamps = true;
protected $createdField = 'created_at';
protected $updatedField = null;
protected $validationRules = [
'action' => 'required|max_length[255]',
];
// Log an activity
public function logActivity($data)
{
// Disable events to prevent any recursive logging
$this->skipEvents();
if (!isset($data['id'])) {
$data['id'] = $this->generateUuid();
}
if (!isset($data['created_at'])) {
$data['created_at'] = date('Y-m-d H:i:s');
}
$result = $this->insert($data);
// Re-enable events
$this->skipEvents(false);
return $result;
}
// Get logs by user
public function getByUser($userId, $limit = 50)
{
return $this->where('user_id', $userId)
->orderBy('created_at', 'DESC')
->limit($limit)
->get()
->getResultArray();
}
// Get logs by entity
public function getByEntity($entityType, $entityId, $limit = 50)
{
return $this->where('entity_type', $entityType)
->where('entity_id', $entityId)
->orderBy('created_at', 'DESC')
->limit($limit)
->get()
->getResultArray();
}
// Get logs by action
public function getByAction($action, $limit = 50)
{
return $this->where('action', $action)
->orderBy('created_at', 'DESC')
->limit($limit)
->get()
->getResultArray();
}
private function generateUuid()
{
return sprintf(
'%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand(0, 0xffff), mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0x0fff) | 0x4000,
mt_rand(0, 0x3fff) | 0x8000,
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
);
}
}

105
app/Models/AiChatModel.php Normal file
View File

@@ -0,0 +1,105 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class AiChatModel extends Model
{
protected $table = 'ai_chats';
protected $primaryKey = 'id';
protected $useAutoIncrement = false;
protected $returnType = 'array';
protected $useSoftDeletes = false;
protected $allowedFields = [
'id',
'user_id',
'title',
'provider_id',
'model_used',
'system_prompt',
'created_at',
'updated_at',
];
protected $useTimestamps = true;
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
protected $validationRules = [
'user_id' => 'required',
];
// Get chats by user
public function getByUser($userId, $limit = 50)
{
return $this->where('user_id', $userId)
->orderBy('updated_at', 'DESC')
->limit($limit)
->get()
->getResultArray();
}
// Get chat with message count
public function getWithMessageCount($chatId)
{
$chat = $this->find($chatId);
if ($chat) {
$messageModel = new AiMessageModel();
$chat['message_count'] = $messageModel->where('chat_id', $chatId)->countAllResults();
}
return $chat;
}
// Get all chats by user with message counts
public function getByUserWithMessageCounts($userId)
{
$chats = $this->getByUser($userId);
$messageModel = new AiMessageModel();
foreach ($chats as &$chat) {
$chat['message_count'] = $messageModel->where('chat_id', $chat['id'])->countAllResults();
}
return $chats;
}
// Get chat with provider info
public function getWithProvider($chatId)
{
return $this->select('ai_chats.*, ai_providers.name as provider_name, ai_providers.display_name')
->join('ai_providers', 'ai_chats.provider_id = ai_providers.id', 'left')
->where('ai_chats.id', $chatId)
->get()
->getRowArray();
}
// Update chat title
public function updateTitle($chatId, $title)
{
return $this->update($chatId, ['title' => $title]);
}
// Create new chat
public function createChat($userId, $data = [])
{
$data['id'] = $this->generateUuid();
$data['user_id'] = $userId;
$data['created_at'] = date('Y-m-d H:i:s');
$data['updated_at'] = date('Y-m-d H:i:s');
return $this->insert($data);
}
private function generateUuid()
{
return sprintf(
'%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand(0, 0xffff), mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0x0fff) | 0x4000,
mt_rand(0, 0x3fff) | 0x8000,
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
);
}
}

View File

@@ -0,0 +1,93 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class AiMessageModel extends Model
{
protected $table = 'ai_messages';
protected $primaryKey = 'id';
protected $useAutoIncrement = false;
protected $returnType = 'array';
protected $useSoftDeletes = false;
protected $allowedFields = [
'id',
'chat_id',
'role',
'content',
'tokens_used',
'created_at',
];
protected $useTimestamps = true;
protected $createdField = 'created_at';
protected $updatedField = null;
protected $validationRules = [
'chat_id' => 'required',
'role' => 'required|in_list[user,assistant,system]',
'content' => 'required',
];
// Get messages by chat
public function getByChat($chatId)
{
return $this->where('chat_id', $chatId)
->orderBy('created_at', 'ASC')
->get()
->getResultArray();
}
// Add message to chat
public function addMessage($chatId, $role, $content, $tokensUsed = null)
{
return $this->insert([
'id' => $this->generateUuid(),
'chat_id' => $chatId,
'role' => $role,
'content' => $content,
'tokens_used' => $tokensUsed,
'created_at' => date('Y-m-d H:i:s'),
]);
}
// Get last message from chat
public function getLastMessage($chatId)
{
return $this->where('chat_id', $chatId)
->orderBy('created_at', 'DESC')
->limit(1)
->get()
->getRowArray();
}
// Delete all messages from chat
public function deleteByChat($chatId)
{
return $this->where('chat_id', $chatId)->delete();
}
// Get total tokens used by chat
public function getTotalTokens($chatId)
{
$result = $this->selectSum('tokens_used')
->where('chat_id', $chatId)
->get()
->getRowArray();
return $result ? (int) $result['tokens_used'] : 0;
}
private function generateUuid()
{
return sprintf(
'%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand(0, 0xffff), mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0x0fff) | 0x4000,
mt_rand(0, 0x3fff) | 0x8000,
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
);
}
}

View File

@@ -0,0 +1,57 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class AiProviderModel extends Model
{
protected $table = 'ai_providers';
protected $primaryKey = 'id';
protected $useAutoIncrement = false;
protected $returnType = 'array';
protected $useSoftDeletes = false;
protected $allowedFields = [
'id',
'name',
'display_name',
'base_url',
'is_builtin',
'created_at',
];
protected $useTimestamps = true;
protected $createdField = 'created_at';
protected $updatedField = null;
protected $validationRules = [
'name' => 'required|max_length[100]|is_unique[ai_providers.name]',
'display_name' => 'required|max_length[255]',
];
// Get builtin providers only
public function getBuiltinProviders()
{
return $this->where('is_builtin', true)
->orderBy('name', 'ASC')
->get()
->getResultArray();
}
// Get custom providers only
public function getCustomProviders()
{
return $this->where('is_builtin', false)
->orderBy('name', 'ASC')
->get()
->getResultArray();
}
// Get provider by name
public function getByName($name)
{
return $this->where('name', $name)
->get()
->getRowArray();
}
}

View File

@@ -0,0 +1,38 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class CategoryModel extends Model
{
use LoggableTrait;
protected $table = 'categories';
protected $primaryKey = 'id';
protected $useAutoIncrement = false;
protected $returnType = 'array';
protected $useSoftDeletes = false;
protected $allowedFields = [
'id',
'user_id',
'name',
'color',
'favorite',
'created_at',
];
protected $useTimestamps = true;
protected $createdField = 'created_at';
protected $updatedField = null;
protected $validationRules = [
'user_id' => 'required',
'name' => 'required|max_length[255]',
];
protected function getEntityType(): string
{
return 'category';
}
}

View File

@@ -0,0 +1,142 @@
<?php
namespace App\Models;
trait LoggableTrait
{
/**
* Log activity after insert
*/
protected function afterInsert(array $data)
{
try {
$this->logActivity('created', $data);
} catch (\Exception $e) {
// Silently fail to avoid breaking the main operation
log_message('error', 'Failed to log activity: ' . $e->getMessage());
}
return $data;
}
/**
* Log activity after update
*/
protected function afterUpdate(array $data)
{
try {
$this->logActivity('updated', $data);
} catch (\Exception $e) {
log_message('error', 'Failed to log activity: ' . $e->getMessage());
}
return $data;
}
/**
* Log activity after delete
*/
protected function afterDelete(array $data)
{
try {
$this->logActivity('deleted', $data);
} catch (\Exception $e) {
log_message('error', 'Failed to log activity: ' . $e->getMessage());
}
return $data;
}
/**
* Log activity to activity_logs table
*/
protected function logActivity($action, $data)
{
$activityLogModel = new ActivityLogModel();
$entityType = $this->getEntityType();
$entityId = $data['id'] ?? $data[$this->primaryKey] ?? null;
$userId = $data['user_id'] ?? null;
// Try to get user from session if not in data
if ($userId === null && function_exists('session')) {
$userId = session()->get('user_id');
}
$logData = [
'user_id' => $userId,
'action' => $this->getActionName($action, $entityType),
'entity_type' => $entityType,
'entity_id' => $entityId,
'details' => json_encode($this->getLogDetails($action, $data)),
'ip_address' => $this->getClientIp(),
'user_agent' => $this->getUserAgent(),
];
$activityLogModel->logActivity($logData);
}
/**
* Get entity type based on table name
*/
protected function getEntityType(): string
{
$table = $this->table;
// Remove plural 's' if present
return rtrim($table, 's');
}
/**
* Get formatted action name
*/
protected function getActionName($action, $entityType): string
{
return "{$entityType}_{$action}";
}
/**
* Get log details (can be overridden in models)
*/
protected function getLogDetails($action, $data): array
{
$details = [
'action' => $action,
];
// Add relevant fields based on entity type
if (isset($data['title'])) {
$details['title'] = $data['title'];
}
if (isset($data['name'])) {
$details['name'] = $data['name'];
}
if (isset($data['email'])) {
$details['email'] = $data['email'];
}
return $details;
}
/**
* Get client IP address
*/
protected function getClientIp(): ?string
{
try {
$request = \Config\Services::request();
return $request->getIPAddress();
} catch (\Exception $e) {
return 'CLI';
}
}
/**
* Get user agent
*/
protected function getUserAgent(): ?string
{
try {
$request = \Config\Services::request();
return $request->getUserAgent()->toString();
} catch (\Exception $e) {
return 'CLI/Script';
}
}
}

View File

@@ -0,0 +1,68 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class MarketplaceThemeModel extends Model
{
protected $table = 'marketplace_themes';
protected $primaryKey = 'id';
protected $useAutoIncrement = false;
protected $returnType = 'array';
protected $useSoftDeletes = false;
protected $allowedFields = [
'id',
'name',
'display_name',
'description',
'author',
'version',
'thumbnail_url',
'download_url',
'price',
'is_published',
'metadata',
'created_at',
'updated_at',
];
protected $useTimestamps = true;
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
protected $validationRules = [
'name' => 'required|max_length[255]|is_unique[marketplace_themes.name]',
'display_name' => 'required|max_length[255]',
'download_url' => 'required',
];
// Get published themes only
public function getPublished()
{
return $this->where('is_published', true)
->orderBy('created_at', 'DESC')
->get()
->getResultArray();
}
// Get free themes
public function getFreeThemes()
{
return $this->where('price', 0)
->where('is_published', true)
->orderBy('created_at', 'DESC')
->get()
->getResultArray();
}
// Get paid themes
public function getPaidThemes()
{
return $this->where('price >', 0)
->where('is_published', true)
->orderBy('price', 'ASC')
->get()
->getResultArray();
}
}

View File

@@ -0,0 +1,38 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class ProjectModel extends Model
{
use LoggableTrait;
protected $table = 'projects';
protected $primaryKey = 'id';
protected $useAutoIncrement = false;
protected $returnType = 'array';
protected $useSoftDeletes = false;
protected $allowedFields = [
'id',
'user_id',
'name',
'description',
'color',
'created_at',
];
protected $useTimestamps = true;
protected $createdField = 'created_at';
protected $updatedField = null;
protected $validationRules = [
'user_id' => 'required',
'name' => 'required|max_length[255]',
];
protected function getEntityType(): string
{
return 'project';
}
}

View File

@@ -0,0 +1,57 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class RecurringTaskCategoryModel extends Model
{
protected $table = 'recurring_task_categories';
protected $primaryKey = 'recurring_task_id'; // Composite primary key
protected $useAutoIncrement = false;
protected $returnType = 'array';
protected $useSoftDeletes = false;
protected $allowedFields = [
'recurring_task_id',
'category_id',
];
protected $useTimestamps = false;
// Add category to recurring task
public function addCategoryToTask($taskId, $categoryId)
{
return $this->insert([
'recurring_task_id' => $taskId,
'category_id' => $categoryId,
]);
}
// Remove category from recurring task
public function removeCategoryFromTask($taskId, $categoryId)
{
return $this->where('recurring_task_id', $taskId)
->where('category_id', $categoryId)
->delete();
}
// Get categories for a recurring task
public function getCategoriesForTask($taskId)
{
return $this->select('categories.*')
->join('categories', 'recurring_task_categories.category_id = categories.id')
->where('recurring_task_categories.recurring_task_id', $taskId)
->get()
->getResultArray();
}
// Get recurring tasks for a category
public function getTasksForCategory($categoryId)
{
return $this->select('recurring_tasks.*')
->join('recurring_tasks', 'recurring_task_categories.recurring_task_id = recurring_tasks.id')
->where('recurring_task_categories.category_id', $categoryId)
->get()
->getResultArray();
}
}

View File

@@ -0,0 +1,69 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class RecurringTaskModel extends Model
{
use LoggableTrait;
protected $table = 'recurring_tasks';
protected $primaryKey = 'id';
protected $useAutoIncrement = false;
protected $returnType = 'array';
protected $useSoftDeletes = false;
protected $allowedFields = [
'id',
'user_id',
'title',
'description',
'schedule',
'custom_days',
'favorite',
'created_at',
'updated_at',
];
protected $useTimestamps = true;
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
protected $validationRules = [
'user_id' => 'required',
'title' => 'required|max_length[255]',
'schedule' => 'required|in_list[daily,weekly,monthly,custom]',
];
protected function getEntityType(): string
{
return 'recurring_task';
}
// Get recurring tasks with categories
public function getWithCategories($taskId = null)
{
$builder = $this->select('recurring_tasks.*, GROUP_CONCAT(categories.name) as category_names')
->join('recurring_task_categories', 'recurring_tasks.id = recurring_task_categories.recurring_task_id', 'left')
->join('categories', 'recurring_task_categories.category_id = categories.id', 'left')
->groupBy('recurring_tasks.id');
if ($taskId) {
$builder->where('recurring_tasks.id', $taskId);
}
return $builder->get()->getResultArray();
}
// Get recurring tasks by user with categories
public function getByUserWithCategories($userId)
{
return $this->select('recurring_tasks.*, GROUP_CONCAT(categories.name) as category_names')
->join('recurring_task_categories', 'recurring_tasks.id = recurring_task_categories.recurring_task_id', 'left')
->join('categories', 'recurring_task_categories.category_id = categories.id', 'left')
->where('recurring_tasks.user_id', $userId)
->groupBy('recurring_tasks.id')
->get()
->getResultArray();
}
}

View File

@@ -0,0 +1,57 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class TodoCategoryModel extends Model
{
protected $table = 'todo_categories';
protected $primaryKey = 'todo_id'; // Composite primary key
protected $useAutoIncrement = false;
protected $returnType = 'array';
protected $useSoftDeletes = false;
protected $allowedFields = [
'todo_id',
'category_id',
];
protected $useTimestamps = false;
// Add category to todo
public function addCategoryToTodo($todoId, $categoryId)
{
return $this->insert([
'todo_id' => $todoId,
'category_id' => $categoryId,
]);
}
// Remove category from todo
public function removeCategoryFromTodo($todoId, $categoryId)
{
return $this->where('todo_id', $todoId)
->where('category_id', $categoryId)
->delete();
}
// Get categories for a todo
public function getCategoriesForTodo($todoId)
{
return $this->select('categories.*')
->join('categories', 'todo_categories.category_id = categories.id')
->where('todo_categories.todo_id', $todoId)
->get()
->getResultArray();
}
// Get todos for a category
public function getTodosForCategory($categoryId)
{
return $this->select('todos.*')
->join('todos', 'todo_categories.todo_id = todos.id')
->where('todo_categories.category_id', $categoryId)
->get()
->getResultArray();
}
}

73
app/Models/TodoModel.php Normal file
View File

@@ -0,0 +1,73 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class TodoModel extends Model
{
use LoggableTrait;
protected $table = 'todos';
protected $primaryKey = 'id';
protected $useAutoIncrement = false;
protected $returnType = 'array';
protected $useSoftDeletes = false;
protected $allowedFields = [
'id',
'user_id',
'title',
'description',
'status',
'due_date',
'due_time',
'sync_enabled',
'reminder_enabled',
'recurring_enabled',
'project_id',
'created_at',
'updated_at',
];
protected $useTimestamps = true;
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
protected $validationRules = [
'user_id' => 'required',
'title' => 'required|max_length[255]',
'status' => 'permit_empty|in_list[open,in_progress,completed,archived]',
];
protected function getEntityType(): string
{
return 'todo';
}
// Get todos with categories
public function getWithCategories($todoId = null)
{
$builder = $this->select('todos.*, GROUP_CONCAT(categories.name) as category_names')
->join('todo_categories', 'todos.id = todo_categories.todo_id', 'left')
->join('categories', 'todo_categories.category_id = categories.id', 'left')
->groupBy('todos.id');
if ($todoId) {
$builder->where('todos.id', $todoId);
}
return $builder->get()->getResultArray();
}
// Get todos by user with categories
public function getByUserWithCategories($userId)
{
return $this->select('todos.*, GROUP_CONCAT(categories.name) as category_names')
->join('todo_categories', 'todos.id = todo_categories.todo_id', 'left')
->join('categories', 'todo_categories.category_id = categories.id', 'left')
->where('todos.user_id', $userId)
->groupBy('todos.id')
->get()
->getResultArray();
}
}

View File

@@ -0,0 +1,68 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class UserAiSettingsModel extends Model
{
protected $table = 'user_ai_settings';
protected $primaryKey = 'user_id';
protected $useAutoIncrement = false;
protected $returnType = 'array';
protected $useSoftDeletes = false;
protected $allowedFields = [
'user_id',
'default_provider_id',
'default_model',
'max_tokens',
'temperature',
'updated_at',
];
protected $useTimestamps = false;
protected $validationRules = [
'user_id' => 'required',
'max_tokens' => 'permit_empty|integer|greater_than[0]',
'temperature' => 'permit_empty|numeric|greater_than_equal_to[0]|less_than_equal_to[2]',
];
// Get or create settings for user
public function getSettings($userId)
{
$settings = $this->find($userId);
if (!$settings) {
// Create default settings
$this->insert([
'user_id' => $userId,
'default_provider_id' => null,
'default_model' => null,
'max_tokens' => 2048,
'temperature' => 0.7,
'updated_at' => date('Y-m-d H:i:s'),
]);
$settings = $this->find($userId);
}
return $settings;
}
// Update settings for user
public function updateSettings($userId, $data)
{
$data['updated_at'] = date('Y-m-d H:i:s');
return $this->update($userId, $data);
}
// Get settings with provider info
public function getSettingsWithProvider($userId)
{
return $this->select('user_ai_settings.*, ai_providers.name as provider_name, ai_providers.display_name')
->join('ai_providers', 'user_ai_settings.default_provider_id = ai_providers.id', 'left')
->where('user_ai_settings.user_id', $userId)
->get()
->getRowArray();
}
}

View File

@@ -0,0 +1,108 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class UserApiKeyModel extends Model
{
protected $table = 'user_api_keys';
protected $primaryKey = 'id';
protected $useAutoIncrement = false;
protected $returnType = 'array';
protected $useSoftDeletes = false;
protected $allowedFields = [
'id',
'user_id',
'provider_id',
'api_key_encrypted',
'label',
'is_active',
'created_at',
'last_used_at',
];
protected $useTimestamps = false;
protected $validationRules = [
'user_id' => 'required',
'provider_id' => 'required',
'api_key_encrypted' => 'required',
];
// Save or update API key for user and provider
public function saveApiKey($userId, $providerId, $encryptedKey, $label = null)
{
$existing = $this->where('user_id', $userId)
->where('provider_id', $providerId)
->first();
if ($existing) {
return $this->update($existing['id'], [
'api_key_encrypted' => $encryptedKey,
'label' => $label,
'is_active' => true,
'last_used_at' => null,
]);
} else {
return $this->insert([
'id' => $this->generateUuid(),
'user_id' => $userId,
'provider_id' => $providerId,
'api_key_encrypted' => $encryptedKey,
'label' => $label,
'is_active' => true,
'created_at' => date('Y-m-d H:i:s'),
'last_used_at' => null,
]);
}
}
// Get API key for user and provider
public function getApiKey($userId, $providerId)
{
return $this->where('user_id', $userId)
->where('provider_id', $providerId)
->where('is_active', true)
->first();
}
// Get all API keys for user
public function getUserApiKeys($userId)
{
return $this->select('user_api_keys.*, ai_providers.name as provider_name, ai_providers.display_name')
->join('ai_providers', 'user_api_keys.provider_id = ai_providers.id')
->where('user_api_keys.user_id', $userId)
->orderBy('user_api_keys.created_at', 'DESC')
->get()
->getResultArray();
}
// Deactivate API key
public function deactivateApiKey($userId, $providerId)
{
return $this->where('user_id', $userId)
->where('provider_id', $providerId)
->update(['is_active' => false]);
}
// Update last used timestamp
public function updateLastUsed($userId, $providerId)
{
return $this->where('user_id', $userId)
->where('provider_id', $providerId)
->update(['last_used_at' => date('Y-m-d H:i:s')]);
}
private function generateUuid()
{
return sprintf(
'%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand(0, 0xffff), mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0x0fff) | 0x4000,
mt_rand(0, 0x3fff) | 0x8000,
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
);
}
}

48
app/Models/UserModel.php Normal file
View File

@@ -0,0 +1,48 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class UserModel extends Model
{
use LoggableTrait;
protected $table = 'users';
protected $primaryKey = 'id';
protected $useAutoIncrement = false;
protected $returnType = 'array';
protected $useSoftDeletes = false;
protected $allowedFields = [
'id',
'email',
'password_hash',
'name',
'avatar_url',
'settings',
'created_at',
'updated_at',
];
protected $useTimestamps = true;
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
protected $validationRules = [
'email' => 'required|valid_email|is_unique[users.email]',
'password_hash' => 'required',
];
protected $validationMessages = [
'email' => [
'required' => 'Email is required',
'valid_email' => 'Please enter a valid email address',
'is_unique' => 'This email is already registered',
],
];
protected function getEntityType(): string
{
return 'user';
}
}

View File

@@ -0,0 +1,104 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class UserThemeModel extends Model
{
protected $table = 'user_themes';
protected $primaryKey = 'id';
protected $useAutoIncrement = false;
protected $returnType = 'array';
protected $useSoftDeletes = false;
protected $allowedFields = [
'id',
'user_id',
'theme_id',
'installed_at',
'active',
'custom_settings',
];
protected $useTimestamps = false;
protected $validationRules = [
'user_id' => 'required',
'theme_id' => 'required',
];
// Install theme for user
public function installTheme($userId, $themeId)
{
return $this->insert([
'id' => $this->generateUuid(),
'user_id' => $userId,
'theme_id' => $themeId,
'installed_at' => date('Y-m-d H:i:s'),
'active' => false,
'custom_settings' => json_encode([]),
]);
}
// Uninstall theme for user
public function uninstallTheme($userId, $themeId)
{
return $this->where('user_id', $userId)
->where('theme_id', $themeId)
->delete();
}
// Set active theme for user
public function setActiveTheme($userId, $themeId)
{
// Deactivate all themes for user
$this->where('user_id', $userId)->update(['active' => false]);
// Activate the specified theme
return $this->where('user_id', $userId)
->where('theme_id', $themeId)
->update(['active' => true]);
}
// Get active theme for user
public function getActiveTheme($userId)
{
return $this->select('user_themes.*, marketplace_themes.*')
->join('marketplace_themes', 'user_themes.theme_id = marketplace_themes.id')
->where('user_themes.user_id', $userId)
->where('user_themes.active', true)
->get()
->getRowArray();
}
// Get all installed themes for user
public function getUserThemes($userId)
{
return $this->select('user_themes.*, marketplace_themes.*')
->join('marketplace_themes', 'user_themes.theme_id = marketplace_themes.id')
->where('user_themes.user_id', $userId)
->orderBy('user_themes.installed_at', 'DESC')
->get()
->getResultArray();
}
// Check if theme is installed for user
public function isInstalled($userId, $themeId)
{
return $this->where('user_id', $userId)
->where('theme_id', $themeId)
->countAllResults() > 0;
}
private function generateUuid()
{
return sprintf(
'%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand(0, 0xffff), mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0x0fff) | 0x4000,
mt_rand(0, 0x3fff) | 0x8000,
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
);
}
}

View File

@@ -0,0 +1,181 @@
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Anmelden / Registrieren - Todo App</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
<style>
body {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
.auth-container {
background: white;
border-radius: 15px;
box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
overflow: hidden;
max-width: 450px;
width: 100%;
}
.auth-header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 2rem;
text-align: center;
}
.auth-header h2 {
margin: 0;
font-weight: 600;
}
.auth-body {
padding: 2rem;
}
.nav-tabs {
border: none;
justify-content: center;
margin-bottom: 2rem;
}
.nav-tabs .nav-link {
border: none;
color: #6c757d;
font-weight: 500;
padding: 0.75rem 2rem;
border-radius: 25px;
margin: 0 0.25rem;
transition: all 0.3s ease;
}
.nav-tabs .nav-link.active {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
}
.form-control {
border-radius: 25px;
padding: 0.75rem 1.25rem;
border: 2px solid #e9ecef;
transition: all 0.3s ease;
}
.form-control:focus {
border-color: #667eea;
box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
}
.input-group-text {
border-radius: 25px 0 0 25px;
border: 2px solid #e9ecef;
background: #f8f9fa;
border-right: none;
}
.form-control:focus + .input-group-text {
border-color: #667eea;
}
.btn-primary {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border: none;
border-radius: 25px;
padding: 0.75rem 2rem;
font-weight: 600;
transition: all 0.3s ease;
width: 100%;
}
.btn-primary:hover {
transform: translateY(-2px);
box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
}
.alert {
border-radius: 10px;
border: none;
}
.tab-content {
min-height: 300px;
}
</style>
</head>
<body>
<div class="auth-container">
<div class="auth-header">
<h2><i class="fas fa-tasks me-2"></i>Todo App</h2>
<p>Melde dich an oder erstelle ein Konto</p>
</div>
<div class="auth-body">
<?php if (session()->getFlashdata('error')): ?>
<div class="alert alert-danger">
<i class="fas fa-exclamation-triangle me-2"></i>
<?= is_array(session()->getFlashdata('error')) ? implode('<br>', session()->getFlashdata('error')) : session()->getFlashdata('error') ?>
</div>
<?php endif; ?>
<ul class="nav nav-tabs" id="authTabs" role="tablist">
<li class="nav-item" role="presentation">
<button class="nav-link active" id="login-tab" data-bs-toggle="tab" data-bs-target="#login" type="button" role="tab">Anmelden</button>
</li>
<li class="nav-item" role="presentation">
<button class="nav-link" id="register-tab" data-bs-toggle="tab" data-bs-target="#register" type="button" role="tab">Registrieren</button>
</li>
</ul>
<div class="tab-content" id="authTabsContent">
<div class="tab-pane fade show active" id="login" role="tabpanel">
<form action="/auth/attemptLogin" method="post">
<?= csrf_field() ?>
<div class="mb-3">
<label for="login-email" class="form-label">E-Mail-Adresse</label>
<div class="input-group">
<span class="input-group-text"><i class="fas fa-envelope"></i></span>
<input type="email" class="form-control" id="login-email" name="email" placeholder="deine@email.com" required>
</div>
</div>
<div class="mb-4">
<label for="login-password" class="form-label">Passwort</label>
<div class="input-group">
<span class="input-group-text"><i class="fas fa-lock"></i></span>
<input type="password" class="form-control" id="login-password" name="password" placeholder="Dein Passwort" required>
</div>
</div>
<button type="submit" class="btn btn-primary">
<i class="fas fa-sign-in-alt me-2"></i>Anmelden
</button>
</form>
</div>
<div class="tab-pane fade" id="register" role="tabpanel">
<form action="/auth/attemptRegister" method="post">
<?= csrf_field() ?>
<div class="mb-3">
<label for="register-name" class="form-label">Name</label>
<div class="input-group">
<span class="input-group-text"><i class="fas fa-user"></i></span>
<input type="text" class="form-control" id="register-name" name="name" placeholder="Dein Name" required>
</div>
</div>
<div class="mb-3">
<label for="register-email" class="form-label">E-Mail-Adresse</label>
<div class="input-group">
<span class="input-group-text"><i class="fas fa-envelope"></i></span>
<input type="email" class="form-control" id="register-email" name="email" placeholder="deine@email.com" required>
</div>
</div>
<div class="mb-4">
<label for="register-password" class="form-label">Passwort</label>
<div class="input-group">
<span class="input-group-text"><i class="fas fa-lock"></i></span>
<input type="password" class="form-control" id="register-password" name="password" placeholder="Wähle ein sicheres Passwort" required>
</div>
</div>
<button type="submit" class="btn btn-primary">
<i class="fas fa-user-plus me-2"></i>Konto erstellen
</button>
</form>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

View File

69
example.env Normal file
View File

@@ -0,0 +1,69 @@
#--------------------------------------------------------------------
# Example Environment Configuration file
#
# This file can be used as a starting point for your own
# custom .env files, and contains most of the possible settings
# available in a default install.
#
# By default, all of the settings are commented out. If you want
# to override the setting, you must un-comment it by removing the '#'
# at the beginning of the line.
#--------------------------------------------------------------------
#--------------------------------------------------------------------
# ENVIRONMENT
#--------------------------------------------------------------------
CI_ENVIRONMENT = development
#--------------------------------------------------------------------
# APP
#--------------------------------------------------------------------
# app.baseURL = ''
# If you have trouble with `.`, you could also use `_`.
# app_baseURL = ''
# app.forceGlobalSecureRequests = false
# app.CSPEnabled = false
#--------------------------------------------------------------------
# DATABASE
#--------------------------------------------------------------------
database.default.hostname = 127.0.0.1
database.default.database = TodoApp
database.default.username = root
database.default.password =
database.default.DBDriver = MySQLi
# database.default.DBPrefix =
database.default.port = 3306
# If you use MySQLi as tests, first update the values of Config\Database::$tests.
# database.tests.hostname = localhost
# database.tests.database = ci4_test
# database.tests.username = root
# database.tests.password = root
# database.tests.DBDriver = MySQLi
# database.tests.DBPrefix =
# database.tests.charset = utf8mb4
# database.tests.DBCollat = utf8mb4_general_ci
# database.tests.port = 3306
#--------------------------------------------------------------------
# ENCRYPTION
#--------------------------------------------------------------------
# encryption.key =
#--------------------------------------------------------------------
# SESSION
#--------------------------------------------------------------------
# session.driver = 'CodeIgniter\Session\Handlers\FileHandler'
# session.savePath = null
#--------------------------------------------------------------------
# LOGGER
#--------------------------------------------------------------------
# logger.threshold = 4

View File

@@ -0,0 +1,198 @@
<?php
use CodeIgniter\Test\CIUnitTestCase;
use CodeIgniter\Test\DatabaseTestTrait;
/**
* MigrationTest - Tests für Datenbankmigrationen
* Verifiziert dass alle Migrationen korrekt ausgeführt werden
* und die Tabellen mit korrekten Spalten erstellt werden
*
* @internal
*/
final class MigrationTest extends CIUnitTestCase
{
use DatabaseTestTrait;
/**
* Test: Users Tabelle existiert
*/
public function testUsersTableExists(): void
{
$db = \Config\Database::connect();
$this->assertTrue($db->tableExists('users'));
}
/**
* Test: Users Tabelle hat erforderliche Spalten
*/
public function testUsersTableHasRequiredColumns(): void
{
$db = \Config\Database::connect();
$fields = $db->getFieldData('users');
$fieldNames = array_map(function ($field) {
return $field->name;
}, $fields);
$this->assertContains('id', $fieldNames);
$this->assertContains('email', $fieldNames);
$this->assertContains('password_hash', $fieldNames);
$this->assertContains('name', $fieldNames);
$this->assertContains('avatar_url', $fieldNames);
$this->assertContains('settings', $fieldNames);
$this->assertContains('created_at', $fieldNames);
$this->assertContains('updated_at', $fieldNames);
}
/**
* Test: Email Spalte ist unique
*/
public function testEmailIsUnique(): void
{
$db = \Config\Database::connect();
$builder = $db->table('users');
// Insert erstes Datensatz
$builder->insert([
'id' => 'unique-test-1',
'email' => 'unique@example.com',
'password_hash' => 'hash1',
'name' => 'Test One',
]);
// Versuche zweites Datensatz mit gleicher Email zu inserten
try {
$builder->insert([
'id' => 'unique-test-2',
'email' => 'unique@example.com',
'password_hash' => 'hash2',
'name' => 'Test Two',
]);
// Falls kein Error, gibt es ein Problem
$this->fail('Unique constraint wurde nicht erzwungen');
} catch (\Exception $e) {
// Expected - unique constraint wurde erzwungen
$this->assertTrue(true);
}
}
/**
* Test: Categories Tabelle existiert
*/
public function testCategoriesTableExists(): void
{
$db = \Config\Database::connect();
$this->assertTrue($db->tableExists('categories'));
}
/**
* Test: Projects Tabelle existiert
*/
public function testProjectsTableExists(): void
{
$db = \Config\Database::connect();
$this->assertTrue($db->tableExists('projects'));
}
/**
* Test: Todos Tabelle existiert
*/
public function testTodosTableExists(): void
{
$db = \Config\Database::connect();
$this->assertTrue($db->tableExists('todos'));
}
/**
* Test: TodoCategories Tabelle existiert
*/
public function testTodoCategoriesTableExists(): void
{
$db = \Config\Database::connect();
$this->assertTrue($db->tableExists('todo_categories'));
}
/**
* Test: Todos Tabelle hat erforderliche Spalten
*/
public function testTodosTableHasRequiredColumns(): void
{
$db = \Config\Database::connect();
$fields = $db->getFieldData('todos');
$fieldNames = array_map(function ($field) {
return $field->name;
}, $fields);
// Diese Spalten sollten mindestens existieren
$this->assertContains('id', $fieldNames);
// Weitere Standard-Spalten...
}
/**
* Test: Datenbank Verbindung funktioniert
*/
public function testDatabaseConnectionWorks(): void
{
$db = \Config\Database::connect();
$this->assertNotNull($db);
}
/**
* Test: Schema wird nicht über Migration hinaus modifiziert
*/
public function testTableCountIsCorrect(): void
{
$db = \Config\Database::connect();
// Abrufen aller Tabellen
$tables = $db->listTables();
// Sollte mindestens diese Tabellen haben
$requiredTables = ['users', 'categories', 'projects', 'todos', 'todo_categories'];
foreach ($requiredTables as $table) {
$this->assertContains($table, $tables, "Tabelle '{$table}' existiert nicht");
}
}
/**
* Test: Users settings Spalte ist JSON
*/
public function testUserSettingsIsJson(): void
{
$db = \Config\Database::connect();
$fields = $db->getFieldData('users');
$settingsField = null;
foreach ($fields as $field) {
if ($field->name === 'settings') {
$settingsField = $field;
break;
}
}
$this->assertNotNull($settingsField);
// Type sollte JSON-ähnlich sein
$this->assertStringContainsString('json', strtolower($settingsField->type));
}
/**
* Test: Timestamps sind in correct format
*/
public function testTimestampsAreCorrectType(): void
{
$db = \Config\Database::connect();
$fields = $db->getFieldData('users');
$dateFields = [];
foreach ($fields as $field) {
if (in_array($field->name, ['created_at', 'updated_at'])) {
$dateFields[] = $field;
}
}
$this->assertCount(2, $dateFields);
}
}

View File

@@ -0,0 +1,222 @@
<?php
namespace Tests\Feature;
use App\Models\UserModel;
use CodeIgniter\Test\CIUnitTestCase;
use CodeIgniter\Test\DatabaseTestTrait;
use CodeIgniter\Test\FeatureTestTrait;
/**
* AuthApiTest - Feature Tests für Auth API
* Testet die Authentication API Endpoints und HTTP Requests/Responses
*
* @internal
*/
final class AuthApiTest extends CIUnitTestCase
{
use DatabaseTestTrait;
use FeatureTestTrait;
protected $namespace = 'App\Controllers';
/**
* Test: Login API gibt 200 zurück für GET auf /auth/login
*/
public function testGetLoginPageReturns200(): void
{
$response = $this->get('/auth/login');
$this->assertTrue($response->getStatusCode() === 200);
$this->assertStringContainsString('form', (string)$response);
}
/**
* Test: Login API gibt 302 (Redirect) zurück mit gültigen Daten
*/
public function testLoginWithValidDataReturns302(): void
{
$userModel = new UserModel();
$userModel->insert([
'email' => 'api@example.com',
'password_hash' => password_hash('password123', PASSWORD_DEFAULT),
'name' => 'API Test',
]);
$response = $this->post('/auth/attemptLogin', [
'email' => 'api@example.com',
'password' => 'password123',
]);
$this->assertTrue($response->getStatusCode() === 302);
}
/**
* Test: Register API erstellt neuen Benutzer
*/
public function testRegisterApiCreatesNewUser(): void
{
$response = $this->post('/auth/attemptRegister', [
'name' => 'API User',
'email' => 'apiregister@example.com',
'password' => 'password123',
]);
$this->assertTrue($response->getStatusCode() === 302);
// Verifiziere dass Benutzer in Datenbank erstellt wurde
$userModel = new UserModel();
$user = $userModel->where('email', 'apiregister@example.com')->first();
$this->assertNotNull($user);
$this->assertEquals('API User', $user['name']);
}
/**
* Test: Login API mit falschen Credentials
*/
public function testLoginWithInvalidDataReturns302(): void
{
$response = $this->post('/auth/attemptLogin', [
'email' => 'nonexistent@api.com',
'password' => 'wrongpassword',
]);
// Sollte redirect sein (zur Login Seite zurück)
$this->assertTrue($response->getStatusCode() === 302);
}
/**
* Test: Logout API gibt 302 Redirect zurück
*/
public function testLogoutApiReturns302(): void
{
$response = $this->get('/auth/logout');
$this->assertTrue($response->getStatusCode() === 302);
}
/**
* Test: POST mit fehlenden Email Feld
*/
public function testLoginWithMissingEmailField(): void
{
$response = $this->post('/auth/attemptLogin', [
'password' => 'password123',
]);
// Sollte fehlschlagen
$this->assertTrue($response->getStatusCode() === 302);
}
/**
* Test: POST mit fehlenden Password Feld
*/
public function testLoginWithMissingPasswordField(): void
{
$response = $this->post('/auth/attemptLogin', [
'email' => 'test@example.com',
]);
// Sollte fehlschlagen
$this->assertTrue($response->getStatusCode() === 302);
}
/**
* Test: Register mit fehlenden Name Feld
*/
public function testRegisterWithMissingNameField(): void
{
$response = $this->post('/auth/attemptRegister', [
'email' => 'noname@example.com',
'password' => 'password123',
]);
// Sollte weiterleiten (möglicherweise mit Error)
$this->assertTrue($response->getStatusCode() === 302);
}
/**
* Test: Content-Type ist richtig bei erfolgreicher Login Seite
*/
public function testLoginPageContentType(): void
{
$response = $this->get('/auth/login');
$this->assertStringContainsString('text/html', $response->getHeaderLine('Content-Type'));
}
/**
* Test: Register API validiert Email Format
*/
public function testRegisterValidatesEmailFormat(): void
{
$response = $this->post('/auth/attemptRegister', [
'name' => 'Invalid Email',
'email' => 'not-an-email',
'password' => 'password123',
]);
// Sollte fehlschlagen oder Fehler zurückgeben
$this->assertTrue($response->getStatusCode() === 302);
}
/**
* Test: Login API Response Headers enthalten Sicherheits-Header
*/
public function testLoginPageIncludesSecurityHeaders(): void
{
$response = $this->get('/auth/login');
// Bootstrap und CSS sollten geladen sein
$content = (string)$response;
$this->assertStringContainsString('bootstrap', strtolower($content));
}
/**
* Test: Register API setzt Benutzer-ID in Session
*/
public function testRegisterSetsUserIdInSession(): void
{
$this->post('/auth/attemptRegister', [
'name' => 'Session Test',
'email' => 'session@api.com',
'password' => 'password123',
]);
// Benutzer sollte in DB existieren
$userModel = new UserModel();
$user = $userModel->where('email', 'session@api.com')->first();
$this->assertNotNull($user);
$this->assertNotNull($user['id']);
}
/**
* Test: Multiple Login Versuche
*/
public function testMultipleLoginAttempts(): void
{
$userModel = new UserModel();
$userModel->insert([
'email' => 'multi@example.com',
'password_hash' => password_hash('correct', PASSWORD_DEFAULT),
'name' => 'Multi Test',
]);
// Erster Versuch (falsch)
$response1 = $this->post('/auth/attemptLogin', [
'email' => 'multi@example.com',
'password' => 'wrong',
]);
// Zweiter Versuch (korrekt)
$response2 = $this->post('/auth/attemptLogin', [
'email' => 'multi@example.com',
'password' => 'correct',
]);
// Beide sollten 302 sein (redirect)
$this->assertTrue($response1->getStatusCode() === 302);
$this->assertTrue($response2->getStatusCode() === 302);
}
}

View File

@@ -0,0 +1,213 @@
<?php
namespace Tests\Unit\Controllers;
use App\Controllers\Auth;
use App\Models\UserModel;
use CodeIgniter\Test\CIUnitTestCase;
use CodeIgniter\Test\DatabaseTestTrait;
use CodeIgniter\Test\FeatureTestTrait;
/**
* AuthControllerTest - Unit Tests für den Auth Controller
* Testet Login, Registrierung und Logout Funktionalität
*
* @internal
*/
final class AuthControllerTest extends CIUnitTestCase
{
use DatabaseTestTrait;
use FeatureTestTrait;
protected $namespace = 'App\Controllers';
/**
* Test: Login Seite wird angezeigt
*/
public function testLoginPageLoads(): void
{
$response = $this->get('/auth/login');
$this->assertTrue($response->getStatusCode() === 200);
$this->assertStringContainsString('Todo App', (string)$response);
$this->assertStringContainsString('Anmelden', (string)$response);
}
/**
* Test: Login mit gültigen Credentials
*/
public function testLoginWithValidCredentials(): void
{
// Benutzer in der Datenbank erstellen
$userModel = new UserModel();
$userData = [
'email' => 'test@example.com',
'password_hash' => password_hash('password123', PASSWORD_DEFAULT),
'name' => 'Test User',
];
$userModel->insert($userData);
// POST Request zum Login
$response = $this->post('/auth/attemptLogin', [
'email' => 'test@example.com',
'password' => 'password123',
]);
// Sollte zu /dashboard weiterleiten
$this->assertTrue($response->getStatusCode() === 302);
}
/**
* Test: Login mit ungültigen Credentials
*/
public function testLoginWithInvalidCredentials(): void
{
$response = $this->post('/auth/attemptLogin', [
'email' => 'nonexistent@example.com',
'password' => 'wrongpassword',
]);
$this->assertTrue($response->getStatusCode() === 302);
}
/**
* Test: Registrierung mit gültigen Daten
*/
public function testRegisterWithValidData(): void
{
$response = $this->post('/auth/attemptRegister', [
'name' => 'Neuer User',
'email' => 'newuser@example.com',
'password' => 'password123',
]);
$this->assertTrue($response->getStatusCode() === 302);
$userModel = new UserModel();
$user = $userModel->where('email', 'newuser@example.com')->first();
$this->assertNotNull($user);
$this->assertEquals('Neuer User', $user['name']);
$this->assertEquals('newuser@example.com', $user['email']);
}
/**
* Test: Registrierung mit doppelter Email sollte fehlschlagen
*/
public function testRegisterWithDuplicateEmail(): void
{
$this->post('/auth/attemptRegister', [
'name' => 'User One',
'email' => 'duplicate@example.com',
'password' => 'password123',
]);
$response = $this->post('/auth/attemptRegister', [
'name' => 'User Two',
'email' => 'duplicate@example.com',
'password' => 'password456',
]);
$this->assertTrue($response->getStatusCode() === 302);
}
/**
* Test: Logout zerstört Session
*/
public function testLogout(): void
{
$userModel = new UserModel();
$userData = [
'email' => 'logout@example.com',
'password_hash' => password_hash('password123', PASSWORD_DEFAULT),
'name' => 'Logout Test User',
];
$userModel->insert($userData);
$this->post('/auth/attemptLogin', [
'email' => 'logout@example.com',
'password' => 'password123',
]);
$response = $this->get('/auth/logout');
$this->assertTrue($response->getStatusCode() === 302);
}
/**
* Test: Passwort wird korrekt gehasht
*/
public function testPasswordIsHashed(): void
{
$password = 'plaintext_password_123';
$response = $this->post('/auth/attemptRegister', [
'name' => 'Hash Test',
'email' => 'hash@example.com',
'password' => $password,
]);
$userModel = new UserModel();
$user = $userModel->where('email', 'hash@example.com')->first();
// Passwort sollte nicht im Klartext gespeichert sein
$this->assertNotEquals($password, $user['password_hash']);
// password_verify sollte true zurückgeben
$this->assertTrue(password_verify($password, $user['password_hash']));
}
/**
* Test: Email ist erforderlich beim Login
*/
public function testLoginRequiresEmail(): void
{
$response = $this->post('/auth/attemptLogin', [
'email' => '',
'password' => 'password123',
]);
$this->assertTrue($response->getStatusCode() === 302);
}
/**
* Test: Email ist erforderlich bei Registrierung
*/
public function testRegisterRequiresEmail(): void
{
$response = $this->post('/auth/attemptRegister', [
'name' => 'Test',
'email' => '',
'password' => 'password123',
]);
$this->assertTrue($response->getStatusCode() === 302);
}
/**
* Test: Login mit ungültiger Email-Adresse
*/
public function testLoginWithInvalidEmail(): void
{
$response = $this->post('/auth/attemptLogin', [
'email' => 'not-an-email',
'password' => 'password123',
]);
$this->assertTrue($response->getStatusCode() === 302);
}
/**
* Test: Session wird nach erfolgreicher Registrierung gesetzt
*/
public function testSessionIsSetAfterRegistration(): void
{
$response = $this->post('/auth/attemptRegister', [
'name' => 'Session Test',
'email' => 'session@example.com',
'password' => 'password123',
]);
$userModel = new UserModel();
$user = $userModel->where('email', 'session@example.com')->first();
$this->assertNotNull($user);
}
}

View File

@@ -0,0 +1,172 @@
<?php
namespace Tests\Unit\Models;
use App\Models\UserModel;
use CodeIgniter\Test\CIUnitTestCase;
use CodeIgniter\Test\DatabaseTestTrait;
/**
* UserModelTest - Unit Tests für das UserModel
* Testet die Benutzerdatenbankoperationen
*
* @internal
*/
final class UserModelTest extends CIUnitTestCase
{
use DatabaseTestTrait;
protected $namespace = 'App\Models';
/**
* Test: Benutzer kann erstellt werden
*/
public function testUserCanBeCreated(): void
{
$userModel = new UserModel();
$data = [
'email' => 'user@example.com',
'password_hash' => password_hash('password123', PASSWORD_DEFAULT),
'name' => 'Test User',
];
$id = $userModel->insert($data);
$this->assertIsNotNull($id);
}
/**
* Test: Benutzer kann nach Email gefunden werden
*/
public function testUserCanBeFoundByEmail(): void
{
$userModel = new UserModel();
$data = [
'email' => 'find@example.com',
'password_hash' => password_hash('password123', PASSWORD_DEFAULT),
'name' => 'Find User',
];
$userModel->insert($data);
$user = $userModel->where('email', 'find@example.com')->first();
$this->assertNotNull($user);
$this->assertEquals('find@example.com', $user['email']);
$this->assertEquals('Find User', $user['name']);
}
/**
* Test: Doppelte Email wird verhindert
*/
public function testDuplicateEmailIsRejected(): void
{
$userModel = new UserModel();
$data = [
'email' => 'duplicate@example.com',
'password_hash' => password_hash('password123', PASSWORD_DEFAULT),
'name' => 'First User',
];
$userModel->insert($data);
$duplicateData = [
'email' => 'duplicate@example.com',
'password_hash' => password_hash('password456', PASSWORD_DEFAULT),
'name' => 'Second User',
];
$result = $userModel->insert($duplicateData);
// Sollte false zurückgeben wegen Validierungsfehler
$this->assertFalse($result);
}
/**
* Test: Benutzer kann aktualisiert werden
*/
public function testUserCanBeUpdated(): void
{
$userModel = new UserModel();
$data = [
'email' => 'update@example.com',
'password_hash' => password_hash('password123', PASSWORD_DEFAULT),
'name' => 'Original Name',
];
$id = $userModel->insert($data);
$updateData = [
'name' => 'Updated Name',
];
$userModel->update($id, $updateData);
$updated = $userModel->find($id);
$this->assertEquals('Updated Name', $updated['name']);
}
/**
* Test: Benutzer kann gelöscht werden
*/
public function testUserCanBeDeleted(): void
{
$userModel = new UserModel();
$data = [
'email' => 'delete@example.com',
'password_hash' => password_hash('password123', PASSWORD_DEFAULT),
'name' => 'Delete User',
];
$id = $userModel->insert($data);
$userModel->delete($id);
$found = $userModel->find($id);
$this->assertNull($found);
}
/**
* Test: Alle Benutzer können abgerufen werden
*/
public function testAllUsersCanBeRetrieved(): void
{
$userModel = new UserModel();
// Insert mehrere Benutzer
for ($i = 1; $i <= 3; $i++) {
$userModel->insert([
'email' => "user{$i}@example.com",
'password_hash' => password_hash('password', PASSWORD_DEFAULT),
'name' => "User {$i}",
]);
}
$users = $userModel->findAll();
$this->assertCount(3, $users);
}
/**
* Test: Passwort Hash ist gültig
*/
public function testPasswordHashIsValid(): void
{
$userModel = new UserModel();
$password = 'mysecurepassword123';
$data = [
'email' => 'hash@example.com',
'password_hash' => password_hash($password, PASSWORD_DEFAULT),
'name' => 'Hash Test',
];
$userModel->insert($data);
$user = $userModel->where('email', 'hash@example.com')->first();
$this->assertTrue(password_verify($password, $user['password_hash']));
$this->assertFalse(password_verify('wrongpassword', $user['password_hash']));
}
}