Ejemplo n.º 1
0
 def reply_comment(self, reply, comment_id):
     comment = self.get_comment(comment_id)
     Utils._assert(
         not comment, "This comment has been deleted.", EntityException)
     replies = comment.get('replies')
     replies[reply.id] = Utils.toJson(reply)
     self.put()
    def post(self, user, institution_urlsafe):
        """Handler of post requests. This method is called when an
        institution requests to be parent of other institution."""
        user.check_permission('send_link_inst_request',
                              'User is not allowed to send request',
                              institution_urlsafe)

        data = json.loads(self.request.body)
        host = self.request.host
        inst_children_request_type = 'REQUEST_INSTITUTION_CHILDREN'

        type_of_invite = data.get('type_of_invite')

        Utils._assert(type_of_invite != inst_children_request_type,
                      "The type must be REQUEST_INSTITUTION_CHILDREN",
                      EntityException)

        parent_key = ndb.Key(urlsafe=institution_urlsafe)
        requested_inst_key = data.get('institution_requested_key')
        requested_inst_key = ndb.Key(urlsafe=requested_inst_key)

        Utils._assert(
            Institution.has_connection_between(parent_key, requested_inst_key),
            "Circular hierarchy not allowed", EntityException)

        request = InviteFactory.create(data, type_of_invite)
        request.put()

        institution_parent = parent_key.get()
        institution_parent.add_child(requested_inst_key)

        request.send_invite(host, user.current_institution)

        self.response.write(json.dumps(request.make()))
Ejemplo n.º 3
0
 def check_authorization(self, user, post_urlsafe, *args):
     obj_key = ndb.Key(urlsafe=post_urlsafe)
     post = obj_key.get()
     Utils._assert(post.author != user.key,
                   'User is not allowed to edit this post',
                   NotAuthorizedException)
     method(self, user, post_urlsafe, *args)
Ejemplo n.º 4
0
    def delete(self, user, invite_urlsafe):
        """Change invite status from 'sent' to 'rejected'.
        
        This method is called when an user reject a invite
        to create a new institution.
        """
        invite_key = ndb.Key(urlsafe=invite_urlsafe)
        invite = invite_key.get()

        invite_class_name = invite.__class__.__name__
        Utils._assert(invite_class_name != 'InviteInstitution',
                      "The invite's type is %s, but InviteInstitution is the expected one" %invite_class_name,
                      NotAuthorizedException)

        Utils._assert(invite.status != 'sent',
                      "This invitation has already been processed",
                      NotAuthorizedException)

        invite.change_status('rejected')
        invite.put()
        invite.send_response_notification(
            user.current_institution, user.key, 'REJECT')

        stub_institution = invite.stub_institution_key.get()
        stub_institution.change_state('inactive')
Ejemplo n.º 5
0
    def delete(self, user, request_key):
        """Change request status from 'sent' to 'rejected'."""
        request = ndb.Key(urlsafe=request_key).get()
        institution_key = request.institution_requested_key.urlsafe()

        Utils._assert(request.status != 'sent',
                      "this request has already been processed",
                      EntityException)

        user.check_permission('answer_user_request',
                              "User is not allowed to reject user request",
                              institution_key)

        request.change_status('rejected')

        sender_user = request.sender_key.get()
        sender_user.remove_profile(institution_key)

        sender_user.put()
        request.put()

        host = self.request.host
        request.send_response_email(host, "REJECT")
        request.send_response_notification(user, user.current_institution,
                                           'REJECT')

        self.response.write(json.dumps(makeUser(sender_user, self.request)))
Ejemplo n.º 6
0
    def put(self, user, institution_key, inviteKey):
        """
        Handle PUT Requests.
        
        This method end up the institution's configurations 
        from its previously created stub. Besides, it marks the invite received as accepted and 
        adds the permissions to the parent admins if the institution created has a parent institution.
        """
        body = json.loads(self.request.body)
        data = body['data']

        institution = ndb.Key(urlsafe=institution_key).get()

        invite = ndb.Key(urlsafe=inviteKey).get()

        Utils._assert(invite.status == 'accepted', 
            "This invitation has already been accepted", 
            NotAuthorizedException)
        
        invite.status = 'accepted'
        invite.put()

        institution.createInstitutionWithStub(user, institution)
        
        user.name = data.get('sender_name')
        user.config_user_adm(institution)

        setup_enqueue_process(invite, institution, user)
        
        institution_json = Utils.toJson(institution)
        self.response.write(json.dumps(
            institution_json))
Ejemplo n.º 7
0
    def post(self, user, post_key, comment_id=None, reply_id=None):
        """Handle POST Requests."""
        """This method is only meant to give like in post, comment or reply and send notification."""
        post = ndb.Key(urlsafe=post_key).get()
        Utils._assert(post.state == 'deleted', "This post has been deleted",
                      EntityException)
        if comment_id:
            comment = post.like_comment(user, comment_id, reply_id)

            notification_type = 'LIKE_COMMENT'
            user_is_the_author = comment['author_key'] == user.key.urlsafe()
            if not user_is_the_author:
                receiver_key = comment['author_key']
                notification_message = post.create_notification_message(
                    user_key=user.key,
                    current_institution_key=user.current_institution,
                    sender_institution_key=post.institution)
                send_message_notification(receiver_key=receiver_key,
                                          notification_type=notification_type,
                                          entity_key=post_key,
                                          message=notification_message)
        else:
            post = post.like(user.key)

            entity_type = 'LIKE_POST'
            params = {
                'receiver_key': post.author.urlsafe(),
                'sender_key': user.key.urlsafe(),
                'entity_key': post.key.urlsafe(),
                'entity_type': entity_type,
                'current_institution': user.current_institution.urlsafe(),
                'sender_institution_key': post.institution.urlsafe()
            }

            enqueue_task('post-notification', params)
Ejemplo n.º 8
0
    def put(self, user, invite_key):
        """Handler of accept invite."""
        invite = ndb.Key(urlsafe=invite_key).get()

        Utils._assert(invite.status != 'sent',
                      "This invitation has already been processed",
                      NotAuthorizedException)

        Utils._assert(invite.make()['type_of_invite'] != 'INVITE_USER_ADM',
                      "Invitation type not allowed", NotAuthorizedException)

        actual_admin = invite.admin_key.get()
        institution = invite.institution_key.get()

        @ndb.transactional(xg=True, retries=10)
        def save_changes(user, actual_admin, invite, institution):
            user.add_institution_admin(institution.key)
            actual_admin.remove_institution_admin(institution.key)
            invite.change_status('accepted')

            system_notification_id = invite.create_system_notification()
            notification_id = invite.create_accept_response_notification(
                user.current_institution)

            enqueue_task(
                'transfer-admin-permissions', {
                    'institution_key': institution.key.urlsafe(),
                    'user_key': user.key.urlsafe(),
                    'notifications_ids':
                    [system_notification_id, notification_id]
                })

        save_changes(user, actual_admin, invite, institution)
        self.response.write(json.dumps(user.make(self.request)))
    def post(self, user, institution_key):
        """Handler of post requests."""
        body = json.loads(self.request.body)
        data = body['data']
        host = self.request.host
        inst_request_type = 'REQUEST_INSTITUTION'

        type_of_invite = data.get('type_of_invite')

        Utils._assert(type_of_invite != inst_request_type,
                      "The type must be REQUEST_INSTITUTION", EntityException)

        user.name = data['admin']['name']
        user.put()

        inst_stub = createInstitution(user, data)
        data['sender_key'] = user.key.urlsafe()
        data['institution_key'] = inst_stub.key.urlsafe()
        data['admin_key'] = user.key.urlsafe()

        request = InviteFactory.create(data, type_of_invite)
        request.put()

        request.send_invite(host, user.current_institution)

        self.response.write(json.dumps(request.make()))
Ejemplo n.º 10
0
    def put(self, user, request_key):
        """Handler PUT Requests."""
        request = ndb.Key(urlsafe=request_key).get()

        Utils._assert(request.status != 'sent',
                      "This request has already been processed",
                      NotAuthorizedException)

        user.check_permission('analyze_request_inst',
                              'User is not allowed to make this action.',
                              request.institution_requested_key.urlsafe())

        request.change_status('accepted')
        request.put()

        institution = request.institution_key.get()
        institution.state = 'active'

        sender = request.sender_key.get()
        sender.add_institution(institution.key)
        sender.follow(institution.key)
        sender.institutions_admin.append(institution.key)
        sender.change_state('active')

        sender.config_user_adm(institution)

        institution.follow(sender.key)
        institution.add_member(sender)
        institution.set_admin(sender.key)
        institution.put()

        request.send_response_email("ACCEPT")

        self.response.write(json.dumps(request.make()))
    def put(self, user, request_key):
        """Handler PUT Requests. Change status of children_request from 'sent' to 'accepted'."""
        request = ndb.Key(urlsafe=request_key).get()
        user.check_permission(
            'answer_link_inst_request',
            'User is not allowed to accept link between institutions',
            request.institution_requested_key.urlsafe())

        Utils._assert(
            request.institution_requested_key.get().parent_institution != None,
            "The institution's already have a parent", NotAuthorizedException)

        request.change_status('accepted')

        institution_children = request.institution_requested_key.get()
        institution_children.set_parent(request.institution_key)

        request.send_response_notification(user.current_institution, user.key,
                                           'ACCEPT')
        request.send_response_email('ACCEPT')

        enqueue_task('add-admin-permissions',
                     {'institution_key': institution_children.key.urlsafe()})

        self.response.write(json.dumps(request.make()))
Ejemplo n.º 12
0
    def patch(self, user, event_urlsafe):
        """Handle PATCH Requests.
        To edit an event some conditions gotta be satisfied:
        The user gotta have the permission, the event can't be
        deleted and the operations gotta be valid.
        """
        patch = self.request.body

        event = ndb.Key(urlsafe=event_urlsafe).get()

        user.check_permission('edit_post',
            "The user can not edit this event",
            event_urlsafe)

        Utils._assert(event.state == 'deleted',
                      "The event has been deleted.", NotAuthorizedException)

        event.verify_patch(patch)

        """Apply patch."""
        JsonPatch.load(patch, event)

        is_patch = True
        event.isValid(is_patch)

        """Update event."""
        event.put()
Ejemplo n.º 13
0
    def post(self, user, post_key):
        """Handle Post Comments requests."""
        body = json.loads(self.request.body)
        comment_data = body['commentData']
        post = ndb.Key(urlsafe=post_key).get()
        institution = post.institution.get()

        Utils._assert(not institution.is_active(),
                      "This institution is not active", EntityException)
        Utils._assert(post.state == 'deleted', "This post has been deleted",
                      EntityException)

        comment = Comment.create(comment_data, user)
        post.add_comment(comment)
        entity_type = 'COMMENT'

        params = {
            'receiver_key': post.author.urlsafe(),
            'sender_key': user.key.urlsafe(),
            'entity_key': post.key.urlsafe(),
            'entity_type': entity_type,
            'current_institution': user.current_institution.urlsafe(),
            'sender_institution_key': post.institution.urlsafe()
        }
        enqueue_task('post-notification', params)

        self.response.write(json.dumps(Utils.toJson(comment)))
Ejemplo n.º 14
0
def check_permission(user, institution, post, comment):
    """Check the user permission to delete comment."""
    isNotPostAuthor = post.author != user.key
    isNotAdmin = institution.admin != user.key
    isNotCommentAuthor = comment.get('author_key') != user.key.urlsafe()
    Utils._assert(isNotPostAuthor and isNotAdmin and isNotCommentAuthor,
                  "User not allowed to remove comment", NotAuthorizedException)
Ejemplo n.º 15
0
    def delete(self, user, post_urlsafe):
        """Handle DELETE Requests."""
        """Get the post from the datastore."""
        obj_key = ndb.Key(urlsafe=post_urlsafe)
        post = obj_key.get()

        is_admin = user.has_permission("remove_posts",
                                       post.institution.urlsafe())
        is_author = user.has_permission("remove_post", post_urlsafe)

        Utils._assert(not is_admin and not is_author,
                      "The user can not remove this post",
                      NotAuthorizedException)

        post.delete(user)

        if (is_admin and not is_author):
            notification_message = post.create_notification_message(
                user_key=user.key,
                current_institution_key=user.current_institution,
                sender_institution_key=post.institution)
            send_message_notification(receiver_key=post.author.urlsafe(),
                                      notification_type='DELETED_POST',
                                      entity_key=post.key.urlsafe(),
                                      message=notification_message,
                                      entity=json.dumps(
                                          post.make(self.request.host)))
Ejemplo n.º 16
0
def calcula_custo(tempo_min, custo_hora):
    """Calcula custo de uma tarefa.
	Argumentos:
		tempo_min -- Tempo em minutos da duração da tarefa
		custo_hora -- Custo por hora para execução da tarefa 
	"""
    Utils._assert(tempo_min < 0 or custo_hora < 0, "Dados inválidos",
                  ExcecaoGenerica)
    return (tempo_min * custo_hora) / 60
 def get(self, user, request_key):
     """Handler GET Requests. 
         Return the request send to user requestting link with institution that he/she administers."""
     request = ndb.Key(urlsafe=request_key).get()
     has_permission = user.has_permission('answer_link_inst_request', request.institution_requested_key.urlsafe())
     Utils._assert(not has_permission,
                   'User is not allowed to acess request link.',
                   NotAuthorizedException)
     
     self.response.write(json.dumps(request.make()))
Ejemplo n.º 18
0
    def delete(self, user, institution_children_urlsafe,
               institution_parent_urlsafe):
        """
        Handle delete parent link between institutions.

        This handler remove the parent link between two institutions.
        This handler is called by children institution to remove link with the parent.
        """
        institution_children = ndb.Key(
            urlsafe=institution_children_urlsafe).get()
        institution_parent = ndb.Key(urlsafe=institution_parent_urlsafe).get()

        Utils._assert(not type(institution_children) is Institution,
                      "Key is not an institution", EntityException)
        Utils._assert(not type(institution_parent) is Institution,
                      "Key is not an institution", EntityException)

        user.check_permission(
            'remove_link',
            "User is not allowed to remove link between institutions",
            institution_children_urlsafe)

        # Remove Parent
        institution_children.set_parent(None)
        admin = institution_parent.admin

        notification_id = create_notification(
            user=user,
            receiver_institution=institution_parent,
            sender_institution=institution_children,
            create_message=institution_children.create_notification_message)

        enqueue_task(
            'remove-admin-permissions', {
                'institution_key': institution_children.key.urlsafe(),
                'parent_key': institution_parent.key.urlsafe(),
                'notification_id': notification_id
            })

        email_sender = RequestLinkEmailSender(
            **{
                'institution_parent_name': institution_parent.name,
                'institution_parent_email':
                institution_parent.institutional_email,
                'institution_requested_key': institution_parent.key.urlsafe(),
                'institution_child_name': institution_children.name,
                'institution_child_email':
                institution_children.institutional_email,
                'subject': get_subject('REMOVED_LINK_EMAIL'),
                'receiver': admin.get().email[0],
                'html': 'removed_institutional_link.html'
            })
        email_sender.send_email()
Ejemplo n.º 19
0
    def check_authorization(self, user, institution_key, inviteKey):
        invite = ndb.Key(urlsafe=inviteKey).get()

        emailIsNotInvited = invite.invitee not in user.email
        institutionIsNotInvited = ndb.Key(
            urlsafe=institution_key) != invite.stub_institution_key

        Utils._assert(emailIsNotInvited or institutionIsNotInvited,
                      'User is not invitee to create this Institution',
                      NotAuthorizedException)

        method(self, user, institution_key, inviteKey)
Ejemplo n.º 20
0
    def post(self, user, url_string):
        """Add follower in the institution."""
        institution_key = ndb.Key(urlsafe=url_string)
        institution = institution_key.get()

        Utils._assert(not institution.is_active(),
                      "This institution is not active", NotAuthorizedException)

        if(not type(institution) is Institution):
            raise Exception("Key is not an Institution")

        institution.follow(user.key)
        user.follow(institution_key)
Ejemplo n.º 21
0
    def check_invite(self):
        invitee = self.invitee_key
        institution = self.institution_key.get()
        Utils._assert(
            invitee not in institution.members, 
            "The invitee is not a member of this institution!", 
            NotAuthorizedException)
        
        Utils._assert(
            invitee == institution.admin,
            "The invitee is already admin of this institution!", 
            NotAuthorizedException
        )
        
        Utils._assert(
            self.sender_key != institution.admin, 
            "Sender is not admin of this institution!", 
            NotAuthorizedException
        )
        
        queryAnotherInvite = InviteUserAdm.query(
            InviteUserAdm.institution_key == self.institution_key,
            InviteUserAdm.status == 'sent'
        )

        Utils._assert(
           queryAnotherInvite.count() > 0,
           "An invitation is already being processed for this institution!",
           NotAuthorizedException
        )
Ejemplo n.º 22
0
    def post(self, user, post_urlsafe):
        """Handle POST Requests.
        This method, if the post is published,
        subscribes the user to the post whose key
        is post_urlsafe. Thus, the user will receive 
        notifications warning about actions in this post.
        """
        post = ndb.Key(urlsafe=post_urlsafe).get()

        Utils._assert(post.state != 'published',
                      'The post is unavailable to this procedure',
                      NotAuthorizedException)

        post.add_subscriber(user)
    def post(self, user, url_string):
        """Add follower in the institution."""
        institution_key = ndb.Key(urlsafe=url_string)
        institution = institution_key.get()

        Utils._assert(institution.state == 'inactive',
                      "The institution has been deleted",
                      NotAuthorizedException)

        if (not type(institution) is Institution):
            raise Exception("Key is not an Institution")

        institution.follow(user.key)
        user.follow(institution_key)
Ejemplo n.º 24
0
 def like(self, author_key):
     """Increment one 'like' in post."""         
     post = self.key.get()
     user =  author_key.get()
     Utils._assert(post.key in user.liked_posts, 
         "User already liked this publication", NotAuthorizedException)
     if post.get_like(author_key) is None:
         like = Like()
         like.author = author_key
         like.id = Utils.getHash(like)
         post.likes.append(like)
         post.put()
         user.like_post(post.key)
     return post
Ejemplo n.º 25
0
    def delete(self, user, post_key, comment_id):
        """Handle Delete Comments requests."""
        post = ndb.Key(urlsafe=post_key).get()
        institution = post.institution.get()

        Utils._assert(institution.state == 'inactive',
                      "The institution has been deleted",
                      NotAuthorizedException)
        Utils._assert(post.state == 'deleted',
                      "Can not delete comment in deleted post",
                      NotAuthorizedException)

        comment = post.get_comment(comment_id)
        has_activity = len(comment.get('replies')) > 0 or len(
            comment.get('likes')) > 0

        Utils._assert(has_activity, "Comment with activity can't be removed",
                      NotAuthorizedException)
        Utils._assert(has_activity, "Comment with activity can't be removed",
                      NotAuthorizedException)

        check_permission(user, institution, post, comment)
        post.remove_comment(comment)

        self.response.write(json.dumps(comment))
Ejemplo n.º 26
0
    def post(self, user):
        """Post Event."""
        data = json.loads(self.request.body)
        institution_key = ndb.Key(urlsafe=data['institution_key'])
        institution = institution_key.get()

        Utils._assert(not institution.is_active(),
                      "This institution is not active", NotAuthorizedException)

        event = Event.create(data, user, institution)
        event.put()
        user.add_permissions(['remove_post', 'edit_post'], event.key.urlsafe())
        user.put()

        self.response.write(json.dumps(Utils.toJson(Event.make(event), host=self.request.host)))
Ejemplo n.º 27
0
    def like_comment(self, user, comment_id=None, reply_id=None):
        """Increment one 'like' in  comment or reply.""" 
        post = self.key.get()
        comment = post.get_comment(comment_id)
        if reply_id:
            comment = comment.get('replies').get(reply_id)

        Utils._assert(comment is None,
                    "This comment has been deleted.", NotAuthorizedException)
        likes = comment.get('likes')
        
        Utils._assert(user.key.urlsafe() in likes,
                    "User already liked this comment", NotAuthorizedException)
        likes.append(user.key.urlsafe())
        post.put()
        return comment
Ejemplo n.º 28
0
    def patch(self, user, post_urlsafe):
        """Handler PATCH Requests."""
        data = self.request.body

        post = ndb.Key(urlsafe=post_urlsafe).get()

        Utils._assert(post.has_activity(), "The user can not update this post",
                      NotAuthorizedException)

        user.check_permission("edit_post",
                              "User is not allowed to edit this post",
                              post_urlsafe)
        """Apply patch."""
        JsonPatch.load(data, post)
        """Update post."""
        post.put()
Ejemplo n.º 29
0
    def get(self, user, event_urlsafe):
        """Handle GET Requests.
        Get specific event, whose key is event_urlsafe,
        if it is not deleted. 
        """
        event_key = ndb.Key(urlsafe=event_urlsafe)
        event = event_key.get()

        Utils._assert(event.state == 'deleted', 
            "The event has been deleted.", NotAuthorizedException)

        assert type(event) is Event, "Key is not an Event"
        event_json = Event.make(event)

        self.response.write(json.dumps(
            event_json
        ))
Ejemplo n.º 30
0
    def delete(self, user, event_urlsafe):
        """Change event's state from 'published' to 'deleted'
        if the user has permission to.
        """
        event_key = ndb.Key(urlsafe=event_urlsafe)
        event = event_key.get()

        is_admin = user.has_permission("remove_posts", event.institution_key.urlsafe())
        is_author = user.has_permission("remove_post", event.key.urlsafe())

        Utils._assert(not is_admin and not is_author,
                      "The user can not remove this event", NotAuthorizedException)

        event.state = 'deleted'
        event.last_modified_by = user.key
        event.last_modified_by_name = user.name
        event.put()