def create_comment(document_id: str, user_id: str, content: Dict) -> Dict:
    if not content.get("comment", False) or not content.get("target", False):
        raise HTTPException("Incorrect body content", 400)

    comment_id = mongo.create_comment(document_id, user_id, content["comment"],
                                      content["target"])

    if comment_id is None:
        raise HTTPException("Incorrect comment information", 400)

    return {"id": str(comment_id)}
def create_document(body: Dict, user_id: str) -> str:
    if not body.get("document_name", False):
        raise HTTPException("Incorrect body content", 400)

    document_name = body["document_name"]
    document_id = mongo.create_document(document_name, user_id)

    if document_id is None:
        raise HTTPException("Document already exist!", 409)

    return str(document_id)
Esempio n. 3
0
 def send(self):
     request = self._make_request()
     try:
         response = urlopen(request)
         return HTTPResponse(response,
                             encoding=self.encoding,
                             is_json=self.receives_json)
     except URLError as e:
         if e.code == 401:
             raise HTTPException("Error while authenticating.")
         elif e.code == 404:
             raise HTTPException("Page '{0}' does not exist.".format(
                 request.get_full_url()))
         else:
             raise HTTPException("An error has occured: {0}".format(e.code))
Esempio n. 4
0
    def parse_request_path(self, path):
        """Parses a request path & validates it"""

        username_match = self.regex_username.search(path)
        if username_match == None:
            raise HTTPException(
                400,
                'Path should conform /hello/<username> pattern. %s breaks this rule'
                % path)

        username = username_match.groups()[0]

        # fast, but less error proof code variant
        #
        #   splitted_path = os.path.split(path)
        #   if len(splitted_path)>2 :
        #       raise Exception('Path should conform /hello/<username> pattern. %s breaks this rule' % username)

        #   username=splitted_path[1]

        #   if ''==username :
        #     raise Exception('Path should conform /hello/<username> pattern. %s breaks this rule' % username)

        #   # re.search('[a-zA-Z]', username) - less fast
        #   if not any(c.isalpha() for c in username) :
        #       raise Exception('<username> must contains only letters. %s does not conform with this rule' % username)

        return username
Esempio n. 5
0
def get_messages(user_id: str) -> List:
    messages = cast(List, mongo.select_messages(user_id))

    if not messages:
        raise HTTPException("Incorrect user identifier", 403)

    return messages
def get_document_comments(document_id: str) -> List:
    comments = mongo.get_document_comments(document_id)

    if not comments:
        raise HTTPException("Invalid document identifier", 400)

    return comments
def archive_document(document_id: str, user_id: str) -> Dict:
    document: Dict = cast(Dict, mongo.find_document(document_id))
    user: Dict = cast(Dict, mongo.find_user_by_id(user_id))

    if document["company"] != user["company"]:
        raise HTTPException(
            "You should be member of company created this document!", 403)

    if document["status"] != Status.SIGNING.value or len(
            document["signed"]) < 2:
        raise HTTPException("Sign document before archive!", 409)

    mongo.update_document(document_id, "status", Status.ARCHIVE.value)
    send_email("archive", document_id, user_id)

    return {}
Esempio n. 8
0
def user_register(body: Dict) -> str:
    fields = ['company', 'username', 'user_role', 'email']

    if any(field not in body for field in fields):
        raise HTTPException("Incorrect body content", 400)

    if not role_validation(body["user_role"]):
        raise HTTPException("Invalid user role", 404)

    user_id = mongo.create_user(body["username"], body["user_role"],
                                body["company"], body["email"])

    if not user_id:
        raise HTTPException("User exist or reached company members limit", 403)

    return str(user_id)
Esempio n. 9
0
def accept_invite(body: Dict, user_id: str, invite_id: str) -> Dict:
    if not mongo.check_user_permissions(user_id, body["document_id"]):
        mongo.accept_invite(body["document_id"], user_id)

    if not mongo.remove_invite_by_id(invite_id):
        raise HTTPException("Incorrect invite identifier!", 400)

    return {}
Esempio n. 10
0
def create_message(body: Dict, user_id: str) -> Dict:
    if not body.get("to_users", False) or not body.get("message", False):
        raise HTTPException("Incorrect body content", 403)

    for user in body["to_users"]:
        mongo.create_message(user_id, user, body["message"])

    return {}
Esempio n. 11
0
def user_login(body: Dict) -> Dict:
    if not body.get("username", False):
        raise HTTPException(f"Incorrect body content {body}!", 400)

    username = body["username"]
    user = mongo.find_user_by_name(username)

    if user is None:
        raise HTTPException(f"User {username} not found!", 404)

    access_token = create_access_token(identity=str(user["_id"]))

    return {
        "token": access_token,
        "username": username,
        "id": str(user["_id"]),
    }
Esempio n. 12
0
def create_invite(user_identifier: str, body: Dict) -> Dict:
    user = mongo.find_user_by_name(body["username"])
    if user is None or str(user["_id"]) == user_identifier:
        raise HTTPException("Invalid identification data!", 403)

    document = cast(Dict, mongo.find_document(body["document"]))

    if (document["company"] != cast(
            Dict, mongo.find_user_by_id(user_identifier))["company"]):
        raise HTTPException("You should have permissions for this action!",
                            403)

    if not mongo.create_invite(user["_id"], body["document"]):
        raise HTTPException("Document not found!", 404)

    send_single_mail(str(document["_id"]), "invite to accept", user)
    return {}
Esempio n. 13
0
def user_profile(user_id: str) -> Dict:
    user = mongo.find_user_by_id(user_id)

    if user is None:
        raise HTTPException("Such user does not exist", 409)

    user["_id"] = str(user["_id"])

    return user
def get_documents(user_id: str) -> List:
    user: Dict = cast(Dict, mongo.find_user_by_id(user_id))

    if not user:
        raise HTTPException(f"User {user_id} not found", 404)

    documents = mongo.select_document(user["company"], user["_id"])

    return documents
def update_document(document_id: str, user_identifier: str,
                    content: Any) -> Dict:
    if not content:
        raise HTTPException("Empty body", 400)

    if content.get("operation", False):
        return update_document_state(document_id, user_identifier,
                                     content["operation"])

    return update_document_content(document_id, user_identifier, content)
def get_users_with_permissions(document_id: str, user_id: str) -> List:
    document = mongo.find_document(document_id)

    if document is None:
        raise HTTPException("Document not found", 404)

    users = mongo.get_users_with_permissions_to_document(
        document["_id"], document["company"], user_id)

    return users
def approve_document(document_id: str, user_id: str) -> Dict:
    document = mongo.find_document(document_id)
    user: Dict = cast(Dict, mongo.find_user_by_id(user_id))

    if not document:
        raise HTTPException(f"Document with {document_id} not found", 404)

    if user["role"] not in [Role.LAWYER.value, Role.ECONOMIST.value]:
        raise HTTPException("Invalid role for approving document!", 409)

    if user_id in document["approved"]:
        raise HTTPException("Document already approved by you!", 409)

    document["approved"].append(user_id)
    mongo.update_document(document_id, "approved", document["approved"])
    mongo.update_document(document_id, "status", Status.AGREED.value)

    send_email("approve", document_id, user_id)
    return {}
Esempio n. 18
0
 def _prepare_content_type(self):
     if self.content_type == MimeType.MULTIPART_FORM:
         if not self.multipart_form:
             raise HTTPException(
                 "Multipart form must be set when using multipart form content type."
             )
             self.set_header("Content-type",
                             self.multipart_form.get_content_type())
     else:
         self.set_header("Content-type", self.content_type)
Esempio n. 19
0
 def _make_data(self):
     if self.content_type == MimeType.JSON:
         data = json.dumps(self.encoded_data)
     elif self.content_type == MimeType.FORM:
         data = urlencode(self.encoded_data)
     elif self.content_type == MimeType.MULTIPART_FORM:
         data = str(self.multipart_form)
     else:
         raise HTTPException("Content type {0} is not handled".format(
             self.content_type))
     return bytes(data.encode(self.encoding))
def update_document_content(document_id: str, user_id: str,
                            content: Any) -> Dict:

    user = cast(Dict, mongo.find_user_by_id(user_id))
    document = mongo.find_document(document_id)

    if not document or user["company"] != document["company"]:
        raise HTTPException("You have no permission for that", 403)

    mongo.update_document(document_id, "content", content)
    return {}
def get_document(document_id: str, user_identifier: str) -> Dict:
    if mongo.check_user_permissions(user_identifier, document_id):
        document_content = mongo.find_document(document_id)

        if document_content:
            return {
                "content": document_content["content"],
                "id": str(document_content["_id"]),
                "status": document_content["status"],
            }

    raise HTTPException(f"Document with {document_id} not found", 404)
def update_document_state(document_id: str, user_id: str,
                          operation: str) -> Dict:
    operations = {
        "approve": approve_document,
        "sign": sign_document,
        "archive": archive_document,
    }

    if not operations.get(operation, False):
        raise HTTPException("Invalid operation type!", 404)

    return operations[operation](document_id, user_id)
def sign_document(document_id: str, user_id: str) -> Dict:
    document = cast(Dict, mongo.find_document(document_id))
    user = cast(Dict, mongo.find_user_by_id(user_id))

    if user["role"] != Role.GENERAL_DIRECTOR.value:
        raise HTTPException("Signing validation failed!", 409)

    if document["status"] not in [Status.AGREED.value, Status.SIGNING.value]:
        raise HTTPException("You can't execute such command!", 409)

    if not mongo.is_approved_by_company(document_id, user["company"]):
        raise HTTPException("Wait until document approved by your company!",
                            409)

    if user_id in document["signed"] or len(document["signed"]) >= 3:
        raise HTTPException("Already signed!", 409)

    document["signed"].append(user_id)
    mongo.update_document(document_id, "signed", document["signed"])
    mongo.update_document(document_id, "status", Status.SIGNING.value)
    send_email("sign", document_id, user_id)

    return {}
Esempio n. 24
0
    def do_GET(self):
        """Handles GET request"""

        try:
            # parse a request path & validate
            logging.debug("Received GET request %s", self.path)
            username = self.parse_request_path(self.path)

            c = DB.conn.cursor()

            # Read a user info
            query = """SELECT date_of_birth 
            FROM user_test 
            WHERE username = '******' 
            """ % username

            cursor = c.execute(query)

            row = cursor.fetchone()

            if None == row:
                raise HTTPException(
                    404, 'No username %s found in database.' % username)

            today = datetime.date.today()
            date_of_birth = datetime.datetime.strptime(row[0],
                                                       '%Y-%m-%d').date()
            next_birthday = datetime.datetime(today.year + 1,
                                              date_of_birth.month,
                                              date_of_birth.day).date()
            days = (next_birthday - today).days

            response = self.get_greetings(username, days)

            self._send_response_code_and_headers(
                200, {'Content-type': 'application/json'})
            self.wfile.write(response.encode())

        except HTTPException as e:
            logging.error(e.code_description_and_message)
            self._send_http_exception_response(e)
        except Exception as e:
            logging.error("Error: {0}".format(str(e.args[0])))
            self._send_501_response("Error {0}".format(str(e.args[0])))
        except:
            logging.error("Unexpected error:", sys.exc_info()[0])
            self._send_501_response()
Esempio n. 25
0
 def method(self, method):
     method = method.upper()
     if method not in HTTPRequest.accepted_methods:
         raise HTTPException("Unknown HTTP method {0}".format(method))
     self._method = method
Esempio n. 26
0
 def check_request(self):
     if any(key not in self.data.keys() for key in self.required_params):
         params_list = ','.join(self.required_params)
         raise HTTPException("Needs parameters '%s'.".format(params_list))
Esempio n. 27
0
def handle_invalid_usage(error: HTTPException) -> Response:
    response = jsonify(error.to_dict())
    response.status_code = error.status_code
    return response
def delete_document(document_id: str, user_identifier: str) -> Dict:
    if not mongo.delete_document(document_id, user_identifier):
        raise HTTPException(
            "You should be document creator to delete this document!", 403)

    return {}
Esempio n. 29
0
    def do_PUT(self):
        """Handles PUT request"""
        logging.debug("Received PUT request")

        try:
            # read the message and convert it into a python dictionary
            length = int(self.headers['content-length'])

            raw_message = self.rfile.read(length)
            message = json.loads(raw_message)

            # parse a request path & validate
            username = self.parse_request_path(self.path)

            if 'dateOfBirth' not in message.keys():
                raise HTTPException(400, 'dateOfBirth not found.')

            try:
                datetime_of_birth = datetime.datetime.strptime(
                    message["dateOfBirth"], '%Y-%m-%d')
                date_of_birth = datetime_of_birth.date()
            except ValueError as e:
                raise HTTPException(
                    400, '%s must be a valid YYYY-MM_DD date.' %
                    message["dateOfBirth"])

            if datetime.date.today() <= date_of_birth:
                raise HTTPException(
                    400, '%s must be a date before the today date.' %
                    date_of_birth.strftime('%Y-%m-%d'))

            c = DB.conn.cursor()

            # Upsert a user
            query = """INSERT OR REPLACE INTO user_test (username, date_of_birth) 
            VALUES ('%s', '%s')
            """ % (username, date_of_birth.strftime('%Y-%m-%d'))

            logging.info("Upsert a user with query %s" % query)

            try:
                c.execute(query)
                DB.conn.commit()
            except sqlite3.Error as e:
                logging.error("An error occurred:", e.args[0])
                self._send_501_response()

            self._send_response_code_and_headers(204)

        except json.JSONDecodeError as e:
            logging.error(e.msg)
            self._send_response(400, e.msg)
        except HTTPException as e:
            logging.error(e.code_description_and_message)
            self._send_http_exception_response(e)
        except Exception as e:
            logging.error("Error: {0}".format(str(e.args[0])))
            self._send_501_response("Error {0}".format(str(e.args[0])))
        except:
            logging.error("Unexpected error:", sys.exc_info()[0])
            self._send_501_response()
Esempio n. 30
0
def undo_invite(invite_id: str) -> Dict:
    if not mongo.remove_invite_by_id(invite_id):
        raise HTTPException("Incorrect invite identifier!", 400)

    return {}