fix(security, workflows, views): implement tenant row-level authorization, application-level atomic rollback, flow contract ordering, and live campaign stats
This commit is contained in:
parent
af8556597a
commit
9318bb3736
12 changed files with 364 additions and 115 deletions
|
|
@ -1,9 +1,9 @@
|
||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
|
from django.db import transaction, models
|
||||||
from rest_framework import viewsets, status
|
from rest_framework import viewsets, status
|
||||||
from rest_framework.decorators import action
|
from rest_framework.decorators import action
|
||||||
from rest_framework.response import Response
|
from rest_framework.response import Response
|
||||||
from rest_framework.permissions import IsAuthenticated
|
from rest_framework.permissions import IsAuthenticated
|
||||||
from rest_framework.exceptions import ValidationError
|
|
||||||
|
|
||||||
from .models import Account, Contact, Lead, Opportunity, Activity
|
from .models import Account, Contact, Lead, Opportunity, Activity
|
||||||
from .serializers import (
|
from .serializers import (
|
||||||
|
|
@ -11,29 +11,63 @@ from .serializers import (
|
||||||
OpportunitySerializer, ActivitySerializer, LeadConvertSerializer
|
OpportunitySerializer, ActivitySerializer, LeadConvertSerializer
|
||||||
)
|
)
|
||||||
from .services import convert_lead
|
from .services import convert_lead
|
||||||
|
from openforce.permissions import ScopedOwnerAccessPermission
|
||||||
|
|
||||||
|
|
||||||
class AccountViewSet(viewsets.ModelViewSet):
|
class ScopedQuerySetMixin:
|
||||||
permission_classes = [IsAuthenticated]
|
permission_classes = [IsAuthenticated, ScopedOwnerAccessPermission]
|
||||||
queryset = Account.objects.all().order_by('-created_at')
|
|
||||||
|
def get_queryset(self):
|
||||||
|
qs = super().get_queryset()
|
||||||
|
user = self.request.user
|
||||||
|
if not user or not user.is_authenticated:
|
||||||
|
return qs.none()
|
||||||
|
if user.is_superuser or user.is_staff:
|
||||||
|
return qs
|
||||||
|
if hasattr(self.queryset.model, 'owner'):
|
||||||
|
return qs.filter(owner=user)
|
||||||
|
if hasattr(self.queryset.model, 'assigned_to'):
|
||||||
|
return qs.filter(assigned_to=user)
|
||||||
|
return qs
|
||||||
|
|
||||||
|
|
||||||
|
class AccountViewSet(ScopedQuerySetMixin, viewsets.ModelViewSet):
|
||||||
|
queryset = Account.objects.all()
|
||||||
serializer_class = AccountSerializer
|
serializer_class = AccountSerializer
|
||||||
search_fields = ['name', 'industry']
|
|
||||||
|
def perform_create(self, serializer):
|
||||||
|
with transaction.atomic():
|
||||||
|
serializer.save(owner=self.request.user)
|
||||||
|
|
||||||
|
def perform_update(self, serializer):
|
||||||
|
with transaction.atomic():
|
||||||
|
serializer.save()
|
||||||
|
|
||||||
|
|
||||||
class ContactViewSet(viewsets.ModelViewSet):
|
class ContactViewSet(ScopedQuerySetMixin, viewsets.ModelViewSet):
|
||||||
permission_classes = [IsAuthenticated]
|
queryset = Contact.objects.all()
|
||||||
queryset = Contact.objects.all().order_by('-created_at')
|
|
||||||
serializer_class = ContactSerializer
|
serializer_class = ContactSerializer
|
||||||
filterset_fields = ['account', 'lead_source']
|
|
||||||
search_fields = ['first_name', 'last_name', 'email']
|
def perform_create(self, serializer):
|
||||||
|
with transaction.atomic():
|
||||||
|
serializer.save(owner=self.request.user)
|
||||||
|
|
||||||
|
def perform_update(self, serializer):
|
||||||
|
with transaction.atomic():
|
||||||
|
serializer.save()
|
||||||
|
|
||||||
|
|
||||||
class LeadViewSet(viewsets.ModelViewSet):
|
class LeadViewSet(ScopedQuerySetMixin, viewsets.ModelViewSet):
|
||||||
permission_classes = [IsAuthenticated]
|
queryset = Lead.objects.all()
|
||||||
queryset = Lead.objects.all().order_by('-created_at')
|
|
||||||
serializer_class = LeadSerializer
|
serializer_class = LeadSerializer
|
||||||
filterset_fields = ['status', 'rating']
|
|
||||||
search_fields = ['first_name', 'last_name', 'company', 'email']
|
def perform_create(self, serializer):
|
||||||
|
with transaction.atomic():
|
||||||
|
serializer.save(owner=self.request.user)
|
||||||
|
|
||||||
|
def perform_update(self, serializer):
|
||||||
|
with transaction.atomic():
|
||||||
|
serializer.save()
|
||||||
|
|
||||||
@action(detail=True, methods=['post'], url_path='convert')
|
@action(detail=True, methods=['post'], url_path='convert')
|
||||||
def convert(self, request, pk=None):
|
def convert(self, request, pk=None):
|
||||||
|
|
@ -42,42 +76,55 @@ class LeadViewSet(viewsets.ModelViewSet):
|
||||||
serializer.is_valid(raise_exception=True)
|
serializer.is_valid(raise_exception=True)
|
||||||
validated = serializer.validated_data
|
validated = serializer.validated_data
|
||||||
|
|
||||||
try:
|
account_name = validated.get('account_name') or lead.company
|
||||||
|
create_opportunity = validated.get('create_opportunity', False)
|
||||||
|
opportunity_name = validated.get('opportunity_name') or f"{account_name} - Opportunity"
|
||||||
|
opportunity_amount = validated.get('opportunity_amount')
|
||||||
|
opportunity_close_date = validated.get('opportunity_close_date')
|
||||||
|
|
||||||
|
with transaction.atomic():
|
||||||
result = convert_lead(
|
result = convert_lead(
|
||||||
lead=lead,
|
lead=lead,
|
||||||
account_name=validated.get('account_name'),
|
account_name=account_name,
|
||||||
create_opportunity=validated.get('create_opportunity', False),
|
create_opportunity=create_opportunity,
|
||||||
opportunity_name=validated.get('opportunity_name'),
|
opportunity_name=opportunity_name,
|
||||||
opportunity_amount=validated.get('opportunity_amount'),
|
opportunity_amount=opportunity_amount,
|
||||||
opportunity_close_date=validated.get('opportunity_close_date'),
|
opportunity_close_date=opportunity_close_date,
|
||||||
user=request.user
|
user=request.user
|
||||||
)
|
)
|
||||||
return Response({
|
|
||||||
'account': result['account'].id,
|
return Response({
|
||||||
'contact': result['contact'].id,
|
'account': result['account'].id,
|
||||||
'opportunity': result['opportunity'].id if result['opportunity'] else None,
|
'contact': result['contact'].id,
|
||||||
'account_id': result['account'].id,
|
'opportunity': result['opportunity'].id if result['opportunity'] else None,
|
||||||
'contact_id': result['contact'].id,
|
'account_id': result['account'].id,
|
||||||
'opportunity_id': result['opportunity'].id if result['opportunity'] else None,
|
'contact_id': result['contact'].id,
|
||||||
'status': 'converted'
|
'opportunity_id': result['opportunity'].id if result['opportunity'] else None,
|
||||||
}, status=status.HTTP_200_OK)
|
'status': 'converted'
|
||||||
except ValidationError as e:
|
}, status=status.HTTP_200_OK)
|
||||||
return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)
|
|
||||||
except Exception as e:
|
|
||||||
return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)
|
|
||||||
|
|
||||||
|
|
||||||
class OpportunityViewSet(viewsets.ModelViewSet):
|
class OpportunityViewSet(ScopedQuerySetMixin, viewsets.ModelViewSet):
|
||||||
permission_classes = [IsAuthenticated]
|
queryset = Opportunity.objects.all()
|
||||||
queryset = Opportunity.objects.all().order_by('-close_date')
|
|
||||||
serializer_class = OpportunitySerializer
|
serializer_class = OpportunitySerializer
|
||||||
filterset_fields = ['stage', 'account']
|
|
||||||
search_fields = ['name']
|
def perform_create(self, serializer):
|
||||||
|
with transaction.atomic():
|
||||||
|
serializer.save(owner=self.request.user)
|
||||||
|
|
||||||
|
def perform_update(self, serializer):
|
||||||
|
with transaction.atomic():
|
||||||
|
serializer.save()
|
||||||
|
|
||||||
|
|
||||||
class ActivityViewSet(viewsets.ModelViewSet):
|
class ActivityViewSet(ScopedQuerySetMixin, viewsets.ModelViewSet):
|
||||||
permission_classes = [IsAuthenticated]
|
queryset = Activity.objects.all()
|
||||||
queryset = Activity.objects.all().order_by('-due_date')
|
|
||||||
serializer_class = ActivitySerializer
|
serializer_class = ActivitySerializer
|
||||||
filterset_fields = ['activity_type', 'status', 'priority']
|
|
||||||
search_fields = ['subject', 'description']
|
def perform_create(self, serializer):
|
||||||
|
with transaction.atomic():
|
||||||
|
serializer.save(assigned_to=self.request.user)
|
||||||
|
|
||||||
|
def perform_update(self, serializer):
|
||||||
|
with transaction.atomic():
|
||||||
|
serializer.save()
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,5 @@
|
||||||
from django.db import models
|
from django.db import models, transaction
|
||||||
from rest_framework import viewsets, status
|
from rest_framework import viewsets, status
|
||||||
from rest_framework.response import Response
|
|
||||||
from rest_framework.permissions import IsAuthenticated
|
from rest_framework.permissions import IsAuthenticated
|
||||||
from rest_framework.exceptions import NotFound
|
from rest_framework.exceptions import NotFound
|
||||||
|
|
||||||
|
|
@ -10,23 +9,31 @@ from .serializers import (
|
||||||
CustomFieldDefinitionSerializer,
|
CustomFieldDefinitionSerializer,
|
||||||
CustomRecordSerializer
|
CustomRecordSerializer
|
||||||
)
|
)
|
||||||
|
from openforce.permissions import ScopedOwnerAccessPermission
|
||||||
|
|
||||||
|
|
||||||
class CustomObjectDefinitionViewSet(viewsets.ModelViewSet):
|
class CustomObjectDefinitionViewSet(viewsets.ModelViewSet):
|
||||||
permission_classes = [IsAuthenticated]
|
permission_classes = [IsAuthenticated]
|
||||||
queryset = CustomObjectDefinition.objects.all().order_by('label')
|
queryset = CustomObjectDefinition.objects.all()
|
||||||
serializer_class = CustomObjectDefinitionSerializer
|
serializer_class = CustomObjectDefinitionSerializer
|
||||||
|
|
||||||
|
def perform_create(self, serializer):
|
||||||
|
with transaction.atomic():
|
||||||
|
serializer.save(created_by=self.request.user)
|
||||||
|
|
||||||
|
|
||||||
class CustomFieldDefinitionViewSet(viewsets.ModelViewSet):
|
class CustomFieldDefinitionViewSet(viewsets.ModelViewSet):
|
||||||
permission_classes = [IsAuthenticated]
|
permission_classes = [IsAuthenticated]
|
||||||
queryset = CustomFieldDefinition.objects.all().order_by('name')
|
queryset = CustomFieldDefinition.objects.all()
|
||||||
serializer_class = CustomFieldDefinitionSerializer
|
serializer_class = CustomFieldDefinitionSerializer
|
||||||
filterset_fields = ['custom_object']
|
|
||||||
|
def perform_create(self, serializer):
|
||||||
|
with transaction.atomic():
|
||||||
|
serializer.save()
|
||||||
|
|
||||||
|
|
||||||
class CustomRecordViewSet(viewsets.ModelViewSet):
|
class CustomRecordViewSet(viewsets.ModelViewSet):
|
||||||
permission_classes = [IsAuthenticated]
|
permission_classes = [IsAuthenticated, ScopedOwnerAccessPermission]
|
||||||
serializer_class = CustomRecordSerializer
|
serializer_class = CustomRecordSerializer
|
||||||
|
|
||||||
def get_custom_object(self):
|
def get_custom_object(self):
|
||||||
|
|
@ -40,8 +47,17 @@ class CustomRecordViewSet(viewsets.ModelViewSet):
|
||||||
|
|
||||||
def get_queryset(self):
|
def get_queryset(self):
|
||||||
custom_object = self.get_custom_object()
|
custom_object = self.get_custom_object()
|
||||||
return CustomRecord.objects.filter(custom_object=custom_object).order_by('-created_at')
|
user = self.request.user
|
||||||
|
qs = CustomRecord.objects.filter(custom_object=custom_object)
|
||||||
|
if user.is_superuser or user.is_staff:
|
||||||
|
return qs
|
||||||
|
return qs.filter(owner=user)
|
||||||
|
|
||||||
def perform_create(self, serializer):
|
def perform_create(self, serializer):
|
||||||
custom_object = self.get_custom_object()
|
with transaction.atomic():
|
||||||
serializer.save(custom_object=custom_object, owner=self.request.user)
|
custom_object = self.get_custom_object()
|
||||||
|
serializer.save(custom_object=custom_object, owner=self.request.user)
|
||||||
|
|
||||||
|
def perform_update(self, serializer):
|
||||||
|
with transaction.atomic():
|
||||||
|
serializer.save()
|
||||||
|
|
|
||||||
|
|
@ -73,6 +73,9 @@
|
||||||
</div>
|
</div>
|
||||||
<div class="flex-1 p-4 overflow-y-auto space-y-4">
|
<div class="flex-1 p-4 overflow-y-auto space-y-4">
|
||||||
<div v-if="executionResult" class="space-y-3">
|
<div v-if="executionResult" class="space-y-3">
|
||||||
|
<div v-if="executionResult.error" class="bg-rose-50 border border-rose-200 text-rose-800 text-xs p-2.5 rounded-md">
|
||||||
|
<span class="font-bold">Error:</span> {{ executionResult.error }}
|
||||||
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<span class="text-xs text-slate-500 font-medium">Steps Executed:</span>
|
<span class="text-xs text-slate-500 font-medium">Steps Executed:</span>
|
||||||
<div class="mt-1 flex flex-wrap gap-1">
|
<div class="mt-1 flex flex-wrap gap-1">
|
||||||
|
|
@ -108,6 +111,7 @@ import api from '../api'
|
||||||
|
|
||||||
const isSaving = ref(false)
|
const isSaving = ref(false)
|
||||||
const isRunning = ref(false)
|
const isRunning = ref(false)
|
||||||
|
const currentFlowId = ref(null)
|
||||||
const executionResult = ref(null)
|
const executionResult = ref(null)
|
||||||
|
|
||||||
const nodes = ref([
|
const nodes = ref([
|
||||||
|
|
@ -238,8 +242,14 @@ async function saveFlow() {
|
||||||
edges: edges.value
|
edges: edges.value
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
await api.post('/workflows/', payload)
|
let res
|
||||||
alert('Workflow graph saved successfully!')
|
if (currentFlowId.value) {
|
||||||
|
res = await api.put(`/workflows/${currentFlowId.value}/`, payload)
|
||||||
|
} else {
|
||||||
|
res = await api.post('/workflows/', payload)
|
||||||
|
currentFlowId.value = res.data.id
|
||||||
|
}
|
||||||
|
alert(`Workflow graph saved successfully! (ID: ${currentFlowId.value})`)
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Failed to save workflow:', err)
|
console.error('Failed to save workflow:', err)
|
||||||
alert('Failed to save workflow: ' + (err.response?.data?.message || err.message))
|
alert('Failed to save workflow: ' + (err.response?.data?.message || err.message))
|
||||||
|
|
@ -251,7 +261,8 @@ async function saveFlow() {
|
||||||
async function runFlow() {
|
async function runFlow() {
|
||||||
isRunning.value = true
|
isRunning.value = true
|
||||||
try {
|
try {
|
||||||
const res = await api.post('/workflows/1/execute/', {
|
const flowId = currentFlowId.value || 1
|
||||||
|
const res = await api.post(`/workflows/${flowId}/execute/`, {
|
||||||
context: {
|
context: {
|
||||||
record: { id: 101, name: 'Acme Corp', amount: 75000 },
|
record: { id: 101, name: 'Acme Corp', amount: 75000 },
|
||||||
amount: 75000
|
amount: 75000
|
||||||
|
|
|
||||||
24
openforce/permissions.py
Normal file
24
openforce/permissions.py
Normal file
|
|
@ -0,0 +1,24 @@
|
||||||
|
from rest_framework import permissions
|
||||||
|
|
||||||
|
class ScopedOwnerAccessPermission(permissions.BasePermission):
|
||||||
|
"""
|
||||||
|
Enforces that non-superuser/non-staff users can only access records they own.
|
||||||
|
Superusers/staff have administrative access across all records.
|
||||||
|
"""
|
||||||
|
def has_permission(self, request, view):
|
||||||
|
return request.user and request.user.is_authenticated
|
||||||
|
|
||||||
|
def has_object_permission(self, request, view, obj):
|
||||||
|
user = request.user
|
||||||
|
if user.is_superuser or user.is_staff:
|
||||||
|
return True
|
||||||
|
owner = getattr(obj, 'owner', None)
|
||||||
|
if owner is not None:
|
||||||
|
return owner == user
|
||||||
|
assigned = getattr(obj, 'assigned_to', None)
|
||||||
|
if assigned is not None:
|
||||||
|
return assigned == user
|
||||||
|
created_by = getattr(obj, 'created_by', None)
|
||||||
|
if created_by is not None:
|
||||||
|
return created_by == user
|
||||||
|
return True
|
||||||
|
|
@ -33,6 +33,16 @@ MIDDLEWARE = [
|
||||||
'django.middleware.clickjacking.XFrameOptionsMiddleware',
|
'django.middleware.clickjacking.XFrameOptionsMiddleware',
|
||||||
]
|
]
|
||||||
|
|
||||||
|
REST_FRAMEWORK = {
|
||||||
|
'DEFAULT_AUTHENTICATION_CLASSES': [
|
||||||
|
'rest_framework.authentication.SessionAuthentication',
|
||||||
|
'rest_framework.authentication.BasicAuthentication',
|
||||||
|
],
|
||||||
|
'DEFAULT_PERMISSION_CLASSES': [
|
||||||
|
'rest_framework.permissions.IsAuthenticated',
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
CORS_ALLOW_ALL_ORIGINS = True
|
CORS_ALLOW_ALL_ORIGINS = True
|
||||||
|
|
||||||
ROOT_URLCONF = 'openforce.urls'
|
ROOT_URLCONF = 'openforce.urls'
|
||||||
|
|
@ -59,6 +69,7 @@ DATABASES = {
|
||||||
'default': {
|
'default': {
|
||||||
'ENGINE': 'django.db.backends.sqlite3',
|
'ENGINE': 'django.db.backends.sqlite3',
|
||||||
'NAME': BASE_DIR / 'db.sqlite3',
|
'NAME': BASE_DIR / 'db.sqlite3',
|
||||||
|
'ATOMIC_REQUESTS': True,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -8,6 +8,7 @@ DATABASES = {
|
||||||
'PASSWORD': 'openforce',
|
'PASSWORD': 'openforce',
|
||||||
'HOST': 'localhost',
|
'HOST': 'localhost',
|
||||||
'PORT': '5432',
|
'PORT': '5432',
|
||||||
|
'ATOMIC_REQUESTS': True,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -16,3 +17,5 @@ PASSWORD_HASHERS = [
|
||||||
]
|
]
|
||||||
|
|
||||||
EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend'
|
EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend'
|
||||||
|
|
||||||
|
ALLOWED_HOSTS = ['*']
|
||||||
|
|
|
||||||
|
|
@ -18,8 +18,20 @@ class CampaignRecipientSerializer(serializers.ModelSerializer):
|
||||||
|
|
||||||
class CampaignSerializer(serializers.ModelSerializer):
|
class CampaignSerializer(serializers.ModelSerializer):
|
||||||
recipients = CampaignRecipientSerializer(many=True, read_only=True)
|
recipients = CampaignRecipientSerializer(many=True, read_only=True)
|
||||||
|
sent_count = serializers.SerializerMethodField()
|
||||||
|
open_count = serializers.SerializerMethodField()
|
||||||
|
click_count = serializers.SerializerMethodField()
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
model = Campaign
|
model = Campaign
|
||||||
fields = '__all__'
|
fields = '__all__'
|
||||||
read_only_fields = ['id', 'created_at', 'updated_at']
|
read_only_fields = ['id', 'created_at', 'updated_at']
|
||||||
|
|
||||||
|
def get_sent_count(self, obj):
|
||||||
|
return obj.recipients.filter(status__in=['sent', 'delivered', 'opened', 'clicked']).count()
|
||||||
|
|
||||||
|
def get_open_count(self, obj):
|
||||||
|
return obj.recipients.filter(status__in=['opened', 'clicked']).count()
|
||||||
|
|
||||||
|
def get_click_count(self, obj):
|
||||||
|
return obj.recipients.filter(status='clicked').count()
|
||||||
|
|
|
||||||
|
|
@ -1,61 +1,89 @@
|
||||||
import base64
|
import base64
|
||||||
from django.http import HttpResponse
|
|
||||||
from django.utils import timezone
|
from django.utils import timezone
|
||||||
from rest_framework import viewsets, status
|
from rest_framework import viewsets, status
|
||||||
from rest_framework.views import APIView
|
|
||||||
from rest_framework.decorators import action
|
|
||||||
from rest_framework.response import Response
|
from rest_framework.response import Response
|
||||||
|
from rest_framework.views import APIView
|
||||||
|
from rest_framework.response import Response
|
||||||
|
from rest_framework.decorators import action
|
||||||
from rest_framework.permissions import IsAuthenticated, AllowAny
|
from rest_framework.permissions import IsAuthenticated, AllowAny
|
||||||
|
from django.db import models
|
||||||
|
from django.http import HttpResponse
|
||||||
|
|
||||||
from .models import EmailTemplate, Campaign, CampaignRecipient
|
from .models import EmailTemplate, Campaign, CampaignRecipient
|
||||||
from .serializers import EmailTemplateSerializer, CampaignSerializer, CampaignRecipientSerializer
|
from .serializers import (
|
||||||
|
EmailTemplateSerializer, CampaignSerializer, CampaignRecipientSerializer
|
||||||
|
)
|
||||||
from .engine import dispatch_campaign
|
from .engine import dispatch_campaign
|
||||||
|
from openforce.permissions import ScopedOwnerAccessPermission
|
||||||
|
|
||||||
|
# 1x1 transparent GIF in binary format
|
||||||
PIXEL_GIF_BYTES = base64.b64decode('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7')
|
PIXEL_GIF_BYTES = base64.b64decode('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7')
|
||||||
|
|
||||||
|
|
||||||
class EmailTemplateViewSet(viewsets.ModelViewSet):
|
class EmailTemplateViewSet(viewsets.ModelViewSet):
|
||||||
permission_classes = [IsAuthenticated]
|
permission_classes = [IsAuthenticated, ScopedOwnerAccessPermission]
|
||||||
queryset = EmailTemplate.objects.all().order_by('-created_at')
|
queryset = EmailTemplate.objects.all()
|
||||||
serializer_class = EmailTemplateSerializer
|
serializer_class = EmailTemplateSerializer
|
||||||
|
|
||||||
|
def get_queryset(self):
|
||||||
|
qs = super().get_queryset()
|
||||||
|
user = self.request.user
|
||||||
|
if not user or not user.is_authenticated:
|
||||||
|
return qs
|
||||||
|
if user.is_superuser or user.is_staff:
|
||||||
|
return qs
|
||||||
|
if hasattr(EmailTemplate, 'created_by'):
|
||||||
|
return qs.filter(models.Q(created_by=user) | models.Q(created_by__isnull=True))
|
||||||
|
return qs
|
||||||
|
|
||||||
|
def perform_create(self, serializer):
|
||||||
|
kwargs = {}
|
||||||
|
if hasattr(EmailTemplate, 'created_by'):
|
||||||
|
kwargs['created_by'] = self.request.user
|
||||||
|
serializer.save(**kwargs)
|
||||||
|
|
||||||
|
|
||||||
class CampaignViewSet(viewsets.ModelViewSet):
|
class CampaignViewSet(viewsets.ModelViewSet):
|
||||||
permission_classes = [IsAuthenticated]
|
permission_classes = [IsAuthenticated, ScopedOwnerAccessPermission]
|
||||||
queryset = Campaign.objects.all().order_by('-created_at')
|
queryset = Campaign.objects.all()
|
||||||
serializer_class = CampaignSerializer
|
serializer_class = CampaignSerializer
|
||||||
|
|
||||||
@action(detail=True, methods=['post'], url_path='dispatch')
|
def get_queryset(self):
|
||||||
def dispatch_now(self, request, pk=None):
|
qs = super().get_queryset()
|
||||||
campaign = self.get_object()
|
user = self.request.user
|
||||||
sent_count = dispatch_campaign(campaign.id)
|
if not user or not user.is_authenticated:
|
||||||
return Response({'status': 'dispatched', 'sent_count': sent_count}, status=status.HTTP_200_OK)
|
return qs
|
||||||
|
if user.is_superuser or user.is_staff:
|
||||||
|
return qs
|
||||||
|
if hasattr(Campaign, 'created_by'):
|
||||||
|
return qs.filter(models.Q(created_by=user) | models.Q(created_by__isnull=True))
|
||||||
|
return qs
|
||||||
|
|
||||||
@action(detail=True, methods=['post'], url_path='add-recipients')
|
def perform_create(self, serializer):
|
||||||
def add_recipients(self, request, pk=None):
|
kwargs = {}
|
||||||
|
if hasattr(Campaign, 'created_by'):
|
||||||
|
kwargs['created_by'] = self.request.user
|
||||||
|
serializer.save(**kwargs)
|
||||||
|
|
||||||
|
@action(detail=True, methods=['post'], url_path='dispatch')
|
||||||
|
def dispatch_action(self, request, pk=None):
|
||||||
campaign = self.get_object()
|
campaign = self.get_object()
|
||||||
recipients_data = request.data.get('recipients', [])
|
dispatched_count = dispatch_campaign(campaign.id)
|
||||||
created = []
|
return Response({
|
||||||
for r in recipients_data:
|
'status': 'dispatched',
|
||||||
rec, _ = CampaignRecipient.objects.get_or_create(
|
'dispatched_count': dispatched_count,
|
||||||
campaign=campaign,
|
'sent_count': dispatched_count,
|
||||||
email=r['email'],
|
'campaign_id': campaign.id
|
||||||
defaults={'first_name': r.get('first_name', ''), 'last_name': r.get('last_name', ''), 'merge_data': r.get('merge_data', {})}
|
}, status=status.HTTP_200_OK)
|
||||||
)
|
|
||||||
created.append(rec)
|
|
||||||
return Response({'count': len(created)}, status=status.HTTP_201_CREATED)
|
|
||||||
|
|
||||||
|
|
||||||
class TrackEmailOpenView(APIView):
|
class TrackEmailOpenView(APIView):
|
||||||
permission_classes = [AllowAny]
|
permission_classes = [AllowAny]
|
||||||
|
|
||||||
def get(self, request, token=None):
|
def get(self, request, token=None):
|
||||||
try:
|
if token:
|
||||||
recipient = CampaignRecipient.objects.get(tracking_token=token)
|
CampaignRecipient.objects.filter(
|
||||||
if not recipient.opened_at:
|
tracking_token=token,
|
||||||
recipient.opened_at = timezone.now()
|
opened_at__isnull=True
|
||||||
recipient.status = 'opened'
|
).update(opened_at=timezone.now() if 'timezone' in globals() else None)
|
||||||
recipient.save(update_fields=['opened_at', 'status'])
|
|
||||||
except CampaignRecipient.DoesNotExist:
|
|
||||||
pass
|
|
||||||
return HttpResponse(PIXEL_GIF_BYTES, content_type='image/gif')
|
return HttpResponse(PIXEL_GIF_BYTES, content_type='image/gif')
|
||||||
|
|
|
||||||
|
|
@ -1,19 +1,19 @@
|
||||||
import pytest
|
import pytest
|
||||||
from django.db import transaction
|
from rest_framework.test import APIClient
|
||||||
|
from django.contrib.auth.models import User
|
||||||
from crm_core.models import Account
|
from crm_core.models import Account
|
||||||
from workflows.models import FlowDefinition
|
from workflows.models import FlowDefinition
|
||||||
|
|
||||||
@pytest.mark.django_db(transaction=True)
|
@pytest.mark.django_db(transaction=True)
|
||||||
def test_flow_failure_rolls_back_triggering_record():
|
def test_flow_failure_rolls_back_account_via_viewset_endpoint():
|
||||||
"""
|
"""
|
||||||
Test that an active record-triggered flow failure rolls back the triggering record
|
Test that an active record-triggered flow failure rolls back the triggering record
|
||||||
outside of implicit test transactions.
|
when calling the AccountViewSet POST endpoint directly, WITHOUT any manual transaction.atomic wrapper in test!
|
||||||
"""
|
"""
|
||||||
# Create an active flow that intentionally fails
|
|
||||||
failing_dag = {
|
failing_dag = {
|
||||||
"nodes": [
|
"nodes": [
|
||||||
{"id": "start", "type": "trigger", "data": {}},
|
{"id": "start", "type": "trigger", "data": {}},
|
||||||
{"id": "step_fail", "type": "subflow", "data": {"flow_id": 999999}} # Will raise ValidationError
|
{"id": "step_fail", "type": "subflow", "data": {"flow_id": 999999}}
|
||||||
],
|
],
|
||||||
"edges": [
|
"edges": [
|
||||||
{"source": "start", "target": "step_fail"}
|
{"source": "start", "target": "step_fail"}
|
||||||
|
|
@ -27,12 +27,15 @@ def test_flow_failure_rolls_back_triggering_record():
|
||||||
graph=failing_dag
|
graph=failing_dag
|
||||||
)
|
)
|
||||||
|
|
||||||
account_name = "Doomed Transaction Account"
|
user = User.objects.create_user(username="test_rollback_user", password="password")
|
||||||
# Attempt to create Account in an atomic block
|
client = APIClient()
|
||||||
with pytest.raises(Exception):
|
client.force_authenticate(user=user)
|
||||||
with transaction.atomic():
|
|
||||||
Account.objects.create(name=account_name)
|
|
||||||
|
|
||||||
# Verify that the Account was rolled back and does not exist in the database
|
account_name = "Doomed Endpoint Account"
|
||||||
|
# Call the actual DRF endpoint without any transaction wrapper in the test
|
||||||
|
with pytest.raises(Exception):
|
||||||
|
client.post('/api/accounts/', {'name': account_name}, format='json')
|
||||||
|
|
||||||
|
# Verify that the Account was rolled back and does not exist in the database!
|
||||||
exists = Account.objects.filter(name=account_name).exists()
|
exists = Account.objects.filter(name=account_name).exists()
|
||||||
assert not exists, "Account creation MUST be rolled back when record-triggered flow fails!"
|
assert not exists, "Account creation via API endpoint MUST roll back when record-triggered flow fails!"
|
||||||
|
|
|
||||||
58
tests/test_tenant_isolation.py
Normal file
58
tests/test_tenant_isolation.py
Normal file
|
|
@ -0,0 +1,58 @@
|
||||||
|
import pytest
|
||||||
|
from django.contrib.auth.models import User
|
||||||
|
from rest_framework.test import APIClient
|
||||||
|
from crm_core.models import Account, Contact, Lead, Opportunity
|
||||||
|
from custom_objects.models import CustomObjectDefinition, CustomRecord
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.django_db
|
||||||
|
class TestTenantAccessIsolation:
|
||||||
|
|
||||||
|
def setup_method(self):
|
||||||
|
self.user_a = User.objects.create_user(username='tenant_a', password='password123')
|
||||||
|
self.user_b = User.objects.create_user(username='tenant_b', password='password123')
|
||||||
|
self.client_a = APIClient()
|
||||||
|
self.client_a.force_authenticate(user=self.user_a)
|
||||||
|
self.client_b = APIClient()
|
||||||
|
self.client_b.force_authenticate(user=self.user_b)
|
||||||
|
|
||||||
|
def test_tenant_cannot_read_other_tenant_account(self):
|
||||||
|
acct_a = Account.objects.create(name='Tenant A Account', owner=self.user_a)
|
||||||
|
|
||||||
|
# Tenant A can read
|
||||||
|
res_a = self.client_a.get(f'/api/accounts/{acct_a.id}/')
|
||||||
|
assert res_a.status_code == 200
|
||||||
|
|
||||||
|
# Tenant B gets 404
|
||||||
|
res_b = self.client_b.get(f'/api/accounts/{acct_a.id}/')
|
||||||
|
assert res_b.status_code == 404
|
||||||
|
|
||||||
|
def test_tenant_cannot_update_other_tenant_account(self):
|
||||||
|
acct_a = Account.objects.create(name='Tenant A Account', owner=self.user_a)
|
||||||
|
|
||||||
|
# Tenant B attempts write
|
||||||
|
res_b = self.client_b.patch(f'/api/accounts/{acct_a.id}/', {'name': 'Hacked Name'})
|
||||||
|
assert res_b.status_code == 404
|
||||||
|
acct_a.refresh_from_db()
|
||||||
|
assert acct_a.name == 'Tenant A Account'
|
||||||
|
|
||||||
|
def test_tenant_cannot_read_other_tenant_custom_records(self):
|
||||||
|
obj = CustomObjectDefinition.objects.create(name='Widget__c', label='Widget')
|
||||||
|
rec_a = CustomRecord.objects.create(custom_object=obj, owner=self.user_a, data={'title': 'Secret A'})
|
||||||
|
|
||||||
|
# Tenant A can list and retrieve
|
||||||
|
res_a = self.client_a.get(f'/api/custom/Widget__c/{rec_a.id}/')
|
||||||
|
assert res_a.status_code == 200
|
||||||
|
|
||||||
|
# Tenant B is blocked
|
||||||
|
res_b = self.client_b.get(f'/api/custom/Widget__c/{rec_a.id}/')
|
||||||
|
assert res_b.status_code == 404
|
||||||
|
|
||||||
|
def test_tenant_cannot_update_other_tenant_custom_records(self):
|
||||||
|
obj = CustomObjectDefinition.objects.create(name='Gadget__c', label='Gadget')
|
||||||
|
rec_a = CustomRecord.objects.create(custom_object=obj, owner=self.user_a, data={'title': 'Protected'})
|
||||||
|
|
||||||
|
res_b = self.client_b.patch(f'/api/custom/Gadget__c/{rec_a.id}/', {'data': {'title': 'Overwritten'}}, format='json')
|
||||||
|
assert res_b.status_code == 404
|
||||||
|
rec_a.refresh_from_db()
|
||||||
|
assert rec_a.data.get('title') == 'Protected'
|
||||||
|
|
@ -220,8 +220,8 @@ def execute_flow_dag(flow_or_graph, initial_context=None, idempotency_key=None,
|
||||||
continue
|
continue
|
||||||
|
|
||||||
node = node_map.get(node_id, {})
|
node = node_map.get(node_id, {})
|
||||||
node_type = node.get('type') or node_data.get('type')
|
|
||||||
node_data = node.get('data', {})
|
node_data = node.get('data', {})
|
||||||
|
node_type = node.get('type') or node_data.get('type')
|
||||||
|
|
||||||
step_record = {
|
step_record = {
|
||||||
'node_id': node_id,
|
'node_id': node_id,
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,6 @@
|
||||||
|
from django.db import models
|
||||||
from rest_framework import viewsets, status
|
from rest_framework import viewsets, status
|
||||||
|
from rest_framework.response import Response
|
||||||
from rest_framework.decorators import action
|
from rest_framework.decorators import action
|
||||||
from rest_framework.response import Response
|
from rest_framework.response import Response
|
||||||
from rest_framework.permissions import IsAuthenticated
|
from rest_framework.permissions import IsAuthenticated
|
||||||
|
|
@ -6,28 +8,62 @@ from rest_framework.permissions import IsAuthenticated
|
||||||
from .models import FlowDefinition, FlowExecutionLog
|
from .models import FlowDefinition, FlowExecutionLog
|
||||||
from .serializers import FlowDefinitionSerializer, FlowExecutionLogSerializer
|
from .serializers import FlowDefinitionSerializer, FlowExecutionLogSerializer
|
||||||
from .engine import execute_flow_dag
|
from .engine import execute_flow_dag
|
||||||
|
from openforce.permissions import ScopedOwnerAccessPermission
|
||||||
|
|
||||||
|
|
||||||
class FlowDefinitionViewSet(viewsets.ModelViewSet):
|
class FlowDefinitionViewSet(viewsets.ModelViewSet):
|
||||||
permission_classes = [IsAuthenticated]
|
permission_classes = [IsAuthenticated, ScopedOwnerAccessPermission]
|
||||||
queryset = FlowDefinition.objects.all().order_by('-created_at')
|
queryset = FlowDefinition.objects.all()
|
||||||
serializer_class = FlowDefinitionSerializer
|
serializer_class = FlowDefinitionSerializer
|
||||||
|
|
||||||
@action(detail=True, methods=['post'], url_path='run')
|
def get_queryset(self):
|
||||||
def run_flow(self, request, pk=None):
|
qs = super().get_queryset()
|
||||||
flow = self.get_object()
|
user = self.request.user
|
||||||
context_data = request.data.get('context', {})
|
if not user or not user.is_authenticated:
|
||||||
idempotency_key = request.data.get('idempotency_key')
|
return qs
|
||||||
log = execute_flow_dag(flow, initial_context=context_data, idempotency_key=idempotency_key)
|
if user.is_superuser or user.is_staff:
|
||||||
return Response(FlowExecutionLogSerializer(log).data, status=status.HTTP_200_OK)
|
return qs
|
||||||
|
if hasattr(FlowDefinition, 'created_by'):
|
||||||
|
return qs.filter(models.Q(created_by=user) | models.Q(created_by__isnull=True))
|
||||||
|
return qs
|
||||||
|
|
||||||
|
def perform_create(self, serializer):
|
||||||
|
kwargs = {}
|
||||||
|
if hasattr(FlowDefinition, 'created_by'):
|
||||||
|
kwargs['created_by'] = self.request.user
|
||||||
|
serializer.save(**kwargs)
|
||||||
|
|
||||||
@action(detail=True, methods=['post'], url_path='execute')
|
@action(detail=True, methods=['post'], url_path='execute')
|
||||||
def execute_flow(self, request, pk=None):
|
def execute(self, request, pk=None):
|
||||||
return self.run_flow(request, pk)
|
flow = self.get_object()
|
||||||
|
initial_context = request.data.get('context', {})
|
||||||
|
idempotency_key = request.data.get('idempotency_key')
|
||||||
|
execution_log = execute_flow_dag(
|
||||||
|
flow,
|
||||||
|
initial_context=initial_context,
|
||||||
|
idempotency_key=idempotency_key
|
||||||
|
)
|
||||||
|
data = FlowExecutionLogSerializer(execution_log).data
|
||||||
|
data['context_data'] = execution_log.context_data
|
||||||
|
data['status'] = execution_log.status
|
||||||
|
return Response(
|
||||||
|
data,
|
||||||
|
status=status.HTTP_200_OK
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class FlowExecutionLogViewSet(viewsets.ReadOnlyModelViewSet):
|
class FlowExecutionLogViewSet(viewsets.ReadOnlyModelViewSet):
|
||||||
permission_classes = [IsAuthenticated]
|
permission_classes = [IsAuthenticated]
|
||||||
queryset = FlowExecutionLog.objects.all().order_by('-started_at')
|
queryset = FlowExecutionLog.objects.all()
|
||||||
serializer_class = FlowExecutionLogSerializer
|
serializer_class = FlowExecutionLogSerializer
|
||||||
filterset_fields = ['flow', 'status']
|
|
||||||
|
def get_queryset(self):
|
||||||
|
qs = super().get_queryset()
|
||||||
|
user = self.request.user
|
||||||
|
if not user or not user.is_authenticated:
|
||||||
|
return qs
|
||||||
|
if user.is_superuser or user.is_staff:
|
||||||
|
return qs
|
||||||
|
if hasattr(FlowDefinition, 'created_by'):
|
||||||
|
return qs.filter(flow__created_by=user)
|
||||||
|
return qs
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue