Beispiel #1
0
def change_password(email, old_password, new_password, confirm_password, **kwargs):
    """
    :param email:
    :param old_password:
    :param new_password:
    :param confirm_password:
    :param kwargs:
    :return:
    """
    user = repositories.user.find_one_by_email_ignore_case(email=email)
    if not user:
        raise BadRequestException("Account linked to this email does not exist.")

    if(     # this step should replace by switch() case to catch exceptions exactly
        # token??
        email and re.match(validate_email, email) and
        old_password and re.match(validate_password, old_password) and
        new_password and re.match(validate_password, new_password) and
        confirm_password and re.match(validate_password, confirm_password) and
        new_password == confirm_password and
        new_password != old_password and

        models.User.check_password(user, old_password)
    ):
        repositories.user.save_history_password_to_database(
            user_id=user.id,
            history_pass_change=user.get_password(),
            **kwargs
        )
        updated_user = repositories.user.update_password_to_database(email=email, new_password=new_password)
    else:
        raise BadRequestException("Invalid data specified")
    return "Password is updated!"
Beispiel #2
0
def login(username, password):
    """
    Validate post data and return token
    :param username:
    :param password:
    :return:
    """
    if(
        username and len(username) < 50 and
        password and re.match(validate_password, password)
    ):
        find_user = repositories.user.find_one_by_username_ignore_case(username=username)
        expired_time_min = datetime.timedelta(minutes=30)
        if not find_user:
            raise BadRequestException("Username does not exist.")
        if models.User.check_password(find_user, password):
            token = create_access_token(identity={
                "username": find_user.username,
                "email": find_user.email,
                "is_admin": find_user.is_admin
            }, expires_delta=expired_time_min)

            repositories.user.save_user_token_to_database(
                user_id=find_user.id,
                token=token,
                expired_time=datetime.datetime.now() + expired_time_min
            )

            repositories.user.update_last_login_to_database(email=find_user.email)
            return token

        else:
            raise BadRequestException("Incorrect password")
    else:
        raise BadRequestException("Invalid username or password")
Beispiel #3
0
def create_user(username, email, password, fullname="", role="", **kwargs):
    """
    Validate post data and create a new user
    :param str username:
    :param str email:
    :param str password:
    :param str fullname:
    :param str role:
    :param kwargs:
    :return: a new user
    :rtype: m.User
    """
    if (username and len(username) < 50 and email
            and re.match(r"[^@]+@[^\.]+\..+", email) and password
            and re.match(r"^[A-Za-z0-9]{6,}$", password)):
        existed_user = repositories.user.find_one_by_email_or_username_ignore_case(
            email, username)
        if existed_user:
            raise BadRequestException(
                "User with username {username} "
                "or email {email} already existed!".format(username=username,
                                                           email=email))

        user = repositories.user.save_user_to_database(username=username,
                                                       email=email,
                                                       fullname=fullname,
                                                       role=role,
                                                       **kwargs)
        return user
    else:
        raise BadRequestException("Invalid user data specified!")
Beispiel #4
0
def register(username, email, password, confirm_password, **kwargs):
    from boilerplate import mail
    """
    validate post data, save user in table signup_request and send email confirmation
    :param username:
    :param email:
    :param password:
    :param confirm_password:
    :param kwargs:
    :return:
    """

    if (
        username and len(username) < 50 and
        email and re.match(validate_email, email) and
        password and re.match(validate_password, password) and
        confirm_password and re.match(validate_password, confirm_password) and
        password == confirm_password
    ):
        existed_user = repositories.user.find_one_by_email_ignore_case(email)
        if existed_user:
            raise BadRequestException(
                "User with email {email} already existed!".format(
                    email=email
                )
            )

        email_confirm_token = serializer.dumps(email, salt='more_salt_please')
        message = Message('PROJECT - Confirm email for registration',
                          sender='*****@*****.**', recipients=[email])
        link = host_users+'/confirm_email/?token={}'.format(email_confirm_token)

        message.body = 'Click the link below to confirm registration in PROJECT: {}'.format(link)
        mail.send(message)

        repositories.user.save_signup_request_to_database(
            username=username,
            email=email,
            password=password,
            # fullname=fullname,
            user_token_confirm=email_confirm_token,
            **kwargs
        )
        return link
    else:
        raise BadRequestException("Invalid user data specified!")
 def validate(self, data, resolver=None, format_checker=None):
     validator = Draft4Validator(self.__schema__,
                                 resolver=resolver,
                                 format_checker=format_checker)
     try:
         validator.validate(data)
     except ValidationError:
         raise BadRequestException(
             message='Input payload validation failed',
             errors=dict(
                 self.format_error(e) for e in validator.iter_errors(data)))
Beispiel #6
0
def forget_password(username, email):
    """
    :param username:
    :param email:
    :param kwargs:
    :return:
    """
    from boilerplate import mail

    if (
            username and len(username) < 50 and
            email and re.match(validate_email, email)
    ):
        existed_user = repositories.user.find_one_by_email_ignore_case(email)
        if not existed_user:
            raise BadRequestException(
                "User with email {email} not found!".format(
                    email=email
                )
            )
        elif (
            existed_user != repositories.user.find_one_by_username_ignore_case(username)
        ):
            raise BadRequestException(
                "User with username and email not match!"
            )
        else:
            email_confirm_token = serializer.dumps(email, salt='more_salt_please')
            message = Message('PROJECT - Confirm email for changing password',
                              sender='*****@*****.**', recipients=[email])
            link = host_users+'/confirm_email_forget_password/?token={}'.format(email_confirm_token)

            message.body = 'Click the link below to confirm changing password: {}'.format(link)
            mail.send(message)

        return link
    else:
        raise BadRequestException(
            "Invalid data specified!"
        )
    def parse_args(self, req=None, strict=False):
        """
        Parse all arguments from the provided request and return
        the results as a ParseResult.
        :param bool strict: if req includes args not in parser,
        throw 400 BadRequest exception
        :return: the parsed results
        :rtype: ParseResult
        """
        if req is None:
            req = request

        result = self.result_class()

        # A record of arguments not yet parsed; as each is found
        # among self.args, it will be popped out
        req.unparsed_arguments = dict(
            self.argument_class('').source(req)) if strict else {}
        errors = {}
        for arg in self.args:
            value, found = arg.parse(req, self.bundle_errors)
            if isinstance(value, ValueError):
                errors.update(found)
                found = None
            if found or arg.store_missing:
                result[arg.dest or arg.name] = value
        if errors:
            raise BadRequestException('Input payload validation failed',
                                      errors)

        if strict and req.unparsed_arguments:
            arguments = ', '.join(req.unparsed_arguments.keys())
            msg = 'Unknown arguments: {0}'.format(arguments)
            raise BadRequest(msg)

        return result