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

chiefonboarding / ChiefOnboarding / 22333279969

24 Feb 2026 01:56AM UTC coverage: 90.623% (+0.05%) from 90.569%
22333279969

push

github

web-flow
Pritunl headers compatibility (#621)

8205 of 9054 relevant lines covered (90.62%)

0.91 hits per line

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

84.43
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.exceptions import PritunlMissingCredentialsError
1✔
39
from admin.integrations.helpers.pritunl import pritunl_headers
1✔
40
from admin.integrations.serializers import (
1✔
41
    SyncUsersManifestSerializer,
42
    WebhookManifestSerializer,
43
)
44
from admin.integrations.utils import get_value_from_notation
1✔
45
from misc.fernet_fields import EncryptedTextField
1✔
46
from misc.fields import EncryptedJSONField
1✔
47
from organization.models import Notification
1✔
48
from organization.utils import has_manager_or_buddy_tags, send_email_with_notification
1✔
49

50

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

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

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

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

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

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

78

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

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

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

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

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

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

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

122

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

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

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

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

159

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

164

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

318
        return value
1✔
319

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

329
        error = ""
1✔
330

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

356
        response = None
1✔
357
        headers = self.headers(data.get("headers", {}))
1✔
358
        try:
1✔
359
            if data.get("extra_headers", "") == "pritunl":
1✔
360
                headers.update(
1✔
361
                    pritunl_headers(data.get("method", "POST"), url, self.extra_args)
362
                )
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 PritunlMissingCredentialsError as e:
1✔
372
            error = str(e)
1✔
373

374
        except (InvalidJSONError, JSONDecodeError):
1✔
375
            error = "JSON is invalid"
×
376

377
        except HTTPError:
1✔
378
            error = "An HTTP error occurred"
×
379

380
        except SSLError:
1✔
381
            error = "An SSL error occurred"
1✔
382

383
        except Timeout:
1✔
384
            error = "The request timed out"
×
385

386
        except (URLRequired, MissingSchema, InvalidSchema, InvalidURL):
1✔
387
            error = "The url is invalid"
1✔
388

389
        except TooManyRedirects:
×
390
            error = "There are too many redirects"
×
391

392
        except InvalidHeader:
×
393
            error = "The header is invalid"
×
394

395
        except:  # noqa E722
×
396
            error = "There was an unexpected error with the request"
×
397

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

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

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

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

428
            try:
1✔
429
                json_headers_payload = json.loads(self.clean_response(headers))
1✔
430
            except (NativeJSONDecodeError, TypeError):
×
431
                json_headers_payload = self.clean_response(headers)
×
432

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

450
        if error:
1✔
451
            return False, error
1✔
452

453
        return True, response
1✔
454

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

469
    @property
1✔
470
    def has_oauth(self):
1✔
471
        return "oauth" in self.manifest and len(self.manifest.get("oauth", {}))
1✔
472

473
    def headers(self, headers=None):
1✔
474
        if headers is None:
1✔
475
            headers = {}
1✔
476

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

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

496
    def user_exists(self, new_hire, save_result=True):
1✔
497
        from users.models import IntegrationUser
1✔
498

499
        if not len(self.manifest.get("exists", [])):
1✔
500
            return None
×
501

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

511
            return not user_integration.revoked
×
512

513
        self.tracker = IntegrationTracker.objects.create(
1✔
514
            category=IntegrationTracker.Category.EXISTS,
515
            integration=self,
516
            for_user=new_hire,
517
        )
518

519
        self.new_hire = new_hire
1✔
520
        self.has_user_context = new_hire is not None
1✔
521

522
        # Renew token if necessary
523
        if not self.renew_key():
1✔
524
            return
×
525

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

528
        if not success:
1✔
529
            return None
×
530

531
        user_exists = self.tracker.steps.last().found_expected
1✔
532

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

538
        return user_exists
1✔
539

540
    def needs_user_info(self, user):
1✔
541
        if self.skip_user_provisioning:
1✔
542
            return False
1✔
543

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

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

554
        return len(form) > 0 or needs_more_info
1✔
555

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

561
        self.new_hire = user
×
562
        self.has_user_context = True
×
563

564
        # Renew token if necessary
565
        if not self.renew_key():
×
566
            return False, "Couldn't renew key"
×
567

568
        revoke_manifest = self.manifest.get("revoke", [])
×
569

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

578
        for item in revoke_manifest:
×
579
            success, response = self.run_request(item)
×
580

581
            if not success or not self.tracker.steps.last().found_expected:
×
582
                return False, self.clean_response(response)
×
583

584
        return True, ""
×
585

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

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

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

619
        return success
1✔
620

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

634
    def _polling(self, item, response):
1✔
635
        polling = item.get("polling")
1✔
636
        continue_if = item.get("continue_if")
1✔
637
        interval = polling.get("interval")
1✔
638
        amount = polling.get("amount")
1✔
639

640
        got_expected_result = self._check_condition(response, continue_if)
1✔
641
        if got_expected_result:
1✔
642
            return True, response
×
643

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

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

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

668
        if self.has_user_context:
1✔
669
            self.params |= new_hire.extra_fields
1✔
670
            self.new_hire = new_hire
1✔
671

672
        # Renew token if necessary
673
        if not self.renew_key():
1✔
674
            return False, None
×
675

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

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

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

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

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

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

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

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

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

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

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

805
    def config_form(self, data=None):
1✔
806
        if self.skip_user_provisioning:
1✔
807
            from .forms import ManualIntegrationConfigForm
1✔
808

809
            return ManualIntegrationConfigForm(data=data)
1✔
810

811
        from .forms import IntegrationConfigForm
1✔
812

813
        return IntegrationConfigForm(instance=self, data=data)
1✔
814

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

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

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

843
        return response
1✔
844

845
    objects = IntegrationManager()
1✔
846
    inactive = IntegrationInactiveManager()
1✔
847

848

849
@receiver(post_delete, sender=Integration)
1✔
850
def delete_schedule(sender, instance, **kwargs):
1✔
851
    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