How to use the kolibri.core.auth.models.FacilityUser.objects function in kolibri

To help you get started, we’ve selected a few kolibri examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github learningequality / kolibri / kolibri / core / auth / management / commands / fullfacilitysync.py View on Github external
def create_superuser_and_provision_device(self, username, dataset_id):
        # Prompt user to pick a superuser if one does not currently exist
        while not DevicePermissions.objects.filter(is_superuser=True).exists():
            # specify username of account that will become a superuser
            if not username:
                username = input(
                    "Please enter username of account that will become the superuser on this device: "
                )
            if not FacilityUser.objects.filter(username=username).exists():
                self.stderr.write(
                    "User with username {} does not exist".format(username)
                )
                username = None
                continue

            # make the user with the given credentials, a superuser for this device
            user = FacilityUser.objects.get(username=username, dataset_id=dataset_id)

            # create permissions for the authorized user
            DevicePermissions.objects.update_or_create(
                user=user, defaults={"is_superuser": True, "can_manage_content": True}
            )

        # if device has not been provisioned, set it up
        if not device_provisioned():
github learningequality / kolibri / kolibri / core / auth / api.py View on Github external
member_of = ModelChoiceFilter(
        method="filter_member_of", queryset=Collection.objects.all()
    )

    def filter_member_of(self, queryset, name, value):
        return queryset.filter(Q(memberships__collection=value) | Q(facility=value))

    class Meta:
        model = FacilityUser
        fields = ["member_of"]


class FacilityUserViewSet(ValuesViewset):
    permission_classes = (KolibriAuthPermissions,)
    filter_backends = (KolibriAuthPermissionsFilter, DjangoFilterBackend)
    queryset = FacilityUser.objects.all()
    serializer_class = FacilityUserSerializer
    filter_class = FacilityUserFilter

    values = (
        "id",
        "username",
        "full_name",
        "facility",
        "roles__kind",
        "roles__collection",
        "roles__id",
        "devicepermissions__is_superuser",
        "id_number",
        "gender",
        "birth_year",
    )
github learningequality / kolibri / kolibri / core / auth / management / commands / deleteuser.py View on Github external
def handle(self, *args, **options):
        try:
            if options["facility"]:
                user = FacilityUser.objects.get(
                    username=options["username"], facility_id=options["facility"]
                )
            else:
                user = FacilityUser.objects.get(username=options["username"])
        except FacilityUser.DoesNotExist:
            raise CommandError(
                "User with username `{username}` does not exist.".format(
                    username=options["username"]
                )
            )
        except FacilityUser.MultipleObjectsReturned:
            raise CommandError(
                (
                    "There is more than one user on this device with the username `{username}`. "
                    "Please specify the facility ID for this user.".format(
                        username=options["username"]
                    )
                )
            )
github learningequality / kolibri / kolibri / core / auth / management / utils.py View on Github external
def create_superuser_and_provision_device(username, dataset_id, noninteractive=False):
    facility = Facility.objects.get(dataset_id=dataset_id)
    # if device has not been provisioned, set it up
    if not device_provisioned():
        provision_device(default_facility=facility)

    # Prompt user to pick a superuser if one does not currently exist
    while not DevicePermissions.objects.filter(is_superuser=True).exists():
        # specify username of account that will become a superuser
        if not username:
            if (
                noninteractive
            ):  # we don't want to setup a device without a superuser, so create a temporary one
                superuser = FacilityUser.objects.create(
                    username="superuser", facility=facility
                )
                superuser.set_password("password")
                superuser.save()
                DevicePermissions.objects.create(
                    user=superuser, is_superuser=True, can_manage_content=True
                )
                print(
                    "Temporary superuser with username: `superuser` and password: `password` created"
                )
                return
            username = input(
                "Please enter username of account that will become the superuser on this device: "
            )
        if not FacilityUser.objects.filter(username=username).exists():
            print(
github learningequality / kolibri / kolibri / plugins / coach / class_summary_api.py View on Github external
def retrieve(self, request, pk):
        classroom = get_object_or_404(auth_models.Classroom, id=pk)
        query_learners = FacilityUser.objects.filter(memberships__collection=classroom)
        query_lesson = Lesson.objects.filter(collection=pk)
        query_exams = Exam.objects.filter(collection=pk)
        query_exam_logs = logger_models.ExamLog.objects.filter(
            exam__in=query_exams
        ).order_by()

        lesson_data = serialize_lessons(query_lesson)
        exam_data = serialize_exams(query_exams)

        individual_learners_group_ids = AdHocGroup.objects.filter(
            parent=classroom
        ).values_list("id", flat=True)

        # filter classes out of exam assignments
        for exam in exam_data:
            exam["groups"] = [
github learningequality / kolibri / kolibri / core / device / serializers.py View on Github external
from kolibri.core.auth.constants.facility_presets import choices
from kolibri.core.auth.constants.facility_presets import mappings
from kolibri.core.auth.constants.role_kinds import ADMIN
from kolibri.core.auth.models import Facility
from kolibri.core.auth.models import FacilityUser
from kolibri.core.auth.serializers import FacilitySerializer
from kolibri.core.auth.serializers import FacilityUserSerializer
from kolibri.core.device.models import DevicePermissions
from kolibri.core.device.models import DeviceSettings
from kolibri.core.device.utils import provision_device


class DevicePermissionsSerializer(serializers.ModelSerializer):

    user = serializers.PrimaryKeyRelatedField(queryset=FacilityUser.objects.all())

    class Meta:
        model = DevicePermissions
        fields = ("user", "is_superuser", "can_manage_content")


class NoFacilityFacilityUserSerializer(FacilityUserSerializer):
    class Meta:
        model = FacilityUser
        fields = ("id", "username", "full_name", "password", "birth_year", "gender")

    def validate(self, attrs):
        return attrs


class DeviceSerializerMixin(object):
github learningequality / kolibri / kolibri / core / analytics / utils.py View on Github external
def extract_facility_statistics(facility):

    dataset_id = facility.dataset_id

    settings = {
        name: getattr(facility.dataset, name)
        for name in facility_settings
        if hasattr(facility.dataset, name)
    }

    settings.update(allow_guest_access=allow_guest_access())

    learners = FacilityUser.objects.filter(dataset_id=dataset_id).exclude(
        roles__kind__in=[role_kinds.ADMIN, role_kinds.COACH]
    )
    coaches = FacilityUser.objects.filter(
        dataset_id=dataset_id, roles__kind__in=[role_kinds.ADMIN, role_kinds.COACH]
    )

    usersessions = UserSessionLog.objects.filter(dataset_id=dataset_id)
    contsessions = ContentSessionLog.objects.filter(
        dataset_id=dataset_id, time_spent__lt=3600 * 2
    )

    # the aggregates below are used to calculate the first and most recent times this device was used
    usersess_agg = usersessions.filter(
        start_timestamp__gt=datetime.datetime(2016, 1, 1)
    ).aggregate(first=Min("start_timestamp"), last=Max("last_interaction_timestamp"))
    contsess_agg = contsessions.filter(
        start_timestamp__gt=datetime.datetime(2016, 1, 1)
    ).aggregate(first=Min("start_timestamp"), last=Max("end_timestamp"))
github learningequality / kolibri / kolibri / core / logger / utils / user_data.py View on Github external
classroom = options["classroom"]
    channels = options["channels"]
    num_exams = options["exams"]
    facility = options["facility"]
    now = options["now"]

    if not channels:
        return

    coaches = facility.get_coaches()
    if coaches:
        coach = random.choice(coaches)
    else:
        members = facility.get_members()
        if not members:
            coach = FacilityUser.objects.create(username="coach", facility=facility)
            coach.set_password("password")
            coach.save()
        else:
            coach = random.choice(members)
            facility.add_coach(coach)

    for count in range(num_exams):

        # exam questions can come from different channels
        exercise_content = ContentNode.objects.filter(
            kind=content_kinds.EXERCISE
        ).filter(~Q(assessmentmetadata__assessment_item_ids=[]))
        # don't add more than 3 resources per:
        n_content_items = min(exercise_content.count(), 3)
        exam_content = []
        content_ids = []
github learningequality / kolibri / kolibri / core / auth / backends.py View on Github external
def get_user(self, user_id):
        """
        Gets a user. Auth backends are required to implement this.

        :param user_id: A FacilityUser pk
        :return: A FacilityUser instance if a BaseUser with that pk is found, else None.
        """
        try:
            return FacilityUser.objects.get(pk=user_id)
        except FacilityUser.DoesNotExist:
            return None