feat: Add user tracking to project tasks and notes

- Implemented user tracking columns in project_tasks and notes tables.
- Added created_by and assigned_to fields to project_tasks.
- Introduced created_by field and is_system flag in notes.
- Updated API endpoints to handle user tracking during task and note creation.
- Enhanced database initialization to include new columns and indexes.
- Created utility functions to fetch users for task assignment.
- Updated front-end components to display user information for tasks and notes.
- Added tests for project-tasks API endpoints to verify functionality.
This commit is contained in:
Chop
2025-06-26 00:17:51 +02:00
parent 294d8343d3
commit 90875db28b
19 changed files with 785 additions and 147 deletions

View File

@@ -809,6 +809,81 @@ POST /api/projects/users
}
```
## Project Tasks User Tracking - NEW FEATURE ✅
### 📋 Task User Management Implementation
We've also implemented comprehensive user tracking for project tasks:
#### Database Schema Updates ✅
- **created_by**: Tracks who created the task (user ID)
- **assigned_to**: Tracks who is assigned to work on the task (user ID)
- **created_at**: Timestamp when task was created
- **updated_at**: Timestamp when task was last modified
- **Indexes**: Performance optimized with proper foreign key indexes
#### API Enhancements ✅
- **Enhanced Queries**: Tasks now include user names and emails via JOIN operations
- **User Assignment**: New `/api/project-tasks/users` endpoint for user management
- **Query Filters**: Support for filtering tasks by assigned user or creator
- **User Context**: Create/update operations automatically capture authenticated user ID
#### UI Components ✅
- **Task Form**: User assignment dropdown in create task forms
- **Task Listing**: "Created By" and "Assigned To" columns in task table
- **User Selection**: Dropdown populated with active users for assignment
#### New Task Query Functions ✅
- `getAllUsersForTaskAssignment()`: Get active users for assignment dropdown
- `getProjectTasksByAssignedUser(userId)`: Filter tasks by assignee
- `getProjectTasksByCreator(userId)`: Filter tasks by creator
- `updateProjectTaskAssignment(taskId, userId)`: Update task assignment
#### Task Creation Behavior ✅
- **Auto-assignment**: Tasks are automatically assigned to the authenticated user as creator
- **Optional Assignment**: Users can assign tasks to other team members during creation
- **Creator Tracking**: All tasks track who created them for accountability
### Task Usage Examples
#### Creating Tasks with User Tracking
```javascript
// Tasks are automatically assigned to the authenticated user as creator
POST /api/project-tasks
{
"project_id": 123,
"task_template_id": 1, // or custom_task_name for custom tasks
"assigned_to": "user-id-here", // Optional, defaults to creator
"priority": "high"
}
```
#### Filtering Tasks by User
```javascript
// Get tasks assigned to specific user
GET /api/project-tasks?assigned_to=user-id
// Get tasks created by specific user
GET /api/project-tasks?created_by=user-id
```
#### Updating Task Assignment
```javascript
POST /api/project-tasks/users
{
"taskId": 456,
"assignedToUserId": "new-user-id"
}
```
### Next Enhancements
1. **Dashboard Views** (Recommended)
@@ -828,123 +903,69 @@ POST /api/projects/users
- Deadline reminders for assigned users
- Status change notifications
## Security Best Practices
## Notes User Tracking - NEW FEATURE ✅
### 1. Password Security
### 📝 Notes User Management Implementation
- Minimum 8 characters
- Require special characters, numbers
- Hash with bcrypt (cost factor 12+)
- Implement password history
We've also implemented comprehensive user tracking for all notes (both project notes and task notes):
### 2. Session Security
#### Database Schema Updates ✅
- Secure cookies
- Session rotation
- Timeout handling
- Device tracking
- **created_by**: Tracks who created the note (user ID)
- **is_system**: Distinguishes between user notes and system-generated notes
- **Enhanced queries**: Notes now include user names and emails via JOIN operations
- **Indexes**: Performance optimized with proper indexes for user lookups
### 3. API Security
#### API Enhancements ✅
- Input validation on all endpoints
- SQL injection prevention (prepared statements)
- XSS protection
- CSRF tokens
- **User Context**: All note creation operations automatically capture authenticated user ID
- **System Notes**: Automatic system notes (task status changes) track who made the change
- **User Information**: Note retrieval includes creator name and email for display
### 4. Audit & Monitoring
#### UI Components ✅
- Log all authentication events
- Monitor failed login attempts
- Track permission changes
- Alert on suspicious activity
- **Project Notes**: Display creator name and email in project note listings
- **Task Notes**: Show who added each note with user badges and timestamps
- **System Notes**: Distinguished from user notes with special styling and "System" badge
- **User Attribution**: Clear indication of who created each note and when
## Testing Status
#### New Note Query Functions ✅
### ✅ Completed Tests
- `getAllNotesWithUsers()`: Get all notes with user and project/task context
- `getNotesByCreator(userId)`: Filter notes by creator for user activity tracking
- Enhanced `getNotesByProjectId()` and `getNotesByTaskId()` with user information
- **Authentication Flow**: Login/logout working correctly
- **API Protection**: All endpoints properly secured
- **Role Validation**: Permission levels enforced
- **Session Management**: JWT tokens and expiration working
- **Password Security**: bcrypt hashing and verification functional
- **Account Lockout**: Failed attempt tracking and temporary lockout
#### Automatic User Tracking ✅
### 🔧 Available Test Scripts
- **Note Creation**: All new notes automatically record who created them
- **System Notes**: Task status changes generate system notes attributed to the user who made the change
- **Audit Trail**: Complete history of who added what notes and when
- `test-auth.mjs` - Tests API route protection and auth endpoints
- `test-auth-detailed.mjs` - Comprehensive authentication flow testing
- `test-complete-auth.mjs` - Full system authentication validation
- `test-logged-in-flow.mjs` - Authenticated user session testing
### Notes Usage Examples
### ✅ Verified Security Features
#### Project Notes with User Tracking
- Unauthorized API requests return 401
- Role-based access control working
- Session tokens properly validated
- Password attempts tracked and limited
- Admin user creation and management functional
- Notes display creator name in a blue badge next to the timestamp
- Form automatically associates notes with the authenticated user
- Clear visual distinction between different note authors
## Deployment Considerations
#### Task Notes with User Tracking
### 1. Environment Variables
- User notes show creator name in a gray badge
- System notes show "System" badge but also track the user who triggered the action
- Full audit trail of task status changes and who made them
- Use strong, random secrets
- Different keys per environment
- Secure secret management
#### System Note Generation
### 2. Database Security
```javascript
// When a user changes a task status, a system note is automatically created:
// "Status changed from 'pending' to 'in_progress'" - attributed to the user who made the change
```
- Regular backups
- Encryption at rest
- Network security
- Access logging
### Benefits
### 3. Application Security
- HTTPS enforcement
- Security headers
- Content Security Policy
- Regular security updates
## Migration Strategy
### 1. Development Phase
- Implement on development branch
- Test thoroughly with sample data
- Document all changes
### 2. Staging Deployment
- Deploy to staging environment
- Performance testing
- Security testing
- User acceptance testing
### 3. Production Deployment
- Database backup before migration
- Gradual rollout
- Monitor for issues
- Rollback plan ready
## Resources and Documentation
### NextAuth.js
- [Official Documentation](https://next-auth.js.org/)
- [Better SQLite3 Adapter](https://authjs.dev/reference/adapter/better-sqlite3)
### Security Libraries
- [Zod Validation](https://zod.dev/)
- [bcryptjs](https://www.npmjs.com/package/bcryptjs)
### Best Practices
- [OWASP Top 10](https://owasp.org/www-project-top-ten/)
- [Next.js Security Guidelines](https://nextjs.org/docs/advanced-features/security-headers)
---
**Next Steps**: Choose which phase to implement first and create detailed implementation tickets for development.
1. **Accountability**: Full audit trail of who added what notes
2. **Context**: Know who to contact for clarification on specific notes
3. **History**: Track communication and decisions made by team members
4. **System Integration**: Automatic notes for system actions still maintain user attribution
5. **User Experience**: Clear visual indicators of note authors improve team collaboration