コード例 #1
0
ファイル: board.py プロジェクト: ar3s3ru/uChan3
        def routine(user: User, board: Board):
            """
            Create new Thread linked to specified board, from POST JSON data.

            :param user:  Requesting User object
            :param board: Board object
            :return: New thread inside specified board
            """
            try:
                # Check thread JSON arguments
                self.check_args()
                self.validate_args()

                # Process anon, image and construct new entity
                anon   = str_to_bool(self.args['anon'])
                image  = self.media_processing()
                thread = Thread(anon, self.args['title'], self.args['text'], image, board.id, user.id)

                # Add new Thread table to database
                uchan.add_to_db(thread)

                # Add new ThreadUser link
                thread = user.get_last_thread()
                uchan.add_to_db(ThreadUser(thread.id, user.id))

                return responses.successful(201, JSONRepresentation.thread(thread, user))
            except ValueError as msg:
                return responses.client_error(400, '{}'.format(msg))
            except KeyError as key:
                return responses.client_error(400, 'Invalid parameter: {}'.format(key))
コード例 #2
0
ファイル: post.py プロジェクト: ar3s3ru/uChan3
        def routine(user: User):
            # Retrieve post
            post = self.get_post(id)

            if post is None:
                # Post does not exist
                return responses.client_error(404, 'Post does not exist')

            if not user.admin and post.author != user.id:
                # Post cannot be deleted from requesting user
                return responses.client_error(401, 'User cannot delete this post')

            image  = post.image is not None             # If post has image
            thread = ThreadAPI.get_thread(post.thread)  # Retrieve thread parent

            if thread is None:
                # Thread is None, IMPOSSIBLE
                raise AssertionError('Thread cannot be None')

            # Delete post from database and decrement replies
            uchan.delete_from_db(post, False)
            thread.decr_replies(image)
            uchan.commit()

            return '', 204
コード例 #3
0
ファイル: thread.py プロジェクト: ar3s3ru/uChan3
def thread_routine(user: User, func, id: int, *args, **kwargs):
    """
    Basic thread routine.
    Serves as a layer of abstraction to thread priority errors in thread method resource routines.

    This function needs to be passed (and called) by session_oriented_request() (inherited from AuthEntity),
    with subroutine function (that has to be called from within this routine) and an ID (serves as Thread ID).

    Function passed to this routine needs this signature:
        >>> def func(user: User, thread: Thread, *args, **kwargs)

    N.B. *args and **kwargs can be omitted.

    :param user:   User Object (got from session_oriented_request())
    :param func:   Subroutine function (needs to be called from within this routine)
    :param id:     Thread ID
    :param args:   Name arguments
    :param kwargs: Positional arguments
    :return:
    """
    thread = ThreadAPI.get_thread(id)

    if thread is None:
        return responses.client_error(404, 'Thread does not exist')

    if not user.board_subscribed(thread.board):
        return responses.client_error(401, 'User is not authorized to see this thread')

    return func(user, thread, *args, **kwargs)
コード例 #4
0
ファイル: board.py プロジェクト: ar3s3ru/uChan3
def board_routine(user: User, func, id: int, *args, **kwargs):
    """
    Basic board routine.
    Serves as a layer of abstraction to treat priority errors in board method resource routines.

    This fuction needs to be passed (and called) by session_oriented_request() (inherited from AuthEntity),
    with subroutine function (that has to be called from within this routine) and an ID (serves as Board ID).

    Function passed to this routine needs this signature:
        >>> def func(user: User, board: Board, *args, **kwargs)

    N.B. *args and **kwargs can be omitted.

    :param user:   User Object (got from session_oriented_request())
    :param func:   Subroutine function (needs to be called from within this routine)
    :param id:     Board ID
    :param args:   Name arguments
    :param kwargs: Positional arguments
    :return:
    """
    # Requesting board object
    board = BoardAPI.get_board(id)

    if board is None:
        # Board does not exists
        return responses.client_error(404, 'Board does not exist')
    elif not user.board_subscribed(id):
        # User not subscribed to this board
        return responses.client_error(401, 'User is not authorized to see this board')

    # Return the result got from closure function passed as argument
    return func(user, board, *args, **kwargs)
コード例 #5
0
ファイル: chat.py プロジェクト: ar3s3ru/uChan3
        def request_routine(user: User):
            threaduser = ChatRequestAPI.get_threaduser(id)

            if threaduser is None:
                return responses.client_error(404, 'User map object does not exists')

            if user.has_requested_chat(threaduser.user):
                return responses.client_error(409, 'Chat already requested')

            request = ChatRequest(user.id, threaduser.user)
            uchan.add_to_db(request)

            return responses.successful(201, 'Chat request sent')
コード例 #6
0
ファイル: thread.py プロジェクト: ar3s3ru/uChan3
        def routine(user: User, thread: Thread):
            """
            Creates new Post table object and returns it as JSON representation.
            Image posting is totally optional (but if chosen, it needs both 'image' and 'image_name' fields.

            :param user:   User object
            :param thread: Thread object
            :return: New Post Object as JSON object
            """
            try:
                self.check_args()
                self.validate_args()

                anon  = str_to_bool(self.args['anon'])
                image = self.media_processing() if self.args['image'] is not None and \
                                                   self.args['image_name'] is not None else None

                post = Post((user.id == thread.author), anon, self.args['text'], thread.id, user.id, thread.board,
                            self.args['reply'], image)

                # Add new Post table to database
                uchan.add_to_db(post)

                # Add new ThreadUser link
                if thread.get_authid(user.id) is None:
                    uchan.add_to_db(ThreadUser(thread.id, user.id))

                # Increments thread counter
                thread.incr_replies((image is not None))
                uchan.commit()

                return responses.successful(201, JSONRepresentation.post(thread.get_last_post(), thread, user))
            except ValueError as msg:
                return responses.client_error(400, '{}'.format(msg))
コード例 #7
0
ファイル: registration.py プロジェクト: ar3s3ru/uChan3
    def post(self):
        """
        POST method implementation for API Registration resource entity.

        :return: JSON response to Registration method (201 Created, 409 Conflict, 400 Bad Request)
        """
        try:
            # Arguments validation
            self.check_args()
            self.validate_args()

            # Integrity checks
            if not self.check_existing_email():
                return responses.client_error(409, "Email already registered")

            if not self.check_existing_nickname():
                return responses.client_error(409, "Nickname already registered")

            salt, token = self.generate_salt(), self.generate_token()

            # Creating new User entity
            user = User(
                self.args["nickname"],
                routines.hashing_password(salt, self.args["password"]),
                salt,
                self.args["university"],
                self.args["email"],
                self.args["gender"],
                False,
                token,
            )

            # TODO: remove this and insert email sending
            print(user.token)

            # Add new entity to database
            uchan.add_to_db(user)
            return responses.successful(201, "Registration sent")
        except ValueError as msg:
            # Arguments validation error
            return responses.client_error(400, "{}".format(msg))
        except IntegrityError as msg:
            # Database integrity error
            return responses.client_error(
                409, "Registration error, check your JSON or contact server manteiner".format(msg)
            )
コード例 #8
0
ファイル: thread.py プロジェクト: ar3s3ru/uChan3
        def routine(user: User, thread: Thread):
            if not user.admin and thread.author != user.id:
                return responses.client_error(401, 'User cannot delete this thread')

            for post in thread.posts:
                uchan.delete_from_db(post, False)

            uchan.delete_from_db(thread)

            return '', 204
コード例 #9
0
ファイル: session.py プロジェクト: ar3s3ru/uChan3
    def post(self):
        """
        POST method implementation for API Session resource entity.

        :return: JSON response (201 Created, 400 Bad Request, 409 Conflict [Database IntegrityError])
        """
        try:
            self.check_args()
            self.validate_args()

            session, user = self.register_session(request)

            uchan.add_to_db(session)
            return responses.successful(201, {'token': session.token, 'user': JSONRepresentation.me(user)})
        except ValueError as msg:
            # Arguments validation error
            return responses.client_error(400, '{}'.format(msg))
        except IntegrityError as msg:
            # Database integrity error
            return responses.client_error(409, 'Session error, check your JSON or contact server manteiner'
                                          .format(msg))
コード例 #10
0
ファイル: university.py プロジェクト: ar3s3ru/uChan3
    def get(self, id=None):
        """
        GET method implementation for University API resource.

        :param id: University ID
        :return: Universities list (if id is None), else an University object (if id is not None); JSON representation.
                 University with ID == 1 is not accessible (401 Unauthorized, if requested);
                 University with ID not in the database will result in 404 Not Found.
        """
        if id is None:
            return responses.successful(200, [JSONRepresentation.university(uni)
                                              for uni in self.university_list() if uni.id != 1])
        elif id == 1:
            return responses.client_error(401, 'Cannot request this university')
        else:
            university = self.university_id(id)

            if university is None:
                return responses.client_error(404, 'University not found')
            else:
                return responses.successful(200, JSONRepresentation.university(university))
コード例 #11
0
ファイル: activation.py プロジェクト: ar3s3ru/uChan3
    def get(self, token: str):
        """
        GET method implementation for API Activation resource entity.

        :param token: Activation token from URL
        :return: JSON Response (200 OK, 404 Not Found, 409 Conflict)
        """
        user = self.retrieve_user_by_token(token)

        if user is None:
            return responses.client_error(404, 'Invalid token')

        if user.activated:
            return responses.client_error(409, 'User already activated')

        # Activate user and add it to boards
        user.activated = True
        self.add_to_general_boards(user)
        self.add_to_university_board(user)

        uchan.commit()
        return responses.successful(200, 'User {} activated'.format(user.nickname))
コード例 #12
0
ファイル: __init__.py プロジェクト: ar3s3ru/uChan3
    def session_oriented_request(self, func, *args, **kwargs):
        """
        Defines a session oriented request, needed to be implemented into subclasses methods like get(), post() ...
        Subclassess methods must define an inner closure that will be passed to this function.

        Closure has to have and User parameter as first positional argument.
        Other arguments are passed from this method callee.

        :param func:   HTTP method implementation function
        :param args:   Arguments
        :param kwargs: Assigned arguments
        :return:
        """
        try:
            session = self.check_authorization()
            user    = get_user(session.user)

            if user is None:
                return responses.client_error(404, 'User not found')

            return func(user, *args, **kwargs)
        except AuthException as ae:
            return responses.client_error(401, '{}'.format(ae))
コード例 #13
0
ファイル: session.py プロジェクト: ar3s3ru/uChan3
    def delete(self, token: str):
        """
        DELETE method implementation for API Session resource entity.

        :param token: Requested token to delete (from URL)
        :return: JSON response (204 No Content, 404 Not Found)
        """
        session = self.retrieve_session(token)

        if session is None:
            return responses.client_error(404, 'Token not found')

        uchan.delete_from_db(session)
        return '', 204
コード例 #14
0
ファイル: chat.py プロジェクト: ar3s3ru/uChan3
def accept_chat_routine(user: User, func, id: int, *args, **kwargs):
    chatrequest = AcceptChatAPI.get_chatrequest(id)

    if chatrequest is None:
        responses.client_error(404, 'Chat request does not exists')

    if chatrequest.u_to != user.id:
        responses.client_error(401, 'Cannot use this chat request')

    if chatrequest.accepted:
        responses.client_error(409, 'Chat request already accepted')

    return func(user, chatrequest, *args, **kwargs)
コード例 #15
0
ファイル: __init__.py プロジェクト: ar3s3ru/uChan3
 def wrapped(self, *args, **kwargs):
     if not self.check_headers(True):
         return responses.client_error(400, 'Wrong format request')
     else:
         return method(self, *args, **kwargs)