class PolicySerializer(serializers.ModelSerializer): """Serializer for the policy model.""" uuid = serializers.UUIDField(read_only=True) name = serializers.CharField(required=True, max_length=150) description = serializers.CharField(allow_null=True, required=False) group = GroupSerializer(required=True) roles = RoleSerializer(many=True, required=True) class Meta: """Metadata for the serializer.""" model = Policy fields = ('uuid', 'name', 'description', 'group', 'roles') def to_representation(self, obj): """Convert representation to dictionary object.""" group = GroupSerializer(obj.group) roles = [] for role in obj.roles.all(): serializer = RoleSerializer(role) roles.append(serializer.data) return { 'uuid': obj.uuid, 'name': obj.name, 'description': obj.description, 'group': group.data, 'roles': roles }
def to_representation(self, obj): """Convert representation to dictionary object.""" group = GroupSerializer(obj.group) roles = [] for role in obj.roles.all(): serializer = RoleSerializer(role) roles.append(serializer.data) return { 'uuid': obj.uuid, 'name': obj.name, 'description': obj.description, 'group': group.data, 'roles': roles }
def principals(self, request, uuid=None): """Get, add or remove principals from a group.""" """ @api {get} /api/v1/groups/:uuid/principals/ Get principals for a group @apiName getPrincipals @apiGroup Group @apiVersion 1.0.0 @apiDescription Get principals for a group @apiHeader {String} token User authorization token @apiParam (Path) {String} id Group unique identifier @apiSuccess {String} uuid Group unique identifier @apiSuccess {String} name Group name @apiSuccess {Array} principals Array of principals @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { "principals": [ { "username": "******" } ] } """ """ @api {post} /api/v1/groups/:uuid/principals/ Add principals to a group @apiName addPrincipals @apiGroup Group @apiVersion 1.0.0 @apiDescription Add principals to a group @apiHeader {String} token User authorization token @apiParam (Path) {String} id Group unique identifier @apiParam (Request Body) {String} username Principal username @apiParamExample {json} Request Body: { "principals": [ { "username": "******" }, { "username": "******" } ] } @apiSuccess {String} uuid Group unique identifier @apiSuccess {String} name Group name @apiSuccess {Array} principals Array of principals @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { "uuid": "16fd2706-8baf-433b-82eb-8c7fada847da", "name": "GroupA", "principals": [ { "username": "******" } ] } """ """ @api {delete} /api/v1/groups/:uuid/principals/ Remove principals from group @apiName removePrincipals @apiGroup Group @apiVersion 1.0.0 @apiDescription Remove principals from a group @apiHeader {String} token User authorization token @apiParam (Path) {String} id Group unique identifier @apiParam (Query) {String} usernames List of comma separated principal usernames @apiSuccessExample {json} Success-Response: HTTP/1.1 204 NO CONTENT """ principals = [] validate_uuid(uuid, "group uuid validation") group = self.get_object() account = self.request.user.account if request.method == "POST": serializer = GroupPrincipalInputSerializer(data=request.data) if serializer.is_valid(raise_exception=True): principals = serializer.data.pop("principals") resp = self.add_principals(group, principals, account) if isinstance(resp, dict) and "errors" in resp: return Response(status=resp["status_code"], data=resp["errors"]) output = GroupSerializer(resp) response = Response(status=status.HTTP_200_OK, data=output.data) elif request.method == "GET": principals_from_params = self.filtered_principals(group, request) page = self.paginate_queryset(principals_from_params) serializer = PrincipalSerializer(page, many=True) principal_data = serializer.data if principal_data: username_list = [ principal["username"] for principal in principal_data ] else: username_list = [] proxy = PrincipalProxy() all_valid_fields = VALID_PRINCIPAL_ORDER_FIELDS + [ "-" + field for field in VALID_PRINCIPAL_ORDER_FIELDS ] if request.query_params.get(ORDERING_PARAM): sort_field = validate_and_get_key(request.query_params, ORDERING_PARAM, all_valid_fields, "username") sort_order = "des" if sort_field == "-username" else "asc" else: sort_order = None resp = proxy.request_filtered_principals(username_list, account, sort_order=sort_order) if isinstance(resp, dict) and "errors" in resp: return Response(status=resp.get("status_code"), data=resp.get("errors")) response = self.get_paginated_response(resp.get("data")) else: if USERNAMES_KEY not in request.query_params: key = "detail" message = "Query parameter {} is required.".format( USERNAMES_KEY) raise serializers.ValidationError({key: _(message)}) username = request.query_params.get(USERNAMES_KEY, "") principals = [name.strip() for name in username.split(",")] self.remove_principals(group, principals, account) response = Response(status=status.HTTP_204_NO_CONTENT) return response
def principals(self, request, uuid=None): """Add or remove principals from a group.""" """ @api {post} /api/v1/groups/:uuid/principals/ Add principals to a group @apiName addPrincipals @apiGroup Group @apiVersion 1.0.0 @apiDescription Add principals to a group @apiHeader {String} token User authorization token @apiParam (Path) {String} id Group unique identifier @apiParam (Request Body) {String} username Principal username @apiParamExample {json} Request Body: { "principals": [ { "username": "******" }, { "username": "******" } ] } @apiSuccess {String} uuid Group unique identifier @apiSuccess {String} name Group name @apiSuccess {Array} principals Array of principals @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK { "uuid": "16fd2706-8baf-433b-82eb-8c7fada847da", "name": "GroupA", "principals": [ { "username": "******" } ] } """ """ @api {delete} /api/v1/groups/:uuid/principals/ Remove principals from group @apiName removePrincipals @apiGroup Group @apiVersion 1.0.0 @apiDescription Remove principals from a group @apiHeader {String} token User authorization token @apiParam (Path) {String} id Group unique identifier @apiParam (Query) {String} usernames List of comma separated principal usernames @apiSuccessExample {json} Success-Response: HTTP/1.1 204 NO CONTENT """ principals = [] group = self.get_object() account = self.request.user.account if request.method == 'POST': serializer = GroupPrincipalInputSerializer(data=request.data) if serializer.is_valid(raise_exception=True): principals = serializer.data.pop('principals') resp = self.add_principals(group, principals, account) if isinstance(resp, dict) and 'errors' in resp: return Response(status=resp['status_code'], data=resp['errors']) output = GroupSerializer(resp) return Response(status=status.HTTP_200_OK, data=output.data) else: if USERNAMES_KEY not in request.query_params: key = 'detail' message = 'Query parameter {} is required.'.format(USERNAMES_KEY) raise serializers.ValidationError({key: _(message)}) username = request.query_params.get(USERNAMES_KEY, '') principals = [name.strip() for name in username.split(',')] self.remove_principals(group, principals, account) return Response(status=status.HTTP_204_NO_CONTENT)