def validate_user_registration_form(json: dict): try: username = json['username'] username_valid = checkers.is_not_empty( username) and checkers.is_string(username) and checkers.has_length( username, minimum=1, maximum=20) except TypeError: username_valid = False try: password = json['password'] password_valid = checkers.is_not_empty( password) and checkers.is_string(password) and checkers.has_length( password, minimum=1, maximum=128) except TypeError: password_valid = False try: email = json['email'] email_valid = checkers.is_email(email) except TypeError: email_valid = False invalid_fields = [] if not username_valid: invalid_fields.append(InvalidField('username', 'Invalid username')) if not password_valid: invalid_fields.append(InvalidField('password', 'Invalid password')) if not email_valid: invalid_fields.append(InvalidField('email', 'Invalid email')) if not (username_valid & password_valid & email_valid): raise InvalidForm(invalid_fields) return username, email, password
def signup_validator(fullname, username, email, password, password2): errors = [] if email and checkers.is_email(email): check_email = User.query.filter_by(email=email).first() if not check_email: pass else: errors.append("An account is already registred with this email.") else: errors.append("Email is invalid.") if password and is_valid_password(password): if password2 is not None and password == password2: pass else: errors.append("Passwords do not match") else: errors.append("Password is invalid: must be 8 characters minimum and a mixture of both letters and numbers.") if fullname and checkers.is_string(fullname) and is_valid_fullname(fullname): pass else: errors.append("Fullname is invalid: must be three characters minimum and cannot have any special characters.") if username and checkers.is_string(username) and is_valid_username(username): check_username = User.query.filter_by(username=username).first() if not check_username: pass else: errors.append("This username is already taken. Please try another.") else: errors.append("Username is invalid. Usernames must be 4 characters minimum and must have only letters, numbers, and/ or underscores") if len(errors) == 0: return True, errors if len(errors) > 0: return False, errors
def comment(): title = "Lang & Code - Comment" if request.method == "POST": post_id = request.form.get("postId") comment_body = request.form.get("commentBody") if post_id and comment_body and checkers.is_string( comment_body) and len(comment_body) >= 10: article = Post.query.get(post_id) author = User.query.get(article.user_id) if article and author: comment = Comment(user_id=current_user.id, article_id=post_id, body=comment_body, approved=True) db.session.add(comment) db.session.commit() flash("Comment added successfully!", "is-primary") return redirect(url_for('article.show_articles', id=post_id)) flash( "Comment could not be added. Either post was not found or you cannot comment on it.", "is-primary") return redirect(url_for('article.articles')) flash( "Some of your input data were not valid. Please check again and then submit.", "is-warning") flash("Comment must be a string of 10 characters at least.") return redirect(url_for('article.show_articles', id=post_id)) flash("You do not have enough permission to comment on articles.", "is-warning") return redirect(url_for('article.show_articles', id=post_id))
def edit_profile(): title = "Lang & Code - Edit Profile" if request.method == "POST": _csrf_token = request.form.get("_csrf_token") username = request.form.get("username") about_me = request.form.get("aboutMe") print(username, about_me) if username is not None and username != current_user.username: if is_valid_username(username): if contains_swear_words(username): return jsonify(message='- You cannot use swear words in your username.', codename=0) new_username = User.query.filter_by(username=username).first() if new_username: return jsonify(message='- A user already exist with this username.', codename=0) else: current_user.username = username current_user.about_me = about_me db.session.commit() return jsonify(message='- Your changes have been saved.', codename=1) return jsonify(message='- Username is invalid. ' 'Usernames must be 4 characters minimum and must have only letters, numbers, dots or underscores', codename=0) if about_me and checkers.is_string(about_me): if contains_swear_words(about_me): return jsonify(message='- You cannot use swear words in your bio.', codename=0) if len(about_me) > 200: return jsonify(message='- Your About Me must not execeed 200 characters.') current_user.about_me = about_me db.session.commit() return jsonify(message='- Your changes have been saved.', codename=1) return jsonify(message='- Please verify your inputs', codename=0) flash("You must be logged in to access the page you requested." , "is-danger") return redirect(url_for('main.index'))
def pop(self, animeTitleOrAliasOrTag=''): ## check if string is an alias or a title animeTitle = self.getTitleFromAlias(animeTitleOrAliasOrTag) if animeTitle: currEpNum = self.getCurrEpNumber(animeTitle) currEpLink = self.getEpisodeFromTitle(animeTitle, currEpNum) if currEpLink: self.incrementStack(animeTitle) return (currEpLink, currEpNum, animeTitle) return (None, None, None) ## assuming the string is a tag tag = animeTitleOrAliasOrTag if checkers.is_string(tag, minimum_length=1): popOrder = self.tagPrioManager.getAnimeSequence(tag) else: allAvaliableTitles = self.anime_ep.keys() popOrder = self.numPrioManager.getAnimeSequence(allAvaliableTitles) # TODO make this a function self.logger.debug('pop: poporder is: {0}'.format(popOrder)) for anime in popOrder: currEpNum = self.getCurrEpNumber(anime) currEpLink = self.getEpisodeFromTitle(anime, currEpNum) if currEpLink: self.incrementStack(anime) return (currEpLink, currEpNum, anime) return (None, None, None)
def notes_validator(title, body, color, tags): errors = list() if title: if not is_empty(title, minimum=1): pass else: errors.append("Title is invalid. Must be a string of 1 characters minimum.") if body and not is_empty(body, minimum=1): pass else: errors.append("Body is invalid: must be 1 characters minimum.") if color: if not checkers.is_string(color): pass else: errors.append("Color is invalid. Must be string.") if tags: if not is_empty(tags, minimum=2): pass else: errors.append("Tags is invalid. Must be at least one tag of two characters minimum.") if len(errors) == 0: return True, errors if len(errors) > 0: return False, errors
def is_valid_password(self, input): if not checkers.is_string(input): return False if not checkers.has_length(input, minimum=8): return False if not (re.search("[a-z]", input) and re.search("[A-Z]", input) and re.search("[0-9]", input)): return False return True
def is_valid_username(self, input): if not checkers.is_string(input): return False if not checkers.has_length(input, minimum=6): return False if not re.search("[a-z]", input): return False return True
def to_utf8(value): """Return a UTF-8 encoded version of ``value`` if ``value`` is a string. :returns: ``value`` if ``value`` is not a string or UTF-8 encoded :class:`str <python:str>` """ if is_py2 and checkers.is_string(value, coerce_value=True): value = validators.string(value, coerce_value=True) return value.encode("utf-8") return value
def validate_user_login_form(json: dict): try: username = json['username'] username_valid = checkers.is_not_empty( username) and checkers.is_string(username) except TypeError: username_valid = False try: password = json['password'] password_valid = checkers.is_not_empty( password) and checkers.is_string(password) except TypeError: password_valid = False invalid_fields = [] if not username_valid: invalid_fields.append(InvalidField('username', 'Invalid username')) if not password_valid: invalid_fields.append(InvalidField('password', 'Invalid password')) if not (username_valid & password_valid): raise InvalidForm(invalid_fields) return username, password
def article_validator(article_title, article_body, article_category, article_tags, article_language_option, article_publication_option): errors = [] if article_title and checkers.is_string(article_title) and len(article_title) >= 10 and not article_title.isspace(): pass else: errors.append("Title is invalid. Must be a string of 10 characters at least.") if article_body and checkers.is_string(article_body) and len(article_body) >= 250 and not article_body.isspace(): pass else: errors.append("Article Body is invalid: must be 250 characters minimum.") if article_category and checkers.is_string(article_category) and len(article_category) >= 3 and not article_category.isspace(): pass else: errors.append("Category is invalid. Must be three characters minimum.") if article_tags and checkers.is_string(article_tags) and len(article_tags) >= 3 and not article_tags.isspace(): pass else: errors.append("Tags is invalid. Must be at least one tag of three characters minimum.") if article_language_option and checkers.is_string(article_language_option) and not article_language_option.isspace(): pass else: errors.append("Article language is invalid. Choose language.") if article_publication_option and checkers.is_string(article_publication_option) and not article_publication_option.isspace(): pass else: errors.append("Publication option is invalid. Choose Publication option.") if len(errors) == 0: return True, errors if len(errors) > 0: return False, errors
def post(self): user_info = request.get_json() params = ['name', 'email', 'dateOfBirth'] for i in user_info.keys(): if i not in params: return {"msg": "invalid request"} if checkers.is_string(user_info['name']) == False \ or checkers.is_email(user_info['email']) == False \ or checkers.is_date(user_info['dateOfBirth']) == False: return {"msg": "invalid request"}, 400 user_info["isDelete"] = False try: mongo.db.users.insert(user_info) except pymongo.errors.DuplicateKeyError: return {"msg": "email already exists"} return 'added user'
def reset_password_validator(token, password, confirm_password): errors = [] if token and checkers.is_string(token): pass else: errors.append("Token is invalid. Request a fresh one.") if password and is_valid_password(password): if confirm_password is not None and password == confirm_password: pass else: errors.append("Passwords do not match") else: errors.append("Password is invalid: must be 8 characters minimum and a mixture of both letters and numbers.") if len(errors) == 0: return True, errors if len(errors) > 0: return False, errors
def signin_validator(email_or_username, password): errors = list() if email_or_username and checkers.is_string(email_or_username): user = User.query.filter( (User.email == email_or_username) | (User.username == email_or_username) ).first() if user: if not user.check_password(password): errors.append("Password is incorrect.") else: errors.append("No account with this email/ username exists.") else: errors.append("Email or password is invalid") if len(errors) == 0: return True, errors, user if len(errors) > 0: return False, errors, None
def missing_value_metadata(self, value): if not value: self._missing_value_metadata = None return elif checkers.is_string(value): value = [value] elif checkers.is_numeric(value): value = [value] validated_values = [] for item in value: try: validated_item = validators.string(item, allow_empty = False) except (ValueError, TypeError): validated_item = validators.int(item, allow_empty = False) validated_values.append(validated_item) self._missing_value_metadata = validated_values
def patch(self, id): user_info = request.get_json() if user_info.get('name'): if not checkers.is_string(user_info.get('name')): return {"msg": "invalid request"}, 400 if user_info.get('email'): if not checkers.is_email(user_info.get('email')): return {"msg": "invalid request"}, 400 if user_info.get('dateOfBirth'): if not checkers.is_date(user_info.get('dateOfBirth')): return {"msg": "invalid request"}, 400 try: mongo.db.users.update({"_id": ObjectId(id)}, {"$set": user_info}) return {"msg": 'updated user'} except pymongo.errors.DuplicateKeyError: return {"msg": "email already exists"} except Exception as e: return {"error": str(e)}
def delete_account(): title = "Lang & Code[!] - Delete Account" if request.method == "GET": flash("Warning: You are about to delete your account. Once deleted, it cannot be recovered.", "is-danger") return render_template("user/delete_account.html", title=title) if request.method == "POST": email = request.form.get("email") password = request.form.get("password") reason = request.form.get("reason") if email and password and email == current_user.email and current_user.check_password(password): deleted_account = DeletedAccount(email=email, reason=reason if checkers.is_string(reason) else None) db.session.add(deleted_account) db.session.delete(current_user) db.session.commit() flash("Account system: Your Account and all the data related to it have been deleted.", "is-danger") return redirect(url_for("main.index")) flash("Account system: Your email or password is invalid", "is-danger") return redirect(url_for("main.index")) flash('Something went wrong, or you do not have enough permission to perform this action.') return redirect(url_for('main.index'))
def signup_validator(username, email, password): errors = list() if email and checkers.is_email(email): check_email = User.query.filter_by(email=email).first() if not check_email: pass else: errors.append("An account is already registred with this email.") else: errors.append("Email is invalid.") if username and checkers.is_string(username): user = User.query.filter(User.username==username).first() if user: errors.append("An account is already registered with this username.") if password and is_valid_password(password): pass else: errors.append("Password is invalid: must be 8 characters \ minimum and a mixture of both letters and numbers.") if len(errors) == 0: return True, errors, user if len(errors) > 0: return False, errors, None
def is_empty(text): return False if text and checkers.is_string( text) and not text.isspace() and len(text) > 0 else True
def is_valid_password(password): if password and checkers.is_string(password) and len(password) >= 8 and not password.isspace(): return True return False
def _get_attribute_csv_data(self, attributes, is_dumping=False, delimiter='|', wrap_all_strings=False, null_text='None', wrapper_character="'", double_wrapper_character_when_nested=False, escape_character="\\", line_terminator='\r\n', config_set=None): r"""Return the CSV representation of ``attributes`` extracted from the model instance (record). :param attributes: Names of :term:`model attributes <model attribute>` to include in the CSV output. :type attributes: :class:`list <python:list>` of :class:`str <python:str>` :param is_dumping: If ``True``, then allow :exc:`UnsupportedSerializationError <sqlathanor.errors.UnsupportedSerializationError>`. Defaults to ``False``. :type is_dumping: :class:`bool <python:bool>` :param delimiter: The delimiter used between columns. Defaults to ``|``. :type delimiter: :class:`str <python:str>` :param wrap_all_strings: If ``True``, wraps any string data in the ``wrapper_character``. If ``None``, only wraps string data if it contains the ``delimiter``. Defaults to ``False``. :type wrap_all_strings: :class:`bool <python:bool>` :param null_text: The text value to use in place of empty values. Only applies if ``wrap_empty_values`` is ``True``. Defaults to ``'None'``. :type null_text: :class:`str <python:str>` :param wrapper_character: The string used to wrap string values when wrapping is necessary. Defaults to ``'``. :type wrapper_character: :class:`str <python:str>` :param double_wrapper_character_when_nested: If ``True``, will double the ``wrapper_character`` when it is found inside a column value. If ``False``, will precede the ``wrapper_character`` by the ``escape_character`` when it is found inside a column value. Defaults to ``False``. :type double_wrapper_character_when_nested: :class:`bool <python:bool>` :param escape_character: The character to use when escaping nested wrapper characters. Defaults to ``\``. :type escape_character: :class:`str <python:str>` :param line_terminator: The character used to mark the end of a line. Defaults to ``\r\n``. :type line_terminator: :class:`str <python:str>` :param config_set: If not :obj:`None <python:None>`, the named configuration set to use. Defaults to :obj:`None <python:None>`. :type config_set: :class:`str <python:str>` / :obj:`None <python:None>` :returns: Data from the object in CSV format ending in ``line_terminator``. :rtype: :class:`str <python:str>` """ if not wrapper_character: wrapper_character = '\'' if not attributes: raise SerializableAttributeError("attributes cannot be empty") if wrap_all_strings: quoting = csv.QUOTE_NONNUMERIC else: quoting = csv.QUOTE_MINIMAL if 'sqlathanor' in csv.list_dialects(): csv.unregister_dialect('sqlathanor') csv.register_dialect('sqlathanor', delimiter=delimiter, doublequote=double_wrapper_character_when_nested, escapechar=escape_character, quotechar=wrapper_character, quoting=quoting, lineterminator=line_terminator) data = [] for item in attributes: try: value = self._get_serialized_value(format='csv', attribute=item, config_set=config_set) except UnsupportedSerializationError as error: if is_dumping: value = getattr(self, item) else: raise error data.append(value) for index, item in enumerate(data): if item == '' or item is None or item == 'None': data[index] = null_text elif not checkers.is_string(item) and not checkers.is_numeric( item): data[index] = str(item) data_dict = dict_() for index, column_name in enumerate(attributes): data_dict[column_name] = data[index] output = StringIO() csv_writer = csv.DictWriter(output, fieldnames=attributes, dialect='sqlathanor') csv_writer.writerow(data_dict) data_row = output.getvalue() output.close() csv.unregister_dialect('sqlathanor') return data_row
def validate_string(string: str, min_len: int, max_len: int) -> bool: return checkers.is_string(string, minimum_length=min_len, maximum_length=max_len)