-
-
Notifications
You must be signed in to change notification settings - Fork 313
feat: Added SQL Injection Lab Data And Tasks #4466
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
WalkthroughThis update introduces new models for tasks and task content, adds Django admin interfaces for these models, and implements a management command to seed SQL injection lab tasks. It also expands the simulation feature with detailed lab and task views, interactive answer submission endpoints, and new templates for rendering lab and task details, including simulation scenarios and MCQs. Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant Browser
participant DjangoServer
participant DB
User->>Browser: Clicks on "Start Lab" or lab link
Browser->>DjangoServer: GET /simulation/lab/<lab_id>/
DjangoServer->>DB: Fetch Lab and Tasks
DB-->>DjangoServer: Lab and list of Tasks
DjangoServer-->>Browser: Render lab_detail.html
User->>Browser: Clicks on Task
Browser->>DjangoServer: GET /simulation/lab/<lab_id>/task/<task_id>/
DjangoServer->>DB: Fetch Task and TaskContent
DB-->>DjangoServer: Task and Content
DjangoServer-->>Browser: Render task_detail.html
User->>Browser: Submits answer (MCQ or simulation payload)
Browser->>DjangoServer: POST /simulation/lab/<lab_id>/task/<task_id>/submit/
DjangoServer->>DB: Fetch Task and TaskContent
DB-->>DjangoServer: Task and Content
DjangoServer-->>Browser: JSON response (correct/incorrect)
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Assessment against linked issues
Assessment against linked issues: Out-of-scope changesNo out-of-scope changes found. Note ⚡️ Unit Test Generation is now available in beta!Learn more here, or try it out under "Finishing Touches" below. 📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
✨ Finishing Touches
🧪 Generate unit tests
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 4
🧹 Nitpick comments (3)
website/admin.py (1)
748-751: Consider enhancing TaskAdmin with additional configurations.The
TaskAdminclass is quite minimal compared to other admin classes in the file. Consider adding useful configurations for better admin experience.class TaskAdmin(admin.ModelAdmin): list_display = ("name", "description", "task_type", "order", "is_active", "created_at") search_fields = ("name", "description") + list_filter = ("task_type", "is_active", "lab", "created_at") + date_hierarchy = "created_at" + ordering = ("lab", "order", "name")website/models.py (1)
2510-2527: Consider adding validation for task type-specific content.The model structure is good, but consider adding validation to ensure consistency between task types and their respective content fields. For example, theory tasks should have
theory_content, while simulation tasks should havesimulation_config.You could add a
clean()method to validate content based on task type:+ def clean(self): + from django.core.exceptions import ValidationError + + if self.task.task_type == 'theory': + if not self.theory_content: + raise ValidationError("Theory tasks must have theory content.") + elif self.task.task_type == 'simulation': + if not self.simulation_config: + raise ValidationError("Simulation tasks must have simulation configuration.") + + # Validate MCQ answer format if MCQ question exists + if self.mcq_question and self.correct_answer: + if self.correct_answer not in ['A', 'B', 'C', 'D']: + raise ValidationError("Correct answer must be A, B, C, or D.")website/views/Simulation.py (1)
60-64: Consider using select_related for optimization.While the current implementation works, you could optimize database queries by using
select_relatedwhen fetching the task.- task = get_object_or_404(Tasks, id=task_id, lab=lab, is_active=True) - - try: - content = task.content - except TaskContent.DoesNotExist: - content = None + task = get_object_or_404( + Tasks.objects.select_related('content'), + id=task_id, + lab=lab, + is_active=True + ) + content = getattr(task, 'content', None)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Knowledge Base: Disabled due to Reviews > Disable Knowledge Base setting
📒 Files selected for processing (9)
blt/urls.py(2 hunks)website/admin.py(3 hunks)website/management/commands/create_sql_injection_tasks.py(1 hunks)website/migrations/0244_tasks_taskcontent.py(1 hunks)website/models.py(1 hunks)website/templates/Simulation.html(2 hunks)website/templates/lab_detail.html(1 hunks)website/templates/task_detail.html(1 hunks)website/views/Simulation.py(2 hunks)
🔇 Additional comments (15)
website/templates/Simulation.html (1)
75-89: LGTM! Clean conversion from button to navigation link.The change from a button element to an anchor tag is semantically correct and aligns with the new lab detail URL structure. The styling and conditional text logic are properly preserved.
website/templates/lab_detail.html (1)
1-117: LGTM! Well-structured lab detail template.The template follows Django best practices with proper template inheritance, URL reversal, and conditional rendering. The Tailwind CSS styling provides a clean, responsive design, and the task type differentiation with icons and color coding enhances usability.
website/templates/task_detail.html (2)
1-182: LGTM! Comprehensive task detail template with solid JavaScript implementation.The template handles both theory and simulation task types well, with proper conditional rendering and clean styling. The JavaScript code correctly implements async form submissions with proper CSRF token handling and error management.
183-260: LGTM! Well-implemented JavaScript handlers.Both the MCQ and simulation form submission handlers are properly implemented with:
- Proper form validation
- Correct CSRF token handling
- Appropriate error handling
- Clean response processing
website/migrations/0244_tasks_taskcontent.py (1)
12-62: LGTM! Well-designed migration with proper model structure.The migration creates two complementary models with:
- Appropriate field types and constraints
- Proper foreign key relationships with CASCADE deletion
- Unique constraint on (lab, order) ensuring proper task sequencing
- JSONField usage for flexible content storage
- Good meta options for ordering and naming
The model structure effectively supports the template functionality and provides a solid foundation for the lab task system.
blt/urls.py (2)
279-279: LGTM! Proper import statement expansion.The import statement correctly includes all the new simulation views needed for the enhanced lab functionality.
363-366: LGTM! Well-structured URL patterns for lab functionality.The URL changes provide:
- Clearer naming with "simulation_dashboard"
- Logical URL hierarchy for labs and tasks
- Proper parameter types (int) for database IDs
- Consistent naming conventions
These URLs properly support the template navigation structure and form submissions.
website/admin.py (4)
41-41: LGTM! Model imports follow proper conventions.The new model imports are correctly placed in alphabetical order and follow the existing import structure pattern.
Also applies to: 64-65
730-746: Well-structured admin class with proper content handling.The
TaskContentAdminclass follows Django admin best practices with appropriate field configurations and a well-implementedget_content_previewmethod that handles different content types gracefully.
753-764: Comprehensive admin class following established patterns.The
LabsAdminclass is well-implemented with comprehensive configurations and follows the patterns established by other admin classes in the file. The customget_description_previewmethod properly handles content truncation.
766-768: Model registrations are correctly implemented.The new model registrations properly pair each model with its corresponding admin class following Django admin conventions.
website/models.py (1)
2486-2508: LGTM! Well-structured model with good practices.The
Tasksmodel is well-designed with proper relationships, constraints, and field definitions. The unique constraint on["lab", "order"]ensures proper task ordering within each lab, and the CASCADE deletion behavior is appropriate.website/management/commands/create_sql_injection_tasks.py (2)
10-14: Good error handling for missing lab.The try-except block properly handles the case when the SQL Injection lab doesn't exist, with a helpful error message directing users to run the prerequisite command.
336-376: Well-structured task creation logic.The implementation correctly uses Django's
get_or_createandupdate_or_createmethods to ensure idempotency. The conditional logic properly handles different task types and provides clear console feedback.website/views/Simulation.py (1)
41-51: Clean implementation of lab detail view.Good use of
get_object_or_404and filtering byis_activestatus. The view follows Django best practices.
|
will add images and more theory :) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
♻️ Duplicate comments (1)
website/management/commands/create_sql_injection_tasks.py (1)
154-158: Fix incorrect simulation_config structure.The
table_structuredictionary incorrectly containssuccess_payloadas a nested field. This should be at the same level as other simulation config fields.Apply this diff to fix the structure:
"table_structure": { "users": ["id", "username", "password", "email"], "products": ["id", "name", "price", "description"], - "success_payload": "' UNION SELECT id, username, password, email FROM users--", }, + "success_payload": "' UNION SELECT id, username, password, email FROM users--",
🧹 Nitpick comments (1)
website/management/commands/create_sql_injection_tasks.py (1)
336-346: Consider adding duplicate key handling.The
get_or_createcall usesname,order, andlabas lookup fields, but if tasks with the same name and order exist for different labs, this could cause issues. Consider making the lookup more explicit.Apply this diff for clearer intent:
task, created = Tasks.objects.get_or_create( lab=sql_lab, name=task_data["name"], - order=task_data["order"], defaults={ "description": task_data["description"], "task_type": task_data["task_type"], + "order": task_data["order"], "is_active": True, }, )
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Knowledge Base: Disabled due to Reviews > Disable Knowledge Base setting
📒 Files selected for processing (2)
website/management/commands/create_sql_injection_tasks.py(1 hunks)website/views/Simulation.py(2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
- GitHub Check: Run Tests
- GitHub Check: docker-test
🔇 Additional comments (9)
website/management/commands/create_sql_injection_tasks.py (3)
1-14: LGTM! Proper error handling and dependencies.The command correctly handles the case where the required "SQL Injection" lab doesn't exist and provides clear instructions to run the prerequisite command.
366-366: LGTM! Proper use of update_or_create for content.The use of
update_or_createensures that task content is properly updated when the command is run multiple times, maintaining idempotency.
378-379: No changes needed:update_total_tasksis defined on the Labs model
A quick search confirms the method exists in website/models.py:# website/models.py def update_total_tasks(self): """ Updates the total_tasks count based on related tasks. This will be called when tasks are added/removed. """ if hasattr(self, "tasks"): self.total_tasks = self.tasks.count() self.save()You can safely ignore this suggestion.
Likely an incorrect or invalid review comment.
website/views/Simulation.py (6)
4-7: LGTM! Proper imports added.The new imports for JsonResponse, get_object_or_404, and the new models are correctly added to support the new functionality.
41-51: LGTM! Clean and secure lab detail view.The view properly uses
get_object_or_404for security and filters for active labs and tasks. The context structure is appropriate for the template.
54-70: LGTM! Proper task detail implementation.The view correctly handles the potential absence of task content with a try-catch block and provides appropriate context to the template.
87-100: LGTM! Secure theory task handling.The theory task handling properly validates user input, compares answers case-insensitively, and provides appropriate feedback.
102-126: LGTM! Improved simulation task handling.The simulation task handling now properly initializes
expected_payloadand handles the case wheresuccess_payloadis not defined. The conditional logic for building the response is correct.
105-124: Approval: Simulation view clean of debug statements and undefined-variable issues
expected_payloadis explicitly initialized toNone, eliminating any risk of an undefined variable.- A search of website/views/Simulation.py confirmed there are no remaining
print()calls.All past review comments have been addressed—approving these changes.
Fixes: #4331, #4332
To populate the database, run:
Screenshots:


Summary by CodeRabbit
New Features
Bug Fixes