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

chiefonboarding / ChiefOnboarding / 22228267986

20 Feb 2026 02:38PM UTC coverage: 90.513% (-0.06%) from 90.569%
22228267986

Pull #621

github

web-flow
Merge 5c567b45d into 6eb818dff
Pull Request #621: Pritunl compatibility

8186 of 9044 relevant lines covered (90.51%)

0.91 hits per line

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

83.48
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 == "prituln":
×
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(
1✔
427
                    self.clean_response(headers)
428
                )
429
            except (NativeJSONDecodeError, TypeError):
×
430
                json_headers_payload = self.clean_response(
×
431
                    headers
432
                )
433

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

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

454
        return True, response
1✔
455

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

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

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

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

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

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

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

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

512
            return not user_integration.revoked
×
513

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

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

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

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

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

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

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

539
        return user_exists
1✔
540

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

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

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

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

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

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

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

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

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

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

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

585
        return True, ""
×
586

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

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

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

620
        return success
1✔
621

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

810
            return ManualIntegrationConfigForm(data=data)
1✔
811

812
        from .forms import IntegrationConfigForm
1✔
813

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

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

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

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

844
        return response
1✔
845

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

849

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