class PlanShareResource(Resource): def __init__(self): self.plan_repository = PlanRepository() super(PlanShareResource, self).__init__() @authenticate def post(self, plan_id, **kwargs): plan = query(self.plan_repository.get(user_id=kwargs['user'].id, id=plan_id)).single_or_default( default=None) if not plan: abort(404, message="This plan does not exist") post_body = request.json if type(post_body) is not list: on_error(error_message="Invalid post body") result = ChangeResult() try: shares = query(post_body) for shared_user in plan.shared_users: if not shares.contains(shared_user, lambda lhs, rhs: rhs['user_id'] == lhs.id): result.add_child_result( self.plan_repository.unshare(plan, shared_user.id)) for share in post_body: user_id = share['user_id'] permission = share['permission'] result.add_child_result( self.plan_repository.share(plan, user_id, permission)) except KeyError as ke: on_error(error_message="Invalid post body") if not result.success(): on_error(error_message="Could not share plan", result=result) self.plan_repository.save_changes() return plan