| 316 | # TODO(dcramer): ideally superuser_sso would be False by default, but that would require |
| 317 | # a lot of tests changing |
| 318 | def login_as( |
| 319 | self, |
| 320 | user, |
| 321 | organization_id=None, |
| 322 | organization_ids=None, |
| 323 | superuser=False, |
| 324 | staff=False, |
| 325 | staff_sso=True, |
| 326 | superuser_sso=True, |
| 327 | ): |
| 328 | if isinstance(user, OrganizationMember): |
| 329 | with assume_test_silo_mode(SiloMode.CONTROL): |
| 330 | user = User.objects.get(id=user.user_id) |
| 331 | |
| 332 | user.backend = settings.AUTHENTICATION_BACKENDS[0] |
| 333 | |
| 334 | request = self.make_request() |
| 335 | with assume_test_silo_mode(SiloMode.CONTROL): |
| 336 | login(request, user) |
| 337 | request.user = user |
| 338 | |
| 339 | if organization_ids is None: |
| 340 | organization_ids = set() |
| 341 | else: |
| 342 | organization_ids = set(organization_ids) |
| 343 | if superuser and superuser_sso is not False: |
| 344 | if SUPERUSER_ORG_ID: |
| 345 | organization_ids.add(SUPERUSER_ORG_ID) |
| 346 | if staff and staff_sso is not False: |
| 347 | if STAFF_ORG_ID: |
| 348 | organization_ids.add(SUPERUSER_ORG_ID) |
| 349 | if organization_id: |
| 350 | organization_ids.add(organization_id) |
| 351 | |
| 352 | # TODO(dcramer): ideally this would get abstracted |
| 353 | if organization_ids: |
| 354 | for o in organization_ids: |
| 355 | sso_session = SsoSession.create(o) |
| 356 | self.session[sso_session.session_key] = sso_session.to_dict() |
| 357 | |
| 358 | # logging in implicitly binds superuser, but for test cases we |
| 359 | # want that action to be explicit to avoid accidentally testing |
| 360 | # superuser-only code |
| 361 | if not superuser: |
| 362 | # XXX(dcramer): we're calling the internal method to avoid logging |
| 363 | request.superuser._set_logged_out() |
| 364 | elif request.user.is_superuser and superuser: |
| 365 | request.superuser.set_logged_in(request.user) |
| 366 | # XXX(dcramer): awful hack to ensure future attempts to instantiate |
| 367 | # the Superuser object are successful |
| 368 | self.save_cookie( |
| 369 | name=SU_COOKIE_NAME, |
| 370 | value=signing.get_cookie_signer(salt=SU_COOKIE_NAME + SU_COOKIE_SALT).sign( |
| 371 | request.superuser.token |
| 372 | ), |
| 373 | max_age=None, |
| 374 | path=SU_COOKIE_PATH, |
| 375 | domain=SU_COOKIE_DOMAIN, |