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

chiefonboarding / ChiefOnboarding / 17811991712

17 Sep 2025 10:11PM UTC coverage: 89.6% (-0.1%) from 89.705%
17811991712

push

github

web-flow
Implement allauth for authentication (#387)

6780 of 7567 relevant lines covered (89.6%)

0.9 hits per line

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

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

48

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

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

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

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

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

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

76

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

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

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

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

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

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

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

120

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

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

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

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

157

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

162

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

316
        return value
1✔
317

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

327
        error = ""
1✔
328

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

354
        response = None
1✔
355
        try:
1✔
356
            response = requests.request(
1✔
357
                data.get("method", "POST"),
358
                url,
359
                headers=self.headers(data.get("headers", {})),
360
                data=post_data,
361
                files=files_to_send,
362
                timeout=120,
363
            )
364
        except (InvalidJSONError, JSONDecodeError):
1✔
365
            error = "JSON is invalid"
×
366

367
        except HTTPError:
1✔
368
            error = "An HTTP error occurred"
×
369

370
        except SSLError:
1✔
371
            error = "An SSL error occurred"
×
372

373
        except Timeout:
1✔
374
            error = "The request timed out"
×
375

376
        except (URLRequired, MissingSchema, InvalidSchema, InvalidURL):
1✔
377
            error = "The url is invalid"
1✔
378

379
        except TooManyRedirects:
×
380
            error = "There are too many redirects"
×
381

382
        except InvalidHeader:
×
383
            error = "The header is invalid"
×
384

385
        except:  # noqa E722
×
386
            error = "There was an unexpected error with the request"
×
387

388
        if response is not None and error == "":
1✔
389
            if len(data.get("status_code", [])) and str(
1✔
390
                response.status_code
391
            ) not in data.get("status_code", []):
392
                error = f"Status code ({response.status_code}) not in allowed list ({data.get('status_code')})"
×
393

394
        try:
1✔
395
            json_response = response.json()
1✔
396
            text_response = ""
1✔
397
        except:  # noqa E722
1✔
398
            json_response = {}
1✔
399
            if error:
1✔
400
                text_response = error
1✔
401
            else:
402
                text_response = response.text
1✔
403

404
        if hasattr(self, "tracker"):
1✔
405
            # TODO: JSON needs to be refactored
406
            try:
1✔
407
                json_payload = json.loads(self.clean_response(json_response))
1✔
408
            except (NativeJSONDecodeError, TypeError):
×
409
                json_payload = self.clean_response(json_response)
×
410

411
            try:
1✔
412
                json_post_payload = json.loads(
1✔
413
                    self.clean_response(self.cast_to_json(post_data))
414
                )
415
            except (NativeJSONDecodeError, TypeError):
×
416
                json_post_payload = self.clean_response(self.cast_to_json(post_data))
×
417

418
            try:
1✔
419
                json_headers_payload = json.loads(
1✔
420
                    self.clean_response(self.headers(data.get("headers", {})))
421
                )
422
            except (NativeJSONDecodeError, TypeError):
×
423
                json_headers_payload = self.clean_response(
×
424
                    self.headers(data.get("headers", {}))
425
                )
426

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

444
        if error:
1✔
445
            return False, error
1✔
446

447
        return True, response
1✔
448

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

463
    @property
1✔
464
    def has_oauth(self):
1✔
465
        return "oauth" in self.manifest and len(self.manifest.get("oauth", {}))
1✔
466

467
    def headers(self, headers=None):
1✔
468
        if headers is None:
1✔
469
            headers = {}
1✔
470

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

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

490
    def user_exists(self, new_hire, save_result=True):
1✔
491
        from users.models import IntegrationUser
1✔
492

493
        if not len(self.manifest.get("exists", [])):
1✔
494
            return None
×
495

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

505
            return not user_integration.revoked
×
506

507
        self.tracker = IntegrationTracker.objects.create(
1✔
508
            category=IntegrationTracker.Category.EXISTS,
509
            integration=self,
510
            for_user=new_hire,
511
        )
512

513
        self.new_hire = new_hire
1✔
514
        self.has_user_context = new_hire is not None
1✔
515

516
        # Renew token if necessary
517
        if not self.renew_key():
1✔
518
            return
×
519

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

522
        if not success:
1✔
523
            return None
×
524

525
        user_exists = self.tracker.steps.last().found_expected
1✔
526

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

532
        return user_exists
1✔
533

534
    def needs_user_info(self, user):
1✔
535
        if self.skip_user_provisioning:
1✔
536
            return False
1✔
537

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

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

548
        return len(form) > 0 or needs_more_info
1✔
549

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

555
        self.new_hire = user
×
556
        self.has_user_context = True
×
557

558
        # Renew token if necessary
559
        if not self.renew_key():
×
560
            return False, "Couldn't renew key"
×
561

562
        revoke_manifest = self.manifest.get("revoke", [])
×
563

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

572
        for item in revoke_manifest:
×
573
            success, response = self.run_request(item)
×
574

575
            if not success or not self.tracker.steps.last().found_expected:
×
576
                return False, self.clean_response(response)
×
577

578
        return True, ""
×
579

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

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

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

613
        return success
1✔
614

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

628
    def _polling(self, item, response):
1✔
629
        polling = item.get("polling")
1✔
630
        continue_if = item.get("continue_if")
1✔
631
        interval = polling.get("interval")
1✔
632
        amount = polling.get("amount")
1✔
633

634
        got_expected_result = self._check_condition(response, continue_if)
1✔
635
        if got_expected_result:
1✔
636
            return True, response
×
637

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

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

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

662
        if self.has_user_context:
1✔
663
            self.params |= new_hire.extra_fields
1✔
664
            self.new_hire = new_hire
1✔
665

666
        # Renew token if necessary
667
        if not self.renew_key():
1✔
668
            return False, None
×
669

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

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

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

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

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

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

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

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

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

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

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

799
    def config_form(self, data=None):
1✔
800
        if self.skip_user_provisioning:
1✔
801
            from .forms import ManualIntegrationConfigForm
1✔
802

803
            return ManualIntegrationConfigForm(data=data)
1✔
804

805
        from .forms import IntegrationConfigForm
1✔
806

807
        return IntegrationConfigForm(instance=self, data=data)
1✔
808

809
    def clean_response(self, response) -> str:
1✔
810
        if isinstance(response, dict):
1✔
811
            try:
1✔
812
                response = json.dumps(response)
1✔
813
            except ValueError:
×
814
                response = str(response)
×
815

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

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

837
        return response
1✔
838

839
    objects = IntegrationManager()
1✔
840
    inactive = IntegrationInactiveManager()
1✔
841

842

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