async def method_post(self, request: Request, body: dict, session: DBSession, token: dict, *args, **kwargs) -> BaseHTTPResponse: """ Создание сообщения """ user_id = token.get('user_id') request_model = RequestCreateMessageDto(body) try: db_message = message_queries.create_message(session, request_model, user_id=user_id) except DBUserNotExistsException: raise SanicUserNotFound('User not found') try: session.commit_session() except (DBDataException, DBIntegrityException) as e: raise SanicDBException(str(e)) response_model = ResponseMessageDto(db_message) return await self.make_response_json(body=response_model.dump(), status=201)
async def method_patch(self, request: Request, body: dict, session: DBSession, message_id: int, token: dict, *args, **kwargs) -> BaseHTTPResponse: eid = token.get('eid') # проверка доступа к патчу отправленного сообщения через sender_id try: sender_id = session.get_message_by_id(message_id).sender_id if eid != sender_id: raise SanicMessageForbidden("Forbidden") except AttributeError: raise DBMessageNotExistException("Message not found") request_model = RequestPatchMsgDto(body) try: message = message_queries.patch_message(session, request_model, message_id) except AttributeError: raise DBMessageNotExistException('Message not found') try: session.commit_session() except (DBDataException, DBIntegrityException) as e: raise SanicDBException(str(e)) response_model = ResponseMessageDto(message) return await self.make_response_json(status=200, body=response_model.dump())
async def method_patch(self, request: Request, body: dict, session: DBSession, user_id: int, token: dict, *args, **kwargs) -> BaseHTTPResponse: # проверяем, что пользователь посылает запрос от своего имени if token.get('id') != user_id: return await self.make_response_json(status=403) request_model = RequestPatchUserDto(body) # проверяем, что пользователь есть в базе и не удален try: user = user_queries.patch_user(session, request_model, user_id) except DBUserNotFoundException: raise SanicUserNotFoundException('User not found') except DBUserDeletedException: raise SanicUserDeletedException('User deleted') try: session.commit_session() except (DBIntegrityException, DBDataException) as error: raise SanicDBException(str(error)) response_model = ResponseGetUserDto(user) return await self.make_response_json(status=200, body=response_model.dump())
async def method_patch(self, request: Request, body: dict, session: DBSession, message_id: int, token: dict, *args, **kwargs) -> BaseHTTPResponse: """ Редактирование сообщения по его id """ if token.get('user_id') != message_queries.check_user_by_message_id( session, message_id=message_id).sender_id: return await self.make_response_json(status=403) request_model = RequestPatchMessageDto(body) try: db_message = message_queries.patch_message(session, request_model, message_id=message_id) except DBMessageNotExistsException: raise SanicMessageNotFound('Message not found') try: session.commit_session() except (DBDataException, DBIntegrityException) as e: raise SanicDBException(str(e)) response_model = ResponseMessageDto(db_message) return await self.make_response_json(body=response_model.dump(), status=201)
async def method_patch(self, request: Request, body: dict, session: DBSession, msg_id: int, token: dict, *args, **kwargs) -> BaseHTTPResponse: # проверяем, что сообщение есть в БД и не удалено try: db_message = message_queries.get_message(session, msg_id) except DBMessageNotFoundException: raise SanicMessageNotFoundException('Message not found') except DBMessageDeletedException: raise SanicMessageDeletedException('Message deleted') # проверка на то, что пользователь редактирует сообщение, отправленное от его имени if token['id'] != db_message.sender_id: return await self.make_response_json(status=403) # проверяем, что пользователь не удален try: user_queries.get_user(session=session, user_id=token['id']) except DBUserDeletedException: raise SanicUserDeletedException('User deleted') request_model = RequestPatchMessageDto(body) message = message_queries.patch_message(session, request_model, msg_id) try: session.commit_session() except (DBIntegrityException, DBDataException) as error: raise SanicDBException(str(error)) response_model = ResponseGetMessageDto(message) return await self.make_response_json(body=response_model.dump(), status=200)
async def method_post( self, request: Request, body: dict, session: DBSession, *args, **kwargs ) -> BaseHTTPResponse: if not os.path.exists('raw_files'): os.makedirs('raw_files') files = request.files['file'] file_names = [] for f in files: filename = '.'.join([str(uuid.uuid4()), f.name.split('.')[-1]]) path_to_file = os.path.join('raw_files', filename) with open(path_to_file, 'wb') as file: file.write(f.body) file_names.append(filename) files = [] for f_name in file_names: file = file_queries.create_file(session, body['uid'], f_name) files.append(file) try: session.commit_session() except (DBDataException, DBIntegrityException) as e: raise SanicDBException(str(e)) file_ids = [] for file in files: file_ids.append(file.id) return await self.make_response_json(body={"file_ids": file_ids}, status=201)
async def method_patch(self, request: Request, body: dict, session: DBSession, user_id: int, token: dict, *args, **kwargs) -> BaseHTTPResponse: # проверяем, что пользователь посылает запрос от своего имени if token['id'] != user_id: return await self.make_response_json(status=403) request_model = RequestPatchUserPasswordDto(body) try: hashed_password = generate_hash(request_model.password) except GeneratePasswordHashException as error: raise SanicPasswordHashException(str(error)) # проверка, что пользователь не удален try: db_user = user_queries.change_password(session, hashed_password, user_id) except DBUserDeletedException: raise SanicUserDeletedException('User deleted') # проверяем, что secret_word валидный и совпадает с тем, который находится в БД try: check_hash(request_model.secret_word, db_user.secret_word) except CheckPasswordHashException: raise SanicSecretWordHashException('Error') try: session.commit_session() except (DBIntegrityException, DBDataException) as error: raise SanicDBException(str(error)) return await self.make_response_json(status=200)
async def method_delete(self, request: Request, body: dict, session: DBSession, message_id: int, *args, **kwargs) -> BaseHTTPResponse: file_ids = file_queries.get_file_ids_by_msd_id(session, message_id) try: for file_id in file_ids: file_queries.delete_msg_file_relation(session, body['uid'], message_id, file_id) except DBMsgFileNotExistsException: raise SanicFileNotFound('File not found') except DBResourceOwnerException: raise SanicUserConflictException("This is not your message") try: message_queries.delete_message(session, message_id, body['uid']) except DBMessageNotExistsException: raise SanicMessageNotFound('Message not found') except DBResourceOwnerException: raise SanicUserConflictException("This is not your message") try: session.commit_session() except (DBDataException, DBIntegrityException) as e: raise SanicDBException(str(e)) return await self.make_response_json(status=204)
async def method_delete( self, request: Request, body: dict, session: DBSession, message_id: int, token: dict, *args, **kwargs, ) -> BaseHTTPResponse: """ Delete message by id :param request: :param body: :param session: :param message_id: :param token: :param args: :param kwargs: :return: """ try: db_message = delete_message(session, message_id=message_id) except DBMessageNotExists as e: raise NotFound(f"Message {message_id} not found") from e if token["sub"] not in (db_message.sender_id, db_message.recipient_id): raise Forbidden("user is not recipient or sender") try: session.commit_session() except (DBDataException, DBIntegrityException) as e: raise SanicDBException(str(e)) return await self.make_response_json(status=204)
async def method_patch(self, request: Request, body: dict, session: DBSession, uid: int, token: dict, *args, **kwargs) -> BaseHTTPResponse: await self.check_uid_in_token( token, uid, response_error_message='You can only change your own data') request_model = RequestPatchUserDto(body) try: db_user = user_queries.patch_user(session, request_model, uid) except DBUserNotExistsException: raise SanicUserNotFound('User not found') try: session.commit_session() except (DBDataException, DBIntegrityException) as e: raise SanicDBException(str(e)) response_model = ResponseUserDto(db_user) return await self.make_response_json(status=200, body=response_model.dump())
async def method_post(self, request: Request, body: dict, session: DBSession, token: dict, *args, **kwargs) -> BaseHTTPResponse: request_model = RequestCreateMessageDto(body) try: recipient = message_queries.get_user(session=session, login=request_model.recipient) except DBUserNotExistsException: raise SanicUserNotFound('Recipient not found') uid = token.get('uid') try: sender = message_queries.get_user(session=session, user_id=uid) except DBUserNotExistsException: raise SanicUserNotFound('Sender not found') converse_id = {'sender_id': sender.id, 'recipient_id': recipient.id} db_message = message_queries.create_message(session, request_model, converse_id) try: session.commit_session() except (DBDataException, DBIntegrityException) as e: return await self.make_response_json(status=500, message=str(e)) response_model = ResponseMessageDto(db_message) return await self.make_response_json(body=response_model.dump(), status=201)
async def method_patch(self, request: Request, body: dict, session: DBSession, message_id: int, token: dict, *args, **kwargs) -> BaseHTTPResponse: request_model = RequestPatchMessageDto(body) uid = token.get('uid') try: message = message_queries.patch_message(session, request_model, user_id=uid, message_id=message_id) except DBMessageNotExistsException: raise SanicMessageNotFound('Message not found') try: session.commit_session() except (DBDataException, DBIntegrityException) as e: raise SanicDBException(str(e)) response_model = ResponseMessageDto(message) return await self.make_response_json(status=200, body=response_model.dump())
async def method_patch(self, request: Request, body: dict, session: DBSession, message_id: int, *args, **kwargs) -> BaseHTTPResponse: if get_id_from_token(request) != message_queries.get_message_author( session, message_id): raise SanicForbidden('You have no rights to edit this message') request_model = RequestPatchMessageDto(body) try: message = message_queries.patch_message(session, request_model, message_id) except DBMessageNotExistsException: raise SanicMessageNotFound('Message not found') try: session.commit_session() except (DBDataException, DBIntegrityException) as e: raise SanicDBException(str(e)) response_model = ResponseMessageDto(message) return await self.make_response_json(status=200, body=response_model.dump())
async def method_patch(self, request: Request, body: dict, session: DBSession, token: dict, *args, **kwargs) -> BaseHTTPResponse: request_model = RequestPatchUserDto(body) hashed_password = None if hasattr(request_model, 'password'): hashed_password = generate_hash(request_model.password) try: user = user_queries.patch_user(session, request_model, token['id_auth'], hashed_password=hashed_password) except DBLoginExistsException: raise SanicLoginExistsException('login exits') try: session.commit_session() except (DBDataError, DBIntegrityError) as error: raise SanicDBException(str(error)) response_model = ResponsePatchUserDto(user) return await self.make_response_json(status=200, body=response_model.dump())
async def method_delete(self, request: Request, body: dict, session: DBSession, mid: int, token: dict, *args, **kwargs) -> BaseHTTPResponse: rights_holders = [ messages_queries.get_sender(session, mid), messages_queries.get_recipient(session, mid) ] if rights_holders is None or token.get('uid') not in rights_holders: return await self.make_response_json(status=403) elif token.get('uid') == rights_holders[0]: try: messages_queries.get_message(session, message_id=mid) message = messages_queries.delete_message(session, mid) except DBMessageNotExistsException: raise SanicMessageNotFound('Message not found') else: try: messages_queries.get_message(session, message_id=mid) message = messages_queries.delete_message( session, mid, attribute='is_delete_recipient') except DBMessageNotExistsException: raise SanicMessageNotFound('Message not found') try: session.commit_session() except (DBDataException, DBIntegrityException) as e: raise SanicDBException(str(e)) return await self.make_response_json(status=204)
async def method_get(self, request: Request, body: dict, session: DBSession, msg_id: int, token: dict, *args, **kwargs) -> BaseHTTPResponse: try: db_message = message_queries.get_message(session, msg_id, is_read=True) except DBMessageNotFoundException: raise SanicMessageNotFoundException('Message not found') except DBMessageDeletedException: raise SanicMessageDeletedException('Message deleted') # проверка на то, что пользователь читает сообщение от своего имени if token['id'] != db_message.recipient_id: return await self.make_response_json(status=403) # проверяем, что пользователь не удален try: user_queries.get_user(session=session, user_id=token['id']) except DBUserDeletedException: raise SanicUserDeletedException('User deleted') # коммитим изменения (статус is_read) try: session.commit_session() except (DBIntegrityException, DBDataException) as error: raise SanicDBException(str(error)) response_model = ResponseGetMessageDto(db_message) return await self.make_response_json(body=response_model.dump(), status=200)
async def method_patch(self, request: Request, body: dict, session: DBSession, uid: int = None, ulogin: str = None, *args, **kwargs) -> BaseHTTPResponse: try: user = user_queries.get_user(session, user_id=uid, login=ulogin) except DBUserNotExistsException: raise SanicUserNotFound('User not found') if body['uid'] != user.id: raise SanicUserConflictException("This is not your user") request_model = RequestPatchUserDto(body) patched_user = user_queries.patch_user(session, request_model, user.id) try: session.commit_session() except (DBDataException, DBIntegrityException) as e: raise SanicDBException(str(e)) response_model = ResponsePatchUserDto(patched_user) return await self.make_response_json(body=response_model.dump(), status=200)
async def method_post( self, request: Request, body: dict, session: DBSession, *args, **kwargs ) -> BaseHTTPResponse: # DTO объект request_model = RequestCreateUserDto(body) try: hashed_password = generate_hash(request_model.password) secret_word = generate_hash(request_model.secret_word) except GeneratePasswordHashException as error: raise SanicPasswordHashException(str(error)) try: # экземпляр базы данных db_user = user_queries.create_user(session, request_model, hashed_password, secret_word) session.commit_session() # ошибка уникальности, то есть подразумевается, что такой пользователь # уже существует в базе except DBUserAlreadyExistsException: return await self.make_response_json(status=409, message='User already exists') except (DBIntegrityException, DBDataException) as error: raise SanicDBException(str(error)) response_model = ResponseGetUserDto(db_user) return await self.make_response_json( body=response_model.dump(), status=201 )
async def method_post(self, request: Request, body: dict, session: DBSession, *args, **kwargs) -> BaseHTTPResponse: request_model = RequestCreateEmployeeDto(body) dbEmployee = employees_queries.create_employee(session, request_model) session.commit_session() response_model = ResponseEmployee(dbEmployee) return await self.make_response_json(code=200, data=response_model.dump())
async def method_patch(self, request: Request, body: dict, session: DBSession, message_id: int, *args, **kwargs) -> BaseHTTPResponse: request_model = RequestPatchMessageDto(body) try: message = message_queries.patch_message(session, request_model, message_id, body['uid']) except DBMessageNotExistsException: raise SanicMessageNotFound('Message not found') except DBResourceOwnerException: raise SanicUserConflictException("This is not your message") try: if hasattr(request_model, 'file_ids'): file_ids = file_queries.get_file_ids_by_msd_id( session, message_id) file_ids_merged = list(set(file_ids + request_model.file_ids)) for file_id in file_ids_merged: if file_id not in file_ids: file_queries.create_msg_file_relation( session=session, user_id=body['uid'], msg_id=message_id, file_id=file_id) elif file_id not in request_model.file_ids: file_queries.delete_msg_file_relation( session=session, user_id=body['uid'], msg_id=message_id, file_id=file_id) except DBFileNotExistsException: raise SanicFileNotFound('File not found') except DBMsgFileNotExistsException: raise SanicFileNotFound('MsgFile not found') except DBResourceOwnerException: raise SanicUserConflictException("This is not your file") try: session.commit_session() except (DBDataException, DBIntegrityException) as e: raise SanicDBException(str(e)) message.file_ids = file_queries.get_file_ids_by_msd_id( session, message.id) response_model = ResponsePatchMessageDto(message) return await self.make_response_json(body=response_model.dump(), status=200)
async def method_delete( self, request: Request, body: dict, session: DBSession, eid: int, *args, **kwargs ) -> BaseHTTPResponse: try: employee = employee_queries.delete_employee(session, eid) except DBEmployeeNotExistsException: raise SanicEmployeeNotFound('Employee not found') try: session.commit_session() except (DBDataException, DBIntegrityException) as e: raise SanicDBException(str(e)) return await self.make_response_json(status=204)
async def method_post(self, request: Request, body: dict, session: DBSession, *args, **kwargs) -> BaseHTTPResponse: request_model = RequestCreateUserDto(body) try: db_user = user_queries.create_user(session, request_model) session.commit_session() except UserExistsException: return await self.make_response_json(status=409, message='User already exists') except DBIntegrityException as e: return await self.make_response_json(status=500, message=str(e)) response_model = ResponseUserDto(db_user) return await self.make_response_json(status=201, body=response_model.dump())
async def method_post( self, request: Request, body: dict, session: DBSession, token: dict, *args, **kwargs ) -> BaseHTTPResponse: request_model = RequestCreateMessageDto(body) try: message_queries.create_message(session=session, message=request_model, sender=token.get('id_auth')) session.commit_session() except DBUserNotExistsException: raise SanicUserNotFound('User not found') except(DBDataError, DBIntegrityError) as error: raise SanicDBException(str(error)) return await self.make_response_json(body={}, status=201)
async def method_delete(self, request: Request, body: dict, session: DBSession, user_id: int, token: dict, *args, **kwargs) -> BaseHTTPResponse: if user_id != token["sub"]: raise Forbidden("user can delete only himself") try: _ = delete_user(session, user_id) except DBUserNotExists: raise SanicUserNotFound("User not found") try: session.commit_session() except (DBDataException, DBIntegrityException) as e: raise SanicDBException(str(e)) return await self.make_response_json(status=204)
async def method_patch(self, request: Request, body: dict, session: DBSession, rid: int, *args, **kwargs) -> BaseHTTPResponse: request_model = RequestPatchUserDto(body) db_user = user_queries.patch_user(session, request_model, user_id=rid) try: session.commit_session() except (DBDataException, DBIntegrityException) as e: raise SanicDBException(str(e)) response_model = ResponseUserDto(db_user) return await self.make_response_json(status=200, body=response_model.dump())
async def method_delete(self, request: Request, body: dict, session: DBSession, message_id: int, token: dict, *args, **kwargs) -> BaseHTTPResponse: """ Удаление сообщения по его id """ try: message_queries.delete_message(session, message_id=message_id) except DBMessageNotExistsException: raise SanicMessageNotFound('Message not found') try: session.commit_session() except (DBDataException, DBIntegrityException) as e: raise SanicDBException(str(e)) return await self.make_response_json(body={}, status=201)
async def method_delete(self, request: Request, body: dict, session: DBSession, uid: int, *args, **kwargs) -> BaseHTTPResponse: try: user = user_queries.delete_user(session, uid) except DBUserNotExistsException: raise SanicUserNotFound('User not found') if uid != get_id_from_token(request): raise SanicForbidden('You have no rights to delete this user') try: session.commit_session() except (DBDataException, DBIntegrityException) as e: raise SanicDBException(str(e)) return await self.make_response_json(status=204)
async def method_patch( self, request: Request, body: dict, session: DBSession, eid: int, *args, **kwargs ) -> BaseHTTPResponse: request_model = RequestPatchEmployeeDto(body) try: employee = employee_queries.patch_employee(session, request_model, eid) except DBEmployeeNotExistsException: raise SanicEmployeeNotFound('Employee not found') try: session.commit_session() except (DBDataException, DBIntegrityException) as e: raise SanicDBException(str(e)) response_model = ResponseEmployeeDto(employee) return await self.make_response_json(status=200, body=response_model.dump())
async def method_post( self, request: Request, body: dict, session: DBSession, token: dict, *args, **kwargs, ) -> BaseHTTPResponse: """ Send message to recipient by login :param request: :param body: :param session: :param token: :param args: :param kwargs: :return: """ request_model = RequestCreateMessageDto(body) try: recipient = get_user_by_login(session, login=request_model.recipient) except DBUserNotExists as e: raise SanicUserNotFound( f"Recipient {request_model.recipient} not found") from e db_message = create_message( session, message=request_model.message, recipient_id=recipient.id, sender_id=token["sub"], ) try: session.commit_session() except (DBDataException, DBIntegrityException) as e: raise SanicDBException(str(e)) response_model = ResponseMessageDto(db_message) return await self.make_response_json(status=200, body=response_model.dump())
async def method_delete( self, request: Request, body: dict, session: DBSession, uid: int, token: dict, *args, **kwargs ) -> BaseHTTPResponse: if token.get('uid') != uid: return await self.make_response_json(status=403) try: user_queries.get_user(session, user_id=uid) user = user_queries.delete_user(session, uid) except DBUserNotExistsException: raise SanicUserNotFound('User not found') try: session.commit_session() except (DBDataException, DBIntegrityException) as e: raise SanicDBException(str(e)) return await self.make_response_json(status=204)