Exemple #1
0
 def put(self, request, groupname):
     group = self.get_group(groupname)
     update = {"users": request.data}  # spec wants list as request body
     serializer = GroupSerializer(group, update, partial=True)
     if serializer.is_valid():
         serializer.save()
         return Response(status=status.HTTP_200_OK)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemple #2
0
 def put(self, request, groupname):
     group = self.get_group(groupname)
     update = {"users": request.data}  # spec wants list as request body
     serializer = GroupSerializer(group, update, partial=True)
     if serializer.is_valid():
         serializer.save()
         return Response(status=status.HTTP_200_OK)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemple #3
0
class ProfileRetrieveUpdateSerializer(serializers.ModelSerializer):
    countries_available = SimpleCountrySerializer(many=True, read_only=True)
    supervisor = serializers.CharField(read_only=True)
    groups = GroupSerializer(source="user.groups", read_only=True, many=True)
    supervisees = serializers.PrimaryKeyRelatedField(source='user.supervisee',
                                                     many=True,
                                                     read_only=True)
    name = serializers.CharField(source='user.get_full_name', read_only=True)
    t2f = T2FUserDataSerializer(source='user')
    last_login = serializers.CharField(source='user.last_login',
                                       read_only=True)
    is_superuser = serializers.CharField(source='user.is_superuser',
                                         read_only=True)
    username = serializers.CharField(source='user.username', read_only=True)
    first_name = serializers.CharField(source='user.first_name',
                                       read_only=True)
    last_name = serializers.CharField(source='user.last_name', read_only=True)
    email = serializers.CharField(source='user.email', read_only=True)
    is_staff = serializers.CharField(source='user.is_staff', read_only=True)
    is_active = serializers.CharField(source='user.is_active', read_only=True)
    country = CountrySerializer(read_only=True)
    show_ap = serializers.SerializerMethodField()

    class Meta:
        model = UserProfile
        exclude = ('id', )

    # TODO remove once feature gating is in place.
    def get_show_ap(self, obj):
        """If user is within one of the allowed countries then
        show_ap is True, otherwise False
        """
        if obj.country.name in AP_ALLOWED_COUNTRIES:
            return True
        return False
    def test_group_query(self, process_mock):
        all_groups = [{
            "name":
            "certusers",
            "gid":
            "29",
            "members":
            ["root", "_jabber", "_postfix", "_cyrus", "_calendar", "_dovecot"],
        }, {
            "name": "_postdrop",
            "gid": "28",
            "members": []
        }]
        process_mock.return_value = all_groups
        url = '{}?name=certusers&gid=29'.format(reverse('groups-query'))
        response = self.client.get(url)
        group = get_groups(settings.GRP_FILEPATH)['29']
        serializer = GroupSerializer(instance=[group], many=True)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data, serializer.data)

        url = '{}?name=blah'.format(reverse('groups-query'))
        response = self.client.get(url)
        # user with name blah doesn't exist, so 404
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
        self.assertEqual(response.data['detail'], "Group not found")
Exemple #5
0
    def retrieve(self, request, pk=None):
        try:
            group = self.all_groups[pk]
        except KeyError:
            raise NotFound(detail="Group not found", code=404)

        serializer = GroupSerializer(instance=group)
        return Response(serializer.data)
Exemple #6
0
    def create(cls, root, info, **kwargs):
        """
        @description: 创建教师
        @param {type} 
        @return: 
        """
        data = kwargs.get("input")
        profile_data = data.pop("profile", None)
        if profile_data is None:
            return cls.get_errors("没有传入profile!")
        if profile_data.get("name", None) is None:
            return cls.get_errors("没有传入name!")
        tg = get_Object_or_None(Group, name="教师")
        if not tg:
            return cls.get_errors("没有教师组!")

        # 创建用户
        user_ser = UserSerializer(data=data)
        ok, user = cls.save(user_ser, root, info)
        if not ok:
            return cls.get_errors(user)

        profile_data["user"] = user.id
        profile_data["creator"] = info.context.user.id
        # 创建对应profile
        profile_ser = UserProfileSerializer(data=profile_data)
        ok, profile = cls.save(profile_ser, root, info)
        if not ok:
            user.delete()
            return cls.get_errors(profile)
        # 创建对应组
        group_ser = GroupSerializer(data={"name": profile_data.get("name")})
        ok, group = cls.save(group_ser, root, info)
        if not ok:
            profile.delete()
            user.delete()
            return cls.get_errors(group)

        # 创建对应组profile
        gp_ser = GroupProfileSerializer(
            data={
                "creator": info.context.user.id,
                "group": group.id,
                "parent_group": tg.id,
            })
        ok, gp = cls.save(gp_ser, root, info)
        if not ok:
            profile.delete()
            user.delete()
            group.delete()
            return cls.get_errors(gp)

        user.groups.add(group)
        user.groups.add(tg)

        return cls.perform_mutate(user, info)
Exemple #7
0
class EventSerializer(serializers.ModelSerializer):
    group = GroupSerializer(many=True)
    starting_time = serializers.DateTimeField(source='timeslot.starting_time')
    ending_time = serializers.DateTimeField(source='timeslot.ending_time')
    class_info = ClassEventSerializer(source='current_class')
    room = RoomSerializer()

    class Meta:
        model = Event
        fields = ("id", "class_info", "room", "group", "starting_time", "ending_time", "date")
Exemple #8
0
    def update(cls, root, info, **kwargs):
        data = kwargs.pop("input")
        profile_data = data.pop("profile", {})
        profile_data["updater"] = info.context.user.id

        pk = data.pop("id")
        group = get_Object_or_None(Group, pk=pk)
        if not group:
            return cls.get_errors([
                ErrorType(
                    field="id",
                    messages=[
                        "A {} obj with id: {} do not exist".format(
                            "Group", pk)
                    ],
                )
            ])

        group_ser = GroupSerializer(instance=group, data=data, partial=True)
        if not group_ser.is_valid():
            errors = [
                ErrorType(field=key, messages=value)
                for key, value in group_ser.errors.items()
            ]
            return cls.get_errors(errors)

        profile = GroupProfile.objects.filter(group_id=group.id)
        profile_ser = GroupProfileSerializer(instance=profile,
                                             data=profile_data,
                                             partial=True)
        ok, profile = cls.save(profile_ser, root, info)
        if not ok:
            return cls.get_errors(profile)

        group = group_ser.save()
        profile_ser.save()

        return cls.perform_mutate(group, info)
Exemple #9
0
    def create(cls, root, info, **kwargs):
        data = kwargs.get("input")
        profile_data = data.pop("profile", {})
        profile_data["creator"] = info.context.user.id

        group_ser = GroupSerializer(data=data)
        ok, group = cls.save(group_ser, root, info)
        if not ok:
            return cls.get_errors(group)

        profile_data["group"] = group.id
        profile_ser = GroupProfileSerializer(data=profile_data)
        ok, profile = cls.save(profile_ser, root, info)
        if not ok:
            group.delete()
            return cls.get_errors(profile)

        return cls.perform_mutate(group, info)
Exemple #10
0
    def validate(self, attrs):
        code = attrs.get('code')
        result = self._credentials_validation(code)
        user = self._get_or_create_user(result['openid'],
                                        result['session_key'])
        r = urlopen(attrs.get('avatarUrl'))
        user.avatar.save("{}_{}.jpg".format(user.id, int(time.time())),
                         File(BytesIO(r.read())))
        attrs['username'] = result['openid']
        attrs['password'] = result['openid']
        self._update_userinfo(user, attrs)
        credentials = {
            self.username_field: attrs.get(self.username_field),
            'password': attrs.get('password')
        }

        if all(credentials.values()):
            user = authenticate(**credentials)
            if user:
                if not user.is_active:
                    msg = _('账户未激活')
                    raise serializers.ValidationError(msg)

                payload = jwt_payload_handler(user)
                data_dict = {
                    'token': jwt_encode_handler(payload),
                    'name': user.name if user.name else user.username,
                    'groups': GroupSerializer(user.groups.all(),
                                              many=True).data,
                    'permissions': User.get_all_permissions(user)
                }
                data_dict.update(
                    UserDetailSerializer(user, context=self.context).data)
                attrs.update(data_dict)
                return attrs
            else:
                msg = _('账号或密码不正确')
                raise serializers.ValidationError(msg)
        else:
            msg = _('必须包含用户信息或者code')
            raise serializers.ValidationError(msg)
Exemple #11
0
    def query(self, request):
        groupname = request.query_params.get('name', None)
        gid = request.query_params.get('gid', None)
        members = request.query_params.getlist('member', None)

        filterset = self.all_groups.values()

        if groupname is not None:
            filterset = [obj for obj in filterset if obj.name == groupname]

        if gid is not None:
            filterset = [obj for obj in filterset if obj.gid == gid]

        if members is not None:
            filterset = [obj for obj in filterset if all(member_name in obj.members for member_name in members)]

        if not filterset:
            raise NotFound(detail="Group not found", code=404)

        serializer = GroupSerializer(instance=filterset, many=True)
        return Response(serializer.data)
    def test_group_retrieve(self, process_mock):
        all_groups = [{
            "name":
            "certusers",
            "gid":
            "29",
            "members":
            ["root", "_jabber", "_postfix", "_cyrus", "_calendar", "_dovecot"],
        }, {
            "name": "_postdrop",
            "gid": "28",
            "members": []
        }]
        process_mock.return_value = all_groups
        pk = '28'
        url = reverse('groups-detail', kwargs={'pk': pk})

        response = self.client.get(url)
        group = get_groups(settings.GRP_FILEPATH)[pk]
        serializer = GroupSerializer(instance=group)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data, serializer.data)
    def test_group_list(self, process_mock):
        all_groups = [{
            "name":
            "certusers",
            "gid":
            "29",
            "members":
            ["root", "_jabber", "_postfix", "_cyrus", "_calendar", "_dovecot"],
        }, {
            "name": "_postdrop",
            "gid": "28",
            "members": []
        }]

        process_mock.return_value = all_groups
        url = reverse('groups-list')
        response = self.client.get(url)
        serializer = GroupSerializer(instance=get_groups(
            settings.GRP_FILEPATH).values(),
                                     many=True)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data, serializer.data)
Exemple #14
0
    def test_user_groups(self, process_pwd_mock, process_grp_mock):
        all_users = [{
            'name': '_appowner',
            'uid': '87',
            'gid': '87',
            'comment': 'Application Owner',
            'home': '/var/empty',
            'shell': '/usr/bin/false'
        }, {
            'name': '_ard',
            'uid': '67',
            'gid': '67',
            'comment': 'Apple Remote Desktop',
            'home': '/var/empty',
            'shell': '/usr/bin/false'
        }]
        all_groups = [
            {
                "name":
                "certusers",
                "gid":
                "29",
                "members": [
                    "root", "_jabber", "_postfix", "_cyrus", "_calendar",
                    "_appowner"
                ],
            },
        ]
        process_pwd_mock.return_value = all_users
        process_grp_mock.return_value = all_groups
        pk = '87'
        url = reverse('users-groups', kwargs={'pk': pk})

        response = self.client.get(url)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        groups = get_groups(settings.GRP_FILEPATH).values()
        serializer = GroupSerializer(instance=groups, many=True)
        self.assertEqual(response.data, serializer.data)
Exemple #15
0
    def groups(self, request, pk=None):
        try:
            user = self.all_users[pk]
        except KeyError:
            raise NotFound(detail="User not found in any groups", code=404)

        try:
            groups = get_groups(settings.GRP_FILEPATH).values()
        except IOError:
            raise NotFound('Invalid File: {}'.format(settings.GRP_FILEPATH))

        try:
            groups = get_groups(settings.GRP_FILEPATH).values()
        except IOError:
            raise NotFound('Invalid File: {}'.format(settings.GRP_FILEPATH))

        filtered_groups = []
        for group in groups:
            if user.name in group.members:
                filtered_groups.append(group)

        serializer = GroupSerializer(instance=filtered_groups, many=True)
        return Response(serializer.data)
    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)

        if serializer.is_valid():
            user = serializer.object.get('user') or request.user
            token = serializer.object.get('token')
            response_data = jwt_response_payload_handler(token, user, request)
            response_data.update(UserDetailSerializer(user).data)
            response_data["groups"] = GroupSerializer(user.groups.all(),
                                                      many=True).data
            response_data["permissions"] = sorted(
                User.get_all_permissions(user))
            response = Response(response_data)
            if api_settings.JWT_AUTH_COOKIE:
                expiration = (datetime.utcnow() +
                              api_settings.JWT_EXPIRATION_DELTA)
                response.set_cookie(api_settings.JWT_AUTH_COOKIE,
                                    token,
                                    expires=expiration,
                                    httponly=True)
            return response

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    def get(self, request, user_id, *args, **kwargs):

        user = get_object_or_404(User, pk=user_id)
        serializer = GroupSerializer(user.group)
        return Response(serializer.data, status=status.HTTP_200_OK)
 def destroy(self, request, *args, **kwargs):
     instance = self.get_object()
     data = GroupSerializer(instance).data
     instance.delete()
     return Response(data, status=status.HTTP_204_NO_CONTENT)
Exemple #19
0
 def get(self, request, groupname):
     group = self.get_group(groupname)
     serializer = GroupSerializer(group)
     return Response(serializer.data, status=status.HTTP_200_OK)
Exemple #20
0
 def list(self, request):
     serializer = GroupSerializer(instance=self.all_groups.values(), many=True)
     return Response(serializer.data)
Exemple #21
0
    def update(cls, root, info, **kwargs):
        data = kwargs.get("input")
        profile_data = data.pop("profile", None)

        data = kwargs.get("input")
        profile_data = data.pop("profile", {})

        # 只有教师才可以修改其他用户的信息
        # 否则就算是传入了id也只能修改自己的信息
        pk = data.pop("id")
        user = info.context.user
        if user.is_staff:
            user = get_Object_or_None(User, pk=pk)
            if not user:
                return cls.get_errors(__fill_error("id", "用户不存在!"))

            if user.is_staff:
                user = info.context.user

            profile_data["updater"] = user.id

        # 如果更改了name属性,则先检查组内是否有同名组
        name = profile_data.get("name", None)
        if name:
            if get_Object_or_None(group, name=name):
                return cls.get_errors(__fill_error("name", "已经存在同名组:" + name))

        user_ser = UserSerializer(instance=user, data=data, partial=True)
        if not user_ser.is_valid():
            errors = [
                ErrorType(field=key, messages=value)
                for key, value in user_ser.errors.items()
            ]
            return cls.get_errors(errors)

        group = user.groups.all().filter(name=user.profile.name).first()
        group_ser = GroupSerializer(instance=group,
                                    data={"name": name},
                                    partial=True)
        if not group_ser.is_valid():
            errors = [
                ErrorType(field=key, messages=value)
                for key, value in group_ser.errors.items()
            ]
            return cls.get_errors(errors)

        gp_ser = GroupProfileSerializer(instance=group.profile,
                                        data={},
                                        partial=True)
        if not gp_ser.is_valid():
            errors = [
                ErrorType(field=key, messages=value)
                for key, value in gp_ser.errors.items()
            ]
            return cls.get_errors(errors)

        profile = UserProfile.objects.filter(user_id=user.id).first()
        profile_ser = None
        if not profile:
            profile_ser = UserProfileSerializer(data=profile_data)
        else:
            profile_ser = UserProfileSerializer(instance=profile,
                                                data=profile_data,
                                                partial=True)
        ok, profile = cls.save(profile_ser, root, info)
        if not ok:
            return cls.get_errors(profile)
        user_ser.save()
        group_ser.save()
        gp_ser.save()
        return cls.perform_mutate(user, info)
Exemple #22
0
    def get(self, request):
        groups = Group.objects.all()

        groups_serialized = GroupSerializer(groups, many=True)
        return Response(groups_serialized.data)