fix(security, workflows, outreach): remove hardcoded credentials, connect runFlow API, test outreach engine, add requirements.txt

This commit is contained in:
Goose 2026-09-26 08:18:14 +00:00
parent 1c8964a122
commit 02c9cf02a7
6 changed files with 174 additions and 10 deletions

View file

@ -1,11 +1,36 @@
import axios from 'axios' import axios from 'axios'
function getCookie(name) {
let cookieValue = null
if (document.cookie && document.cookie !== '') {
const cookies = document.cookie.split(';')
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim()
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1))
break
}
}
}
return cookieValue
}
const api = axios.create({ const api = axios.create({
baseURL: '/api', baseURL: '/api',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json'
'Authorization': 'Basic ' + btoa('admin:openforce123') // Default dev credentials
} }
}) })
// Attach CSRF token for Django session authentication
api.interceptors.request.use((config) => {
const csrfToken = getCookie('csrftoken')
if (csrfToken) {
config.headers['X-CSRFToken'] = csrfToken
}
return config
}, (error) => {
return Promise.reject(error)
})
export default api export default api

View file

@ -63,6 +63,8 @@ import { Background } from '@vue-flow/background'
import { Controls } from '@vue-flow/controls' import { Controls } from '@vue-flow/controls'
import api from '../api' import api from '../api'
const currentFlowId = ref(null)
const nodes = ref([ const nodes = ref([
{ {
id: 'start-trigger', id: 'start-trigger',
@ -114,19 +116,33 @@ async function saveFlow() {
edges: edges.value.map(e => ({ source: e.source, target: e.target })) edges: edges.value.map(e => ({ source: e.source, target: e.target }))
} }
} }
await api.post('/flows/', payload) let res
if (currentFlowId.value) {
res = await api.put(`/workflows/${currentFlowId.value}/`, payload)
} else {
res = await api.post('/workflows/', payload)
}
currentFlowId.value = res.data.id
alert('Flow Definition successfully saved & DAG validated via Kahn\'s algorithm!') alert('Flow Definition successfully saved & DAG validated via Kahn\'s algorithm!')
return res.data
} }
async function runFlow() { async function runFlow() {
executionTrace.value = { try {
status: 'completed', if (!currentFlowId.value) {
context: { const saved = await saveFlow()
lead_id: 42, currentFlowId.value = saved.id
score: 25,
stage: 'Qualified',
steps_executed: ['start-trigger', 'score-step', 'qualify-step']
} }
const res = await api.post(`/workflows/${currentFlowId.value}/execute/`, {
context: { lead_id: 42, initial_score: 0 }
})
executionTrace.value = {
status: res.data.status,
context: res.data.context_data || res.data.context || {}
}
} catch (err) {
console.error('Failed to execute flow:', err)
alert('Flow execution error: ' + (err.response?.data?.detail || err.message))
} }
} }
</script> </script>

View file

@ -25,6 +25,7 @@ router.register(r'custom-objects', CustomObjectDefinitionViewSet, basename='cust
router.register(r'custom-fields', CustomFieldDefinitionViewSet, basename='custom-field') router.register(r'custom-fields', CustomFieldDefinitionViewSet, basename='custom-field')
router.register(r'workflows', FlowDefinitionViewSet, basename='workflow') router.register(r'workflows', FlowDefinitionViewSet, basename='workflow')
router.register(r'flows', FlowDefinitionViewSet, basename='flow')
router.register(r'workflow-logs', FlowExecutionLogViewSet, basename='workflow-log') router.register(r'workflow-logs', FlowExecutionLogViewSet, basename='workflow-log')
router.register(r'email-templates', EmailTemplateViewSet, basename='email-template') router.register(r'email-templates', EmailTemplateViewSet, basename='email-template')
@ -34,6 +35,7 @@ urlpatterns = [
path('admin/', admin.site.urls), path('admin/', admin.site.urls),
path('api/', include(router.urls)), path('api/', include(router.urls)),
path('api/track/<uuid:token>/', TrackEmailOpenView.as_view(), name='track_email_open'), path('api/track/<uuid:token>/', TrackEmailOpenView.as_view(), name='track_email_open'),
path('api/outreach/track/open/<uuid:token>/', TrackEmailOpenView.as_view(), name='track_email_open_alt'),
path('api/custom/<str:object_name>/', CustomRecordViewSet.as_view({ path('api/custom/<str:object_name>/', CustomRecordViewSet.as_view({
'get': 'list', 'get': 'list',
'post': 'create' 'post': 'create'

9
requirements.txt Normal file
View file

@ -0,0 +1,9 @@
Django>=4.2,<5.0
djangorestframework>=3.14,<4.0
psycopg2-binary>=2.9
jsonschema>=4.0
django-cors-headers>=4.0
whitenoise>=6.5
pytest>=7.0
pytest-django>=4.5
pytest-cov>=4.0

108
tests/test_outreach.py Normal file
View file

@ -0,0 +1,108 @@
import pytest
from django.core import mail
from outreach.models import EmailTemplate, Campaign, CampaignRecipient
from outreach.engine import inject_tracking_pixel, dispatch_campaign
@pytest.mark.django_db
class TestOutreachEngine:
def test_merge_tag_substitution(self):
template = EmailTemplate.objects.create(
name='Test Promo',
subject='Hello {{ first_name }}!',
body_html='<p>Hi {{ first_name }}, welcome to {{ company }}! Your code is {{ promo_code }}.</p>',
body_text='Hi {{ first_name }}, welcome to {{ company }}!'
)
context = {
'first_name': 'Alice',
'company': 'Acme Corp',
'promo_code': 'SAVE20'
}
subj, html, text = template.render(context)
assert subj == 'Hello Alice!'
assert 'Hi Alice, welcome to Acme Corp! Your code is SAVE20.' in html
assert 'Hi Alice, welcome to Acme Corp!' in text
def test_missing_merge_tag_fallback(self):
template = EmailTemplate.objects.create(
name='Missing Tag Test',
subject='Welcome {{ first_name }} to {{ nonexistent_var }}',
body_html='<p>Hello {{ first_name }}, your plan is {{ missing_plan }}</p>',
body_text='Hello {{ first_name }}, plan: {{ missing_plan }}'
)
context = {'first_name': 'Bob'}
subj, html, text = template.render(context)
# Missing tags are not provided in context, so unrendered placeholders remain or are handled safely
assert 'Welcome Bob' in subj
assert 'Hello Bob' in html
assert 'Hello Bob' in text
def test_inject_tracking_pixel_with_body_tag(self):
html = '<html><body><p>Test</p></body></html>'
token = '12345678-1234-5678-1234-567812345678'
result = inject_tracking_pixel(html, token, base_url='https://crm.example.com')
assert f'<img src="https://crm.example.com/api/outreach/track/open/{token}/"' in result
assert '</body>' in result
assert result.endswith('</body></html>')
def test_inject_tracking_pixel_without_body_tag(self):
html = '<p>Just a fragment</p>'
token = '12345678-1234-5678-1234-567812345678'
result = inject_tracking_pixel(html, token, base_url='https://crm.example.com')
assert f'<img src="https://crm.example.com/api/outreach/track/open/{token}/"' in result
assert result.startswith('<p>Just a fragment</p><img')
def test_multi_recipient_dispatch(self):
mail.outbox = []
template = EmailTemplate.objects.create(
name='Outreach Blast',
subject='Special Offer for {{ first_name }}',
body_html='<html><body><p>Hey {{ first_name }}, check this out!</p></body></html>',
body_text='Hey {{ first_name }}, check this out!'
)
campaign = Campaign.objects.create(
name='Q3 Outreach',
template=template,
status='draft'
)
rec1 = CampaignRecipient.objects.create(
campaign=campaign,
email='alice@example.com',
first_name='Alice',
last_name='Smith',
status='queued',
merge_data={'company': 'AliceCo'}
)
rec2 = CampaignRecipient.objects.create(
campaign=campaign,
email='bob@example.com',
first_name='Bob',
last_name='Jones',
status='queued',
merge_data={'company': 'BobCo'}
)
sent_count = dispatch_campaign(campaign.id, base_url='http://testserver')
assert sent_count == 2
assert len(mail.outbox) == 2
rec1.refresh_from_db()
rec2.refresh_from_db()
campaign.refresh_from_db()
assert rec1.status == 'sent'
assert rec1.sent_at is not None
assert rec2.status == 'sent'
assert rec2.sent_at is not None
assert campaign.status == 'completed'
# Verify email contents & tracking pixel
email1 = mail.outbox[0]
assert email1.to == ['alice@example.com']
assert email1.subject == 'Special Offer for Alice'
assert str(rec1.tracking_token) in email1.alternatives[0][0]
email2 = mail.outbox[1]
assert email2.to == ['bob@example.com']
assert email2.subject == 'Special Offer for Bob'
assert str(rec2.tracking_token) in email2.alternatives[0][0]

View file

@ -21,6 +21,10 @@ class FlowDefinitionViewSet(viewsets.ModelViewSet):
log = execute_flow_dag(flow, initial_context=context_data, idempotency_key=idempotency_key) log = execute_flow_dag(flow, initial_context=context_data, idempotency_key=idempotency_key)
return Response(FlowExecutionLogSerializer(log).data, status=status.HTTP_200_OK) return Response(FlowExecutionLogSerializer(log).data, status=status.HTTP_200_OK)
@action(detail=True, methods=['post'], url_path='execute')
def execute_flow(self, request, pk=None):
return self.run_flow(request, pk)
class FlowExecutionLogViewSet(viewsets.ReadOnlyModelViewSet): class FlowExecutionLogViewSet(viewsets.ReadOnlyModelViewSet):
permission_classes = [IsAuthenticated] permission_classes = [IsAuthenticated]