• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

chiefonboarding / ChiefOnboarding / 22248500823

21 Feb 2026 02:19AM UTC coverage: 90.474% (-0.1%) from 90.569%
22248500823

Pull #621

github

web-flow
Merge 0e8044d5a into 6eb818dff
Pull Request #621: Pritunl compatibility

8187 of 9049 relevant lines covered (90.47%)

0.9 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

83.92
back/admin/integrations/models.py
1
import base64
1✔
2
import io
1✔
3
import json
1✔
4
import time
1✔
5
import uuid
1✔
6
from datetime import timedelta
1✔
7
from json.decoder import JSONDecodeError as NativeJSONDecodeError
1✔
8

9
import requests
1✔
10
from django.conf import settings
1✔
11
from django.core.exceptions import ValidationError
1✔
12
from django.db import models
1✔
13
from django.db.models.signals import post_delete
1✔
14
from django.dispatch import receiver
1✔
15
from django.template import Context, Template
1✔
16
from django.template.loader import render_to_string
1✔
17
from django.urls import reverse, reverse_lazy
1✔
18
from django.utils import timezone
1✔
19
from django.utils.crypto import get_random_string
1✔
20
from django.utils.translation import gettext_lazy as _
1✔
21
from django_q.models import Schedule
1✔
22
from django_q.tasks import schedule
1✔
23
from requests.exceptions import (
1✔
24
    HTTPError,
25
    InvalidHeader,
26
    InvalidJSONError,
27
    InvalidSchema,
28
    InvalidURL,
29
    JSONDecodeError,
30
    MissingSchema,
31
    SSLError,
32
    Timeout,
33
    TooManyRedirects,
34
    URLRequired,
35
)
36
from twilio.rest import Client
1✔
37

38
from admin.integrations.helpers.pritunl import pritunl_headers
1✔
39
from admin.integrations.serializers import (
1✔
40
    SyncUsersManifestSerializer,
41
    WebhookManifestSerializer,
42
)
43
from admin.integrations.utils import get_value_from_notation
1✔
44
from misc.fernet_fields import EncryptedTextField
1✔
45
from misc.fields import EncryptedJSONField
1✔
46
from organization.models import Notification
1✔
47
from organization.utils import has_manager_or_buddy_tags, send_email_with_notification
1✔
48

49

50
class IntegrationTracker(models.Model):
1✔
51
    """Model to track the integrations that ran. Gives insights into error messages"""
52

53
    class Category(models.IntegerChoices):
1✔
54
        EXECUTE = 0, _("Run the execute part")
1✔
55
        EXISTS = 1, _("Check if user exists")
1✔
56
        REVOKE = 2, _("Revoke user")
1✔
57

58
    integration = models.ForeignKey(
1✔
59
        "integrations.Integration", on_delete=models.CASCADE, null=True
60
    )
61
    category = models.IntegerField(choices=Category.choices)
1✔
62
    for_user = models.ForeignKey("users.User", on_delete=models.CASCADE, null=True)
1✔
63
    ran_at = models.DateTimeField(auto_now_add=True)
1✔
64

65
    @property
1✔
66
    def ran_execute_block(self):
1✔
67
        return self.category == IntegrationTracker.Category.EXECUTE
×
68

69
    @property
1✔
70
    def ran_exists_block(self):
1✔
71
        return self.category == IntegrationTracker.Category.EXISTS
×
72

73
    @property
1✔
74
    def ran_revoke_block(self):
1✔
75
        return self.category == IntegrationTracker.Category.REVOKE
×
76

77

78
class IntegrationTrackerStep(models.Model):
1✔
79
    tracker = models.ForeignKey(
1✔
80
        "integrations.IntegrationTracker",
81
        on_delete=models.CASCADE,
82
        related_name="steps",
83
    )
84
    status_code = models.IntegerField()
1✔
85
    json_response = models.JSONField()
1✔
86
    text_response = models.TextField()
1✔
87
    url = models.TextField()
1✔
88
    method = models.TextField()
1✔
89
    post_data = models.JSONField()
1✔
90
    headers = models.JSONField()
1✔
91
    expected = models.TextField()
1✔
92
    error = models.TextField()
1✔
93

94
    @property
1✔
95
    def has_succeeded(self):
1✔
96
        return self.status_code >= 200 and self.status_code < 300
×
97

98
    @property
1✔
99
    def found_expected(self):
1✔
100
        if self.expected == "":
1✔
101
            return True
×
102

103
        if self.text_response != "":
1✔
104
            return self.expected in self.text_response
×
105
        if len(self.json_response):
1✔
106
            return self.expected in json.dumps(self.json_response)
1✔
107
        return False
×
108

109
    @property
1✔
110
    def pretty_json_response(self):
1✔
111
        return json.dumps(self.json_response, indent=4)
1✔
112

113
    @property
1✔
114
    def pretty_headers(self):
1✔
115
        return json.dumps(self.headers, indent=4)
1✔
116

117
    @property
1✔
118
    def pretty_post_data(self):
1✔
119
        return json.dumps(self.post_data, indent=4)
1✔
120

121

122
class IntegrationManager(models.Manager):
1✔
123
    def get_queryset(self):
1✔
124
        return super().get_queryset()
1✔
125

126
    def sequence_integration_options(self):
1✔
127
        # any webhooks and account provisioning
128
        return self.get_queryset().filter(
1✔
129
            integration=Integration.Type.CUSTOM,
130
            manifest_type__in=[
131
                Integration.ManifestType.WEBHOOK,
132
                Integration.ManifestType.MANUAL_USER_PROVISIONING,
133
            ],
134
        )
135

136
    def account_provision_options(self):
1✔
137
        # only account provisioning (no general webhooks)
138
        return self.get_queryset().filter(
1✔
139
            integration=Integration.Type.CUSTOM,
140
            manifest_type=Integration.ManifestType.WEBHOOK,
141
            manifest__exists__isnull=False,
142
        ) | self.get_queryset().filter(
143
            integration=Integration.Type.CUSTOM,
144
            manifest_type=Integration.ManifestType.MANUAL_USER_PROVISIONING,
145
        )
146

147
    def import_users_options(self):
1✔
148
        # only import user items
149
        return (
1✔
150
            self.get_queryset()
151
            .filter(
152
                integration=Integration.Type.CUSTOM,
153
                manifest_type=Integration.ManifestType.SYNC_USERS,
154
            )
155
            .exclude(manifest__schedule__isnull=False)
156
        )
157

158

159
class IntegrationInactiveManager(models.Manager):
1✔
160
    def get_queryset(self):
1✔
161
        return super().get_queryset().filter(is_active=False)
1✔
162

163

164
class Integration(models.Model):
1✔
165
    class Type(models.IntegerChoices):
1✔
166
        SLACK_BOT = 0, _("Slack bot")
1✔
167
        CUSTOM = 10, _("Custom")
1✔
168

169
    class ManifestType(models.IntegerChoices):
1✔
170
        WEBHOOK = 0, _("Provision user accounts or trigger webhooks")
1✔
171
        SYNC_USERS = 1, _("Sync users")
1✔
172
        MANUAL_USER_PROVISIONING = (
1✔
173
            3,
174
            _("Manual user account provisioning, no manifest required"),
175
        )
176

177
    name = models.CharField(max_length=300, default="", blank=True)
1✔
178
    is_active = models.BooleanField(
1✔
179
        default=True, help_text="If inactive, it's a test/debug integration"
180
    )
181
    integration = models.IntegerField(choices=Type.choices)
1✔
182
    manifest_type = models.IntegerField(
1✔
183
        choices=ManifestType.choices, null=True, blank=True
184
    )
185
    token = EncryptedTextField(max_length=10000, default="", blank=True)
1✔
186
    refresh_token = EncryptedTextField(max_length=10000, default="", blank=True)
1✔
187
    base_url = models.CharField(max_length=22300, default="", blank=True)
1✔
188
    redirect_url = models.CharField(max_length=22300, default="", blank=True)
1✔
189
    account_id = models.CharField(max_length=22300, default="", blank=True)
1✔
190
    active = models.BooleanField(default=True)  # legacy?
1✔
191
    ttl = models.IntegerField(null=True, blank=True)
1✔
192
    expiring = models.DateTimeField(auto_now_add=True, blank=True)
1✔
193
    one_time_auth_code = models.UUIDField(
1✔
194
        default=uuid.uuid4, editable=False, unique=True
195
    )
196

197
    manifest = models.JSONField(default=dict, null=True, blank=True)
1✔
198
    extra_args = EncryptedJSONField(default=dict)
1✔
199
    enabled_oauth = models.BooleanField(default=False)
1✔
200

201
    # Slack
202
    app_id = models.CharField(max_length=100, default="")
1✔
203
    client_id = models.CharField(max_length=100, default="")
1✔
204
    client_secret = models.CharField(max_length=100, default="")
1✔
205
    signing_secret = models.CharField(max_length=100, default="")
1✔
206
    verification_token = models.CharField(max_length=100, default="")
1✔
207
    bot_token = EncryptedTextField(max_length=10000, default="", blank=True)
1✔
208
    bot_id = models.CharField(max_length=100, default="")
1✔
209

210
    @property
1✔
211
    def skip_user_provisioning(self):
1✔
212
        return self.manifest_type == Integration.ManifestType.MANUAL_USER_PROVISIONING
1✔
213

214
    @property
1✔
215
    def is_sync_users_integration(self):
1✔
216
        return self.manifest_type == Integration.ManifestType.SYNC_USERS
×
217

218
    @property
1✔
219
    def can_revoke_access(self):
1✔
220
        return len(self.manifest.get("revoke", []))
1✔
221

222
    @property
1✔
223
    def update_url(self):
1✔
224
        return reverse("integrations:update", args=[self.id])
1✔
225

226
    def get_icon_template(self):
1✔
227
        return render_to_string("_integration_config.html")
1✔
228

229
    @property
1✔
230
    def schedule_name(self):
1✔
231
        return f"User sync for integration: {self.id}"
1✔
232

233
    @property
1✔
234
    def secret_values(self):
1✔
235
        return [
1✔
236
            item
237
            for item in self.manifest["initial_data_form"]
238
            if item.get("secret", False) and item.get("name") != "generate"
239
        ]
240

241
    @property
1✔
242
    def missing_secret_values(self):
1✔
243
        return [
×
244
            item for item in self.secret_values if item["id"] not in self.extra_args
245
        ]
246

247
    @property
1✔
248
    def filled_secret_values(self):
1✔
249
        return [item for item in self.secret_values if item["id"] in self.extra_args]
1✔
250

251
    @property
1✔
252
    def requires_assigned_manager_or_buddy(self):
1✔
253
        # returns manager, buddy
254
        return has_manager_or_buddy_tags(self.manifest)
1✔
255

256
    def clean(self):
1✔
257
        if not self.manifest or self.skip_user_provisioning:
1✔
258
            # ignore field if form doesn't have it or no manifest is necessary
259
            return
1✔
260

261
        if self.manifest_type == Integration.ManifestType.WEBHOOK:
1✔
262
            manifest_serializer = WebhookManifestSerializer(data=self.manifest)
1✔
263
        else:
264
            manifest_serializer = SyncUsersManifestSerializer(data=self.manifest)
1✔
265
        if not manifest_serializer.is_valid():
1✔
266
            raise ValidationError({"manifest": json.dumps(manifest_serializer.errors)})
×
267

268
    def save(self, *args, **kwargs):
1✔
269
        super().save(*args, **kwargs)
1✔
270

271
        # skip if it's not a sync user integration (no background jobs for the others)
272
        if self.manifest_type != Integration.ManifestType.SYNC_USERS:
1✔
273
            return
1✔
274

275
        # update the background job based on the manifest
276
        schedule_cron = self.manifest.get("schedule")
1✔
277

278
        try:
1✔
279
            schedule_obj = Schedule.objects.get(name=self.schedule_name)
1✔
280
        except Schedule.DoesNotExist:
1✔
281
            # Schedule does not exist yet, so create it if specified
282
            if schedule_cron:
1✔
283
                schedule(
1✔
284
                    "admin.integrations.tasks.sync_user_info",
285
                    self.id,
286
                    schedule_type=Schedule.CRON,
287
                    cron=schedule_cron,
288
                    name=self.schedule_name,
289
                )
290
            return
1✔
291

292
        # delete if cron was removed
293
        if schedule_cron is None:
1✔
294
            schedule_obj.delete()
1✔
295
            return
1✔
296

297
        # if schedule changed, then update
298
        if schedule_obj.cron != schedule_cron:
×
299
            schedule_obj.cron = schedule_cron
×
300
            schedule_obj.save()
×
301

302
    def register_manual_integration_run(self, user):
1✔
303
        from users.models import IntegrationUser
1✔
304

305
        IntegrationUser.objects.update_or_create(
1✔
306
            user=user,
307
            integration=self,
308
            defaults={"revoked": user.is_offboarding},
309
        )
310

311
    def cast_to_json(self, value):
1✔
312
        try:
1✔
313
            value = json.loads(value)
1✔
314
        except Exception:
1✔
315
            pass
1✔
316

317
        return value
1✔
318

319
    def run_request(self, data):
1✔
320
        url = self._replace_vars(data["url"])
1✔
321
        if "data" in data:
1✔
322
            post_data = self._replace_vars(json.dumps(data["data"]))
1✔
323
        else:
324
            post_data = {}
1✔
325
        if data.get("cast_data_to_json", True):
1✔
326
            post_data = self.cast_to_json(post_data)
1✔
327

328
        error = ""
1✔
329

330
        # extract files from locally saved files and send them with the request
331
        files_to_send = {}
1✔
332
        for field_name, file_name in data.get("files", {}).items():
1✔
333
            try:
1✔
334
                files_to_send[field_name] = (file_name, self.params["files"][file_name])
1✔
335
            except KeyError:
1✔
336
                error = f"{file_name} could not be found in the locally saved files"
1✔
337
                if hasattr(self, "tracker"):
1✔
338
                    IntegrationTrackerStep.objects.create(
1✔
339
                        status_code=0,
340
                        tracker=self.tracker,
341
                        json_response={},
342
                        text_response=error,
343
                        url=self.clean_response(url),
344
                        method=data.get("method", "POST"),
345
                        post_data=json.loads(
346
                            self.clean_response(self.cast_to_json(post_data))
347
                        ),
348
                        headers=json.loads(
349
                            self.clean_response(self.headers(data.get("headers", {})))
350
                        ),
351
                        error=error,
352
                    )
353
                return False, error
1✔
354

355
        response = None
1✔
356
        headers = self.headers(data.get("headers", {}))
1✔
357
        if extra_headers := data.get("extra_headers"):
1✔
358
            if extra_headers == "pritunl":
×
359
                headers.update(
×
360
                    pritunl_headers(data.get("method", "POST"), url, self.extra_args)
361
                )
362
        try:
1✔
363
            response = requests.request(
1✔
364
                data.get("method", "POST"),
365
                url,
366
                headers=headers,
367
                data=post_data,
368
                files=files_to_send,
369
                timeout=120,
370
            )
371
        except (InvalidJSONError, JSONDecodeError):
1✔
372
            error = "JSON is invalid"
×
373

374
        except HTTPError:
1✔
375
            error = "An HTTP error occurred"
×
376

377
        except SSLError:
1✔
378
            error = "An SSL error occurred"
1✔
379

380
        except Timeout:
1✔
381
            error = "The request timed out"
×
382

383
        except (URLRequired, MissingSchema, InvalidSchema, InvalidURL):
1✔
384
            error = "The url is invalid"
1✔
385

386
        except TooManyRedirects:
×
387
            error = "There are too many redirects"
×
388

389
        except InvalidHeader:
×
390
            error = "The header is invalid"
×
391

392
        except:  # noqa E722
×
393
            error = "There was an unexpected error with the request"
×
394

395
        if response is not None and error == "":
1✔
396
            if len(data.get("status_code", [])) and str(
1✔
397
                response.status_code
398
            ) not in data.get("status_code", []):
399
                error = f"Status code ({response.status_code}) not in allowed list ({data.get('status_code')})"
×
400

401
        try:
1✔
402
            json_response = response.json()
1✔
403
            text_response = ""
1✔
404
        except:  # noqa E722
1✔
405
            json_response = {}
1✔
406
            if error:
1✔
407
                text_response = error
1✔
408
            else:
409
                text_response = response.text
×
410

411
        if hasattr(self, "tracker"):
1✔
412
            # TODO: JSON needs to be refactored
413
            try:
1✔
414
                json_payload = json.loads(self.clean_response(json_response))
1✔
415
            except (NativeJSONDecodeError, TypeError):
×
416
                json_payload = self.clean_response(json_response)
×
417

418
            try:
1✔
419
                json_post_payload = json.loads(
1✔
420
                    self.clean_response(self.cast_to_json(post_data))
421
                )
422
            except (NativeJSONDecodeError, TypeError):
×
423
                json_post_payload = self.clean_response(self.cast_to_json(post_data))
×
424

425
            try:
1✔
426
                json_headers_payload = json.loads(self.clean_response(headers))
1✔
427
            except (NativeJSONDecodeError, TypeError):
×
428
                json_headers_payload = self.clean_response(headers)
×
429

430
            IntegrationTrackerStep.objects.create(
1✔
431
                status_code=0 if response is None else response.status_code,
432
                tracker=self.tracker,
433
                json_response=json_payload,
434
                text_response=(
435
                    "Cannot display, could be file"
436
                    if data.get("save_as_file", False)
437
                    else self.clean_response(text_response)
438
                ),
439
                url=self.clean_response(url),
440
                method=data.get("method", "POST"),
441
                post_data=json_post_payload,
442
                headers=json_headers_payload,
443
                expected=self._replace_vars(data.get("expected", "")),
444
                error=self.clean_response(error),
445
            )
446

447
        if error:
1✔
448
            return False, error
1✔
449

450
        return True, response
1✔
451

452
    def _replace_vars(self, text):
1✔
453
        params = {} if not hasattr(self, "params") else self.params
1✔
454
        if self.pk is not None:
1✔
455
            params["redirect_url"] = settings.BASE_URL + reverse_lazy(
1✔
456
                "integrations:oauth-callback", args=[self.id]
457
            )
458
        if hasattr(self, "new_hire") and self.new_hire is not None:
1✔
459
            text = self.new_hire.personalize(text, self.extra_args | params)
1✔
460
            return text
1✔
461
        t = Template(text)
1✔
462
        context = Context(self.extra_args | params)
1✔
463
        text = t.render(context)
1✔
464
        return text
1✔
465

466
    @property
1✔
467
    def has_oauth(self):
1✔
468
        return "oauth" in self.manifest and len(self.manifest.get("oauth", {}))
1✔
469

470
    def headers(self, headers=None):
1✔
471
        if headers is None:
1✔
472
            headers = {}
1✔
473

474
        headers = (
1✔
475
            self.manifest.get("headers", {}).items()
476
            if len(headers) == 0
477
            else headers.items()
478
        )
479
        new_headers = {}
1✔
480
        for key, value in headers:
1✔
481
            # If Basic authentication then swap to base64
482
            if key == "Authorization" and value.startswith("Basic"):
1✔
483
                auth_details = self._replace_vars(value.split(" ", 1)[1])
1✔
484
                value = "Basic " + base64.b64encode(
1✔
485
                    auth_details.encode("ascii")
486
                ).decode("ascii")
487

488
            # Adding an empty string to force to return a string instead of a
489
            # safestring. Ref: https://github.com/psf/requests/issues/6159
490
            new_headers[self._replace_vars(key) + ""] = self._replace_vars(value) + ""
1✔
491
        return new_headers
1✔
492

493
    def user_exists(self, new_hire, save_result=True):
1✔
494
        from users.models import IntegrationUser
1✔
495

496
        if not len(self.manifest.get("exists", [])):
1✔
497
            return None
×
498

499
        # check if user has been created manually
500
        if self.skip_user_provisioning:
1✔
501
            try:
×
502
                user_integration = IntegrationUser.objects.get(
×
503
                    user=new_hire, integration=self
504
                )
505
            except IntegrationUser.DoesNotExist:
×
506
                return False
×
507

508
            return not user_integration.revoked
×
509

510
        self.tracker = IntegrationTracker.objects.create(
1✔
511
            category=IntegrationTracker.Category.EXISTS,
512
            integration=self,
513
            for_user=new_hire,
514
        )
515

516
        self.new_hire = new_hire
1✔
517
        self.has_user_context = new_hire is not None
1✔
518

519
        # Renew token if necessary
520
        if not self.renew_key():
1✔
521
            return
×
522

523
        success, response = self.run_request(self.manifest["exists"])
1✔
524

525
        if not success:
1✔
526
            return None
×
527

528
        user_exists = self.tracker.steps.last().found_expected
1✔
529

530
        if save_result:
1✔
531
            IntegrationUser.objects.update_or_create(
1✔
532
                integration=self, user=new_hire, defaults={"revoked": not user_exists}
533
            )
534

535
        return user_exists
1✔
536

537
    def needs_user_info(self, user):
1✔
538
        if self.skip_user_provisioning:
1✔
539
            return False
1✔
540

541
        # form created from the manifest, this info is always needed to create a new
542
        # account. Check if there is anything that needs to be filled
543
        form = self.manifest.get("form", [])
1✔
544

545
        # extra items that are needed from the integration (often prefilled by admin)
546
        extra_user_info = self.manifest.get("extra_user_info", [])
1✔
547
        needs_more_info = any(
1✔
548
            item["id"] not in user.extra_fields.keys() for item in extra_user_info
549
        )
550

551
        return len(form) > 0 or needs_more_info
1✔
552

553
    def revoke_user(self, user):
1✔
554
        if self.skip_user_provisioning:
×
555
            # should never be triggered
556
            return False, "Cannot revoke manual integration"
×
557

558
        self.new_hire = user
×
559
        self.has_user_context = True
×
560

561
        # Renew token if necessary
562
        if not self.renew_key():
×
563
            return False, "Couldn't renew key"
×
564

565
        revoke_manifest = self.manifest.get("revoke", [])
×
566

567
        # add extra fields directly to params
568
        self.params = self.new_hire.extra_fields
×
569
        self.tracker = IntegrationTracker.objects.create(
×
570
            category=IntegrationTracker.Category.REVOKE,
571
            integration=self if self.pk is not None else None,
572
            for_user=self.new_hire,
573
        )
574

575
        for item in revoke_manifest:
×
576
            success, response = self.run_request(item)
×
577

578
            if not success or not self.tracker.steps.last().found_expected:
×
579
                return False, self.clean_response(response)
×
580

581
        return True, ""
×
582

583
    def renew_key(self):
1✔
584
        # Oauth2 refreshing access token if needed
585
        success = True
1✔
586
        if (
1✔
587
            self.has_oauth
588
            and "expires_in" in self.extra_args.get("oauth", {})
589
            and self.expiring < timezone.now()
590
        ):
591
            success, response = self.run_request(self.manifest["oauth"]["refresh"])
1✔
592

593
            if not success:
1✔
594
                user = self.new_hire if self.has_user_context else None
1✔
595
                Notification.objects.create(
1✔
596
                    notification_type=Notification.Type.FAILED_INTEGRATION,
597
                    extra_text=self.name,
598
                    created_for=user,
599
                    description="Refresh url: " + str(response),
600
                )
601
                return success
1✔
602

603
            self.extra_args["oauth"] |= response.json()
1✔
604
            if "expires_in" in response.json():
1✔
605
                self.expiring = timezone.now() + timedelta(
1✔
606
                    seconds=response.json()["expires_in"]
607
                )
608
            self.save(update_fields=["expiring", "extra_args"])
1✔
609
            if hasattr(self, "tracker"):
1✔
610
                # we need to clean the last step as we now probably got new secret keys
611
                # that need to be masked
612
                last_step = self.tracker.steps.last()
×
613
                last_step.json_response = self.clean_response(last_step.json_response)
×
614
                last_step.save()
×
615

616
        return success
1✔
617

618
    def _check_condition(self, response, condition):
1✔
619
        value = self._replace_vars(condition.get("value"))
1✔
620
        try:
1✔
621
            # first argument will be taken from the response
622
            response_value = get_value_from_notation(
1✔
623
                condition.get("response_notation"), response.json()
624
            )
625
        except KeyError:
×
626
            # we know that the result might not be in the response yet, as we are
627
            # waiting for the correct response, so just respond with an empty string
628
            response_value = ""
×
629
        return value == response_value
1✔
630

631
    def _polling(self, item, response):
1✔
632
        polling = item.get("polling")
1✔
633
        continue_if = item.get("continue_if")
1✔
634
        interval = polling.get("interval")
1✔
635
        amount = polling.get("amount")
1✔
636

637
        got_expected_result = self._check_condition(response, continue_if)
1✔
638
        if got_expected_result:
1✔
639
            return True, response
×
640

641
        tried = 1
1✔
642
        while amount > tried:
1✔
643
            time.sleep(interval)
1✔
644
            success, response = self.run_request(item)
1✔
645
            got_expected_result = self._check_condition(response, continue_if)
1✔
646
            if got_expected_result:
1✔
647
                return True, response
1✔
648
            tried += 1
1✔
649
        # if exceeding the max amounts, then fail
650
        return False, response
1✔
651

652
    def execute(self, new_hire=None, params=None, retry_on_failure=False):
1✔
653
        self.params = params or {}
1✔
654
        self.params["responses"] = []
1✔
655
        self.params["files"] = {}
1✔
656
        self.new_hire = new_hire
1✔
657
        self.has_user_context = new_hire is not None
1✔
658

659
        self.tracker = IntegrationTracker.objects.create(
1✔
660
            category=IntegrationTracker.Category.EXECUTE,
661
            integration=self if self.pk is not None else None,
662
            for_user=self.new_hire,
663
        )
664

665
        if self.has_user_context:
1✔
666
            self.params |= new_hire.extra_fields
1✔
667
            self.new_hire = new_hire
1✔
668

669
        # Renew token if necessary
670
        if not self.renew_key():
1✔
671
            return False, None
×
672

673
        # Add generated secrets
674
        for item in self.manifest.get("initial_data_form", []):
1✔
675
            if "name" in item and item["name"] == "generate":
1✔
676
                self.extra_args[item["id"]] = get_random_string(length=10)
1✔
677

678
        response = None
1✔
679
        # Run all requests
680
        for item in self.manifest["execute"]:
1✔
681
            success, response = self.run_request(item)
1✔
682

683
            # check if we need to poll before continuing
684
            if polling := item.get("polling", False):
1✔
685
                success, response = self._polling(item, response)
1✔
686

687
            # check if we need to block this integration based on condition
688
            if continue_if := item.get("continue_if", False):
1✔
689
                got_expected_result = self._check_condition(response, continue_if)
1✔
690
                if not got_expected_result:
1✔
691
                    response = self.clean_response(response=response)
1✔
692
                    Notification.objects.create(
1✔
693
                        notification_type=Notification.Type.BLOCKED_INTEGRATION,
694
                        extra_text=self.name,
695
                        created_for=new_hire,
696
                        description=f"Execute url ({item['url']}): {response}",
697
                    )
698
                    return False, response
1✔
699

700
            # No need to retry or log when we are importing users
701
            if not success:
1✔
702
                if self.has_user_context:
1✔
703
                    response = self.clean_response(response=response)
1✔
704
                    if polling:
1✔
705
                        response = "Polling timed out: " + response
×
706
                    Notification.objects.create(
1✔
707
                        notification_type=Notification.Type.FAILED_INTEGRATION,
708
                        extra_text=self.name,
709
                        created_for=new_hire,
710
                        description=f"Execute url ({item['url']}): {response}",
711
                    )
712
                if retry_on_failure:
1✔
713
                    # Retry url in one hour
714
                    schedule(
1✔
715
                        "admin.integrations.tasks.retry_integration",
716
                        new_hire.id,
717
                        self.id,
718
                        params,
719
                        name=(
720
                            f"Retrying integration {self.id} for new hire {new_hire.id}"
721
                        ),
722
                        next_run=timezone.now() + timedelta(hours=1),
723
                        schedule_type=Schedule.ONCE,
724
                    )
725
                return False, response
1✔
726

727
            # save if file, so we can reuse later
728
            save_as_file = item.get("save_as_file")
1✔
729
            if save_as_file is not None:
1✔
730
                self.params["files"][save_as_file] = io.BytesIO(response.content)
1✔
731

732
            # save json response temporarily to be reused in other parts
733
            try:
1✔
734
                self.params["responses"].append(response.json())
1✔
735
            except:  # noqa E722
×
736
                # if we save a file, then just append an empty dict
737
                self.params["responses"].append({})
×
738

739
            # store data coming back from response to the user, so we can reuse in other
740
            # integrations
741
            if store_data := item.get("store_data", {}):
1✔
742
                for new_hire_prop, notation_for_response in store_data.items():
1✔
743
                    try:
1✔
744
                        value = get_value_from_notation(
1✔
745
                            notation_for_response, response.json()
746
                        )
747
                    except KeyError:
1✔
748
                        return (
1✔
749
                            False,
750
                            f"Could not store data to new hire: {notation_for_response}"
751
                            f" not found in {self.clean_response(response.json())}",
752
                        )
753

754
                    # save to new hire and to temp var `params` on this model for use in
755
                    # the same integration
756
                    new_hire.extra_fields[new_hire_prop] = value
1✔
757
                    self.params[new_hire_prop] = value
1✔
758
                new_hire.save()
1✔
759

760
        # Run all post requests (notifications)
761
        for item in self.manifest.get("post_execute_notification", []):
1✔
762
            if item["type"] == "email":
1✔
763
                send_email_with_notification(
1✔
764
                    subject=self._replace_vars(item["subject"]),
765
                    message=self._replace_vars(item["message"]),
766
                    to=self._replace_vars(item["to"]),
767
                    notification_type=(
768
                        Notification.Type.SENT_EMAIL_INTEGRATION_NOTIFICATION
769
                    ),
770
                )
771
                return True, None
1✔
772
            else:
773
                try:
×
774
                    client = Client(
×
775
                        settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN
776
                    )
777
                    client.messages.create(
×
778
                        to=new_hire.phone,
779
                        from_=settings.TWILIO_FROM_NUMBER,
780
                        body=self._replace_vars(item["message"]),
781
                    )
782
                except Exception:
×
783
                    Notification.objects.create(
×
784
                        notification_type=(
785
                            Notification.Type.FAILED_TEXT_INTEGRATION_NOTIFICATION
786
                        ),
787
                        extra_text=self.name,
788
                        created_for=new_hire,
789
                    )
790
                    return True, None
×
791

792
        # Succesfully ran integration, add notification only when we are provisioning
793
        # access
794
        if self.has_user_context:
1✔
795
            Notification.objects.create(
1✔
796
                notification_type=Notification.Type.RAN_INTEGRATION,
797
                extra_text=self.name,
798
                created_for=new_hire,
799
            )
800
        return True, response
1✔
801

802
    def config_form(self, data=None):
1✔
803
        if self.skip_user_provisioning:
1✔
804
            from .forms import ManualIntegrationConfigForm
1✔
805

806
            return ManualIntegrationConfigForm(data=data)
1✔
807

808
        from .forms import IntegrationConfigForm
1✔
809

810
        return IntegrationConfigForm(instance=self, data=data)
1✔
811

812
    def clean_response(self, response) -> str:
1✔
813
        if not isinstance(response, str):
1✔
814
            try:
1✔
815
                response = json.dumps(response)
1✔
816
            except (TypeError, ValueError):
1✔
817
                response = str(response)
1✔
818

819
        for name, value in self.extra_args.items():
1✔
820
            if isinstance(value, dict):
1✔
821
                for inner_name, inner_value in value.items():
×
822
                    response = response.replace(
×
823
                        str(inner_value),
824
                        _("***Secret value for %(name)s***")
825
                        % {"name": name + "." + inner_name},
826
                    )
827
            elif value != "":
1✔
828
                response = response.replace(
1✔
829
                    str(value), _("***Secret value for %(name)s***") % {"name": name}
830
                )
831

832
            if name == "Authorization" and value.startswith("Basic"):
1✔
833
                response = response.replace(
×
834
                    base64.b64encode(value.split(" ", 1)[1].encode("ascii")).decode(
835
                        "ascii"
836
                    ),
837
                    "BASE64 ENCODED SECRET",
838
                )
839

840
        return response
1✔
841

842
    objects = IntegrationManager()
1✔
843
    inactive = IntegrationInactiveManager()
1✔
844

845

846
@receiver(post_delete, sender=Integration)
1✔
847
def delete_schedule(sender, instance, **kwargs):
1✔
848
    Schedule.objects.filter(name=instance.schedule_name).delete()
1✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc