backend.py 1.25 KB
Newer Older
Sharad Heft's avatar
Sharad Heft committed
1 2 3 4 5 6 7 8 9 10 11 12
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.contrib.auth.backends import ModelBackend
from django.conf import settings
from django.db import transaction


class TESTOAuth2Backend(ModelBackend):
    def authenticate(self, id=None, username=None, **profile):
        if id is None or username is None:
            return None

13
        user, _ = get_user_model().objects.get_or_create(
Sharad Heft's avatar
Sharad Heft committed
14 15 16 17
            pk=id,
            username=username
        )

18 19
        if getattr(settings, 'TEST_OAUTH_CREATE_GROUPS', False):
            self._do_create_groups(user, profile.get('groups', []))
Sharad Heft's avatar
Sharad Heft committed
20 21 22 23

        return user

    def get_user(self, user_id):
24 25
        UserModel = get_user_model()

Sharad Heft's avatar
Sharad Heft committed
26 27 28 29
        try:
            return UserModel.objects.get(pk=user_id)
        except UserModel.DoesNotExist:
            return None
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46

    @transaction.atomic
    def _do_create_groups(self, user, groups):
        user.groups.clear()

        for g in groups:
            group, _ = Group.objects.get_or_create(
                id=g['id'], name=g['name']
            )

            user.groups.add(group)

            # Adding carveout for Server Admin group
            if g['name'] == "Server Admin":
                user.is_staff = True

        user.save()