def _generate_key(self, salt=""): sha = hashlib.sha256() sha.update(u.sanitize(self.commission_type.strip()).encode(ENCODING)) sha.update(u.sanitize(self.client.strip()).encode(ENCODING)) sha.update(self.reference_id.strip().encode(ENCODING)) sha.update(str(salt).encode(ENCODING)) return sha.hexdigest()
def _generate_key(self, salt=''): sha = hashlib.sha256() sha.update(u.sanitize(self.commission_type).encode(ENCODING)) sha.update(u.sanitize(self.client).encode(ENCODING)) sha.update(u.sanitize(self.referrer).encode(ENCODING)) sha.update(str(salt).encode(ENCODING)) return sha.hexdigest()
def process_comparison(self): if self.pair is None: return None workbook = self.create_workbook(OUTPUT_DIR_ABA) worksheet = workbook.add_worksheet('ABA Comparison Results') fmt_error = get_error_format(workbook) row = 0 col_a = 0 col_b = 13 keys_unmatched = set(self.pair.datarows.keys()) - set( self.datarows.keys()) for key in self.datarows.keys(): self_row = self.datarows[key] pair_row = self.pair.datarows.get(key, None) if pair_row is None: worksheet.write_row(row, col_a, self_row, fmt_error) error = new_error(self.filename, self.pair.filename, f'No match found for row', '', '', ' '.join(self_row)) self.summary_errors.append(error) else: for index, value in enumerate(self_row): format_ = None if u.sanitize(value) == u.sanitize( pair_row[index]) else fmt_error worksheet.write(row, index, value, format_) worksheet.write(row, index + col_b, pair_row[index], format_) if value != pair_row[index]: column = self.get_column(value[0], index) error = new_error( self.filename, self.pair.filename, f'Values of {column} does not match', '', '', value, pair_row[index]) self.summary_errors.append(error) row += 1 for key in keys_unmatched: worksheet.write_row(row, col_b, self.pair.datarows[key], fmt_error) error = new_error(self.filename, self.pair.filename, f'No match found for row', '', '', '', ' '.join(self.pair.datarows[key])) self.summary_errors.append(error) row += 1 if len(self.summary_errors) > 0: workbook.close() else: del workbook return self.summary_errors
def edit_my_entry(url): """Редактировать заявку на джем от текущего пользователя""" user = get_user_from_request() jam = Jam.get_or_none(Jam.url == url) if jam is None: return errors.not_found() entry = JamEntry.get_or_none(jam=jam, creator=user) if entry is None: return errors.not_found() json = request.json title = json.get("title", entry.title) url = json.get("url", entry.url) description = json.get("info", entry.info) short_description = json.get("short_info", entry.short_info) links = json.get("links", []) has_entry_with_same_url = False entries_with_same_url = JamEntry.select().where((JamEntry.url == url) & (JamEntry.jam == jam)) for e in entries_with_same_url: if e.id != entry.id: has_entry_with_same_url = True if has_entry_with_same_url: return errors.jam_entry_url_already_taken() image = None if "logo" in json: image = json["logo"] entry.title = title entry.url = url entry.info = sanitize(description) entry.short_info = sanitize(short_description) if image: entry.logo = Content.get_or_none(Content.id == image) JamEntryLink.delete().where(JamEntryLink.entry == entry).execute() for link in links: JamEntryLink.create( entry=entry, title=link["title"], href=link["href"], order=link["order"], ) entry.save() return jsonify({"success": 1, "entry": _entry_to_json(entry)})
def create_jam(): """Создать джем""" user = get_user_from_request() json = request.json required_fields = ["title", "url", "description", "short_description"] missed_fields = [] for field in required_fields: if field not in json: missed_fields.append(field) if len(missed_fields) > 0: return errors.wrong_payload(missed_fields) title = json["title"] url = json["url"] description = json["description"] short_description = json["short_description"] image = json.get("logo", None) start_date = json.get("start_date", None) end_date = json.get("end_date", None) criterias = json.get("criterias", []) if Jam.get_or_none(Jam.url == url) is not None: return errors.jam_url_already_taken() blog = create_blog_for_jam(user, title, url, image) jam = Jam.create( created_date=datetime.datetime.now(), updated_date=datetime.datetime.now(), creator=user, blog=blog, title=title, url=url, short_description=sanitize(short_description), description=sanitize(description), start_date=start_date, end_date=end_date, ) if image: jam.logo = Content.get_or_none(Content.id == image) jam.save() for criteria in criterias: JamCriteria.create(jam=jam, title=criteria["title"], order=criteria["order"]) return jsonify({"success": 1, "jam": jam.to_json()})
def current_user(): """Получить текущего пользователя или отредактировать профиль""" user = get_user_from_request() if request.method == "POST": json = request.get_json() user.email = json.get("email", user.email) user.name = json.get("name", user.name) user.about = sanitize(json.get("about", user.about)) user.birthday = json.get("birthday", user.birthday) if "avatar" in json: content = Content.get_or_none(Content.id == json["avatar"]) if content: if not content.is_image: return errors.user_avatar_is_not_image() elif content.size > 1024 * 500: # 500kb return errors.user_avatar_too_large() else: user.avatar = content user.save() user = User.get(User.id == user.id) return jsonify({"success": 1, "user": user.to_json_with_email()})
def edit_comment_in_entry(url, entry_url, comment_id): """Редактировать комментарий""" jam = Jam.get_or_none(Jam.url == url) if jam is None: return errors.not_found() entry = JamEntry.get_or_none(JamEntry.url == entry_url) if entry is None: return errors.not_found() user = get_user_from_request() if user is None: return errors.not_authorized() json = request.get_json() text = None if "text" in json: text = sanitize(json.get("text")) else: return errors.wrong_payload("text") comment = _edit_comment(comment_id, user, text) return jsonify({"success": 1, "comment": comment.to_json()})
def test_sanitize(): html = '<p><strong><span style="color:rgb(59, 67, 81);">Жирный текст</span></strong></p><p><em>Нихрена себе тут интервалы между строками, зачем так много?</em></p><p><u>Подчёркнутый</u></p><p><s>Зачёркнутый</s></p><p>Параграф? Что делает кнопка "Параграф" в нашем редакторе вообще? Она как будто нажата и не отжимается.</p><p><span style="color:rgb(255, 178, 67);">Ну цвет текста, это понятно. Только выглядит как пипетка - кажется будто можно её взять и подобрать цвет со скриншота сайта или какой-то загруженной картинки. Странновато чуть.</span></p><h1>Заголовок 1</h1><h2>2</h2><h3>3</h3><h4>4</h4><h5>5</h5><h6>6</h6><p>Хотелось бы чтоб панель инструментов WYSIWYG-редактора скроллилась вниз по мере увеличения текста поста. А то вот досюда допечатал и уже надо скроллить обратно наверх каждый раз. Или чтоб она дублировалась внизу поста. Но это хуже, т. к. в середине поста её всё равно не будет.</p><p>Для первого теста хватит, думаю.</p><p>И я почему-то не могу выбрать опубликовать пост в блог "На Коленке". Чё это?</p>' # noqa new_html = sanitize(html) assert len(html) == len(new_html) - 2 # -2 for added spaces in styles html = '<h2><div style="text-align:right;">hey bois</div></h2><ol><li><p>this is mu</p><table><tbody><tr><td><p></p></td><td><p></p><div style="text-align:center;">Привет</div><p></p></td><td><p></p></td></tr><tr><td><p>Это пример</p></td><td><p></p></td><td><p></p></td></tr><tr><td><p></p></td><td><p></p></td><td><p>Таблицы</p></td></tr></tbody></table></li></ol>' # noqa new_html = sanitize(html) assert len(html) == len(new_html) - 2 # -2 for added spaces in styles html = "http://veloc1.me" new_html = sanitize(html) assert new_html == '<a href="http://veloc1.me" rel="nofollow">http://veloc1.me</a>' html = "<p>Some text</p><cut></cut>" new_html = sanitize(html) assert new_html == "<p>Some text</p><cut></cut>"
def edit_jam(url): """Редактировать джем""" user = get_user_from_request() jam = Jam.get_or_none(Jam.url == url) if jam is None: return errors.not_found() if jam.creator != user: return errors.no_access() json = request.json title = json.get("title", jam.title) # url = json.get("url", jam.url) description = json.get("description", jam.description) short_description = json.get("short_description", jam.short_description) start_date = json.get("start_date", jam.start_date) end_date = json.get("end_date", jam.end_date) criterias = json.get("criterias", []) image = None if "image" in json: image = json["image"] edit_blog_for_jam(jam.blog, title, url, image) jam.title = title # jam.url = url jam.description = sanitize(description) jam.short_description = sanitize(short_description) jam.start_date = start_date jam.end_date = end_date if image: jam.logo = Content.get_or_none(Content.id == image) jam.updated_date = datetime.datetime.now() jam.save() JamCriteria.delete().where(JamCriteria.jam == jam).execute() for criteria in criterias: JamCriteria.create(jam=jam, title=criteria["title"], order=criteria["order"]) return jsonify({"success": 1, "jam": jam.to_json()})
def fill_blog_from_json(blog, json): if json is not None: blog.title = json.get("title", blog.title) blog.description = sanitize(json.get("description", blog.description)) blog.url = json.get("url", blog.url) blog.blog_type = json.get("blog_type", blog.blog_type) if "image" in json: blog.image = Content.get_or_none(Content.id == json["image"]) blog.updated_date = datetime.datetime.now()
def parse(self): file = open(self.full_path, 'r') for index, line in enumerate(file.readlines()): if line.startswith('0'): aba_line = self.parse_line_type_0(line) key = u.sanitize(''.join(aba_line)) self.datarows[key] = aba_line elif line.startswith('1'): aba_line = self.parse_line_type_1(line) key = u.sanitize(aba_line[7]) self.datarows[key] = aba_line elif line.startswith('7'): aba_line = self.parse_line_type_7(line) key = u.sanitize(''.join(aba_line)) self.datarows[key] = aba_line else: msg = f'There is an invalid ABA line on line {index}' error = new_error(self.filename, self.pair.filename, msg) self.summary_errors.append(error)
def _edit_comment(comment_id, user, text): comment = Comment.get_or_none(Comment.id == comment_id) if comment is None: return errors.not_found() is_accessible = user.is_admin or comment.creator == user if not is_accessible: return errors.no_access() comment.text = sanitize(text) comment.save() return comment
def equals(self, obj): if type(obj) != BrokerInvoiceRow: return False return ( u.sanitize(self.commission_type) == u.sanitize(obj.commission_type) and u.sanitize(self.client) == u.sanitize(obj.client) and u.sanitize(self.reference_id) == u.sanitize(obj.reference_id) and u.sanitize(u.bank_fullname(self.bank)) == u.sanitize( u.bank_fullname(obj.bank)) and self.compare_numbers( self.loan_balance, obj.loan_balance, self.margin) and self.compare_numbers(self.amount_paid, obj.amount_paid, self.margin) and self.compare_numbers(self.gst_paid, obj.gst_paid, self.margin) and self.compare_numbers(self.total_amount_paid, obj.total_amount_paid, self.margin))
def fill_post_from_json(post, json): if json is not None: post.title = json.get("title", post.title) post.text = sanitize(json.get("text", post.text)) if post.text is not None: cut_info = process_cut(post.text) post.has_cut = cut_info["has_cut"] post.cut_text = cut_info["text_before_cut"] post.cut_name = cut_info["cut_name"] post.is_draft = json.get("is_draft", post.is_draft) post.url = json.get("url", post.url) post.updated_date = datetime.datetime.now()
def equals(self, obj): if type(obj) != ReferrerInvoiceRow: return False return ( u.sanitize(self.commission_type) == u.sanitize(obj.commission_type) and u.sanitize(self.client) == u.sanitize(obj.client) and u.sanitize(self.referrer) == u.sanitize(obj.referrer) and self.compare_numbers(self.amount_paid, obj.amount_paid, self.margin) and self.compare_numbers(self.gst_paid, obj.gst_paid, self.margin) and self.compare_numbers(self.total, obj.total, self.margin) )
def _add_comment(type, object_id, user, text, parent_comment_id=None): text = sanitize(text) parent = None level = 0 if parent_comment_id: parent = Comment.get_or_none(Comment.id == parent_comment_id) if parent is not None: level = parent.level + 1 comment = Comment.create( object_type=type, object_id=object_id, created_date=datetime.datetime.now(), updated_date=datetime.datetime.now(), creator=user, text=text, parent=parent, level=level, ) return comment
def equal_abn(self): if self.pair is None: return False return u.sanitize(self.abn) == u.sanitize(self.pair.abn)
def comments(url): """Получить список комментариев для поста или добавить новый комментарий""" post = Post.get_or_none(Post.url == url) if post is None: return errors.not_found() if request.method == "GET": user = get_user_from_request() if post.is_draft: if user is None: return errors.no_access() if post.creator != user: return errors.no_access() return _get_comments("post", post.id, user) elif request.method == "POST": user = get_user_from_request() if user is None: return errors.not_authorized() json = request.get_json() if "text" in json: text = sanitize(json.get("text")) else: return errors.wrong_payload("text") parent_id = None if "parent" in json: parent_id = json["parent"] parent = None if parent_id: parent = Comment.get_or_none(Comment.id == parent_id) comment = _add_comment("post", post.id, user, text, parent_id) if user.id != post.creator.id: t = "Пользователь {0} оставил комментарий к вашему посту {1}: {2}" notification_text = t.format(user.visible_name, post.title, text) Notification.create( user=post.creator, created_date=datetime.datetime.now(), text=notification_text, object_type="comment", object_id=comment.id, ) if parent is not None: if user.id != parent.creator.id: t = "Пользователь {0} ответил на ваш комментарий {1}: {2}" notification_text = t.format(user.visible_name, parent.text, text) Notification.create( user=parent.creator, created_date=datetime.datetime.now(), text=notification_text, object_type="comment", object_id=comment.id, ) return jsonify({"success": 1, "comment": comment.to_json()})
def equal_commission_type(self): if self.pair is None: return False return u.sanitize(self.commission_type) == u.sanitize(self.pair.commission_type)
def equal_client(self): if self.pair is None: return False return u.sanitize(self.client) == u.sanitize(self.pair.client)
def equal_referrer(self): if self.pair is None: return False return u.sanitize(self.referrer) == u.sanitize(self.pair.referrer)
def equal_to(self): if self.pair is None: return False return u.sanitize(self.to) == u.sanitize(self.pair.to)
def equal_from(self): if self.pair is None: return False return u.sanitize(self.from_) == u.sanitize(self.pair.from_)
def equal_comments(self): if self.pair is None: return False return u.sanitize(self.comments) == u.sanitize(self.pair.comments)
def equal_bank(self): if self.pair is None: return False bank_a = u.bank_fullname(self.bank) bank_b = u.bank_fullname(self.pair.bank) return u.sanitize(bank_a) == u.sanitize(bank_b)
def equal_account(self): if self.pair is None: return False return u.sanitize(self.account) == u.sanitize(self.pair.account)
def equal_bsb(self): if self.pair is None: return False return u.sanitize(self.bsb) == u.sanitize(self.pair.bsb)
def test_sanitize(value, expected): sanitized_value = utils.sanitize(value) assert sanitized_value == expected