Ejemplo n.º 1
0
 def test_htpasswd_bcrypt(self):
     try:
         from passlib.hash import bcrypt
         from passlib.exc import MissingBackendError
     except ImportError:
         pytest.skip("passlib is not installed")
     try:
         bcrypt.hash("test-bcrypt-backend")
     except MissingBackendError:
         pytest.skip("bcrypt backend for passlib is not installed")
     self._test_htpasswd(
         "bcrypt",
         "tmp:$2y$05$oD7hbiQFQlvCM7zoalo/T.MssV3VNTRI3w5KDnj8NTUKJNWfVpvRq")
Ejemplo n.º 2
0
 def _encrypt(self, clearvalue, salt=None):
     # Using the parameter for rounds will generate the error
     # ValueError: rounds too high (bcrypt requires <= 31 rounds)
     # when using the bcrypt hasher.
     # rounds = parameters.get_global_parameter("rounds_number")
     # To get around this, I use the default of 12.
     rounds = 12
     return bcrypt.hash(clearvalue, rounds=rounds)
Ejemplo n.º 3
0
    def __init__(self, configuration):
        super().__init__(configuration)
        self.filename = os.path.expanduser(
            configuration.get("auth", "htpasswd_filename"))
        self.encryption = configuration.get("auth", "htpasswd_encryption")

        if self.encryption == "ssha":
            self.verify = self._ssha
        elif self.encryption == "sha1":
            self.verify = self._sha1
        elif self.encryption == "plain":
            self.verify = self._plain
        elif self.encryption == "md5":
            try:
                from passlib.hash import apr_md5_crypt
            except ImportError as e:
                raise RuntimeError(
                    "The htpasswd encryption method 'md5' requires "
                    "the passlib module.") from e
            self.verify = functools.partial(self._md5apr1, apr_md5_crypt)
        elif self.encryption == "bcrypt":
            try:
                from passlib.hash import bcrypt
            except ImportError as e:
                raise RuntimeError(
                    "The htpasswd encryption method 'bcrypt' requires "
                    "the passlib module with bcrypt support.") from e
            # A call to `encrypt` raises passlib.exc.MissingBackendError with a
            # good error message if bcrypt backend is not available. Trigger
            # this here.
            bcrypt.hash("test-bcrypt-backend")
            self.verify = functools.partial(self._bcrypt, bcrypt)
        elif self.encryption == "crypt":
            try:
                import crypt
            except ImportError as e:
                raise RuntimeError(
                    "The htpasswd encryption method 'crypt' requires "
                    "the crypt() system support.") from e
            self.verify = functools.partial(self._crypt, crypt)
        else:
            raise RuntimeError(
                "The htpasswd encryption method %r is not "
                "supported." % self.encryption)
Ejemplo n.º 4
0
 def add(self, data, tipo=None):
     # Forzar a que la clave se guarde cifrada
     data.update(password=bcrypt.hash(data["password"]))
     data.update(email=data["email"].lower())
     return DBCollection.add(self, data, model.Profesor)
Ejemplo n.º 5
0
async def create_and_get_user(username, password):
    async with Connection() as conn:
        insert_user = await conn.execute(SSOModels.user.insert().values(
            username=username, password=bcrypt.hash(password)))
        user = await insert_user.fetchone()
        return user
Ejemplo n.º 6
0
 def __init__(self, full_name: str, email, password):
     self.full_name = full_name
     self.username = full_name.lower().replace(' ', '.')
     self.password = bcrypt.hash(password)
     self.email = email
Ejemplo n.º 7
0
    def register(self):
        c.execute("""CREATE TABLE IF NOT EXISTS customerInformation(
                  forename TEXT,
                  surname TEXT,
                  username TEXT,
                  password TEXT,
                  passcode TEXT
                  )""")  #creating the table within the database.
        conn.commit()  #saving the changes

        forename = self.forename.get()
        surname = self.surname.get()
        username = self.username.get()
        password = self.password.get()
        conf_pass = self.conf_pass.get()
        passcode = self.passcode.get()

        if (forename and surname and username and password and conf_pass
                and passcode) == "":
            mb.showerror("Error", "Fields cannot be blank")
        elif not forename.isalpha() and not surname.isalpha(
        ):  #checks if the surname and forename only contain letters
            mb.showerror("Error",
                         "Forename and surname can only contian letters")
        elif (forename and surname and username and password and conf_pass
              and passcode) == "*":
            mb.showerror("Error", " Character not allowed")
        elif len(username) < 4 or len(
                username
        ) > 21:  #checking if the username is wihthin the range of characters
            mb.showerror("Error",
                         "Username length has to be between 4 to 21 characters"
                         )  #shows an error message if the if statement is true
        elif not username.isalnum(
        ):  #checks if the username is not alphanumeric
            mb.showerror("Error", "Username needs to be alphanumeric"
                         )  #shows an error message to the user
        elif (len(password) and len(conf_pass)) < 8 or (len(password) and
                                                        len(conf_pass)) > 21:
            mb.showerror("Error",
                         "Password has to be between 8 to 21 characters")
        elif len(passcode
                 ) < 4:  #checks if the length of the passcode is less than 4
            mb.showerror("Error", "Passcode has to be 4 characters or more")
        elif conf_pass != password:
            mb.showerror("Error", "Passwords don't match")
        else:
            username_data = []
            count = 0
            password = bcrypt.hash(password)  #hashes the password
            passcode = bcrypt.hash(passcode)  #hashes the passcode
            c.execute("SELECT username FROM customerInformation"
                      )  #selects the username in the table
            data = c.fetchall()  #fetches all of the usernames
            for row in data:
                username_data.append(row)  #adds the usernames into a database.
            if len(username_data
                   ) != 0:  #checks if the length of the data is not
                while count < len(username_data
                                  ):  #creates a loop until the condtion is met
                    if username == username_data[count][0]:
                        mb.showerror("Error", "Username already in use")
                        break  #prevents an infiniate loop
                    elif username != username_data[count][0]:
                        count += 1
                    if count >= len(username_data):
                        c.execute(
                            """INSERT INTO customerInformation(forename, surname, username, password, passcode)
                                  VALUES(?,?,?,?,?)""",
                            (forename, surname, username, password,
                             passcode))  #adds in the data into the table
                        conn.commit()  #saves the information
                        mb.showinfo(
                            "Success",
                            "Information Added")  #shows a success message
                        break  #breaks the loop.
            else:
                c.execute(
                    """INSERT INTO customerInformation(forename, surname, username, password, passcode)
                          VALUES(?,?,?,?,?)""",
                    (forename, surname, username, password, passcode))
                conn.commit()
                mb.showinfo("Success", "Information Added")
Ejemplo n.º 8
0
 def password(self, password):
     self._password = bcrypt.hash(password)
Ejemplo n.º 9
0
    def test_sqlresolver_passwords(self):
        """
        test that we can use pbkdf2 and bcrypt passwords with an sql resolver
        """

        users = {}

        # ------------------------------------------------------------------ --

        # create the User schema

        self.createUserTable()

        # ------------------------------------------------------------------ --

        # add users

        bach_password = "******"
        bach_password_hash = ('{PKCS5S2}ZYIjvFLd99ldgx5b7sqOlDCKNt31'
                              'UBX9HQKxTZwU50WfuZlWTNG5qBsCsFUMWwxC')

        users['bach'] = {
            'login': '******',
            'uid': '21.3.1685',
            'telephonenumber': '',
            'mobile': bach_password,
            'surname': 'Bach',
            'givenname': 'Johann Sebastian',
            'password': bach_password_hash,
            'mail': '*****@*****.**'
        }

        assert atlassian_pbkdf2_sha1.verify(bach_password, bach_password_hash)
        self.addUser(**users['bach'])

        # ------------------------------------------------------------------ --

        chopin_password = "******"
        chopin_password_hash = atlassian_pbkdf2_sha1.hash(chopin_password)

        users['chopin'] = {
            'login': '******',
            'uid': '22.10.1849',
            'telephonenumber': '',
            'mobile': chopin_password,
            'surname': 'Chopin',
            'givenname': 'Fryderyk Franciszek',
            'password': chopin_password_hash,
            'mail': '*****@*****.**'
        }

        assert atlassian_pbkdf2_sha1.verify(chopin_password,
                                            chopin_password_hash)
        self.addUser(**users['chopin'])

        # ------------------------------------------------------------------ --

        brahms_password = '******'
        brahms_password_hash = ('$2a$12$NT0I31Sa7ihGEWpka9ASYrEFk'
                                'huTNeBQ2xfZskIiiJeyFXhRgS.Sy')

        users['brahms'] = {
            'login': '******',
            'uid': '7.5.1833',
            'telephonenumber': '',
            'mobile': brahms_password,
            'surname': 'Brahms',
            'givenname': 'Johannes',
            'password': brahms_password_hash,
            'mail': '*****@*****.**'
        }

        assert passlib_bcrypt.verify(brahms_password, brahms_password_hash)

        self.addUser(**users['brahms'])

        # ------------------------------------------------------------------ --

        mozart_password = '******'
        mozart_password_hash = passlib_bcrypt.hash(mozart_password)

        users['mozart'] = {
            'login': '******',
            'uid': '27.1.1756',
            'telephonenumber': '',
            'mobile': mozart_password,
            'surname': 'Mozart',
            'givenname': 'Wolfgang Amadeus',
            'password': mozart_password_hash,
            'mail': '*****@*****.**'
        }

        assert passlib_bcrypt.verify(mozart_password, mozart_password_hash)

        self.addUser(**users['mozart'])

        # ------------------------------------------------------------------ --

        schubert_password = '******'
        schubert_password_hash = '$P$8ohUJ.1sdFw09/bMaAQPTGDNi2BIUt1'

        users['schubert'] = {
            'login': '******',
            'uid': '31.1.1797',
            'telephonenumber': '',
            'mobile': schubert_password,
            'surname': 'Schubert',
            'givenname': 'Franz Peter',
            'password': schubert_password_hash,
            'mail': '*****@*****.**'
        }

        assert passlib_phpass.verify(schubert_password, schubert_password_hash)

        self.addUser(**users['schubert'])

        # ------------------------------------------------------------------ --

        mendelssohn_password = '******'
        mendelssohn_password_hash = passlib_phpass.hash(mendelssohn_password)

        users['mendelssohn'] = {
            'login': '******',
            'uid': '31.2.1809',
            'telephonenumber': '',
            'mobile': mendelssohn_password,
            'surname': 'Mendelssohn',
            'givenname': 'Jakob Ludwig',
            'password': mendelssohn_password_hash,
            'mail': '*****@*****.**'
        }

        assert passlib_phpass.verify(mendelssohn_password,
                                     mendelssohn_password_hash)

        self.addUser(**users['mendelssohn'])

        # ------------------------------------------------------------- --

        # define resolver and realm

        realm = 'sqlRealm'

        self.addSqlResolver('my_sql_users')
        self.addSqlRealm(realm, 'my_sql_users', defaultRealm=True)

        # ------------------------------------------------------------- --

        # run the pbkdf2 atlasian test with user bach

        user = users['bach']['login']
        password = users['bach']['mobile']

        self.run_password_check(user, password, realm=realm)

        # run the pbkdf2 atlasian test with user chopin

        user = users['chopin']['login']
        password = users['chopin']['mobile']

        self.run_password_check(user, password, realm=realm)

        # run the bcrypt test with user brahms

        user = users['brahms']['login']
        password = users['brahms']['mobile']

        self.run_password_check(user, password, realm=realm)

        # run the bcrypt test with user mozart

        user = users['mozart']['login']
        password = users['mozart']['mobile']

        self.run_password_check(user, password, realm=realm)

        # run the php test with user schubert

        user = users['schubert']['login']
        password = users['schubert']['mobile']

        self.run_password_check(user, password, realm=realm)

        # run the php test with user mendelssohn

        user = users['mendelssohn']['login']
        password = users['mendelssohn']['mobile']

        self.run_password_check(user, password, realm=realm)

        return
Ejemplo n.º 10
0
def hash_password(raw_password: str) -> str:
    return bcrypt.hash(raw_password)
Ejemplo n.º 11
0
async def create_user(user: UserAuthInSchema):
    user_obj = UserAuth(username=user.username,
                        password_hash=bcrypt.hash(user.password_hash))
    await user_obj.save()
    user = await UserAuthSchema.from_tortoise_orm(user_obj)
    return user
Ejemplo n.º 12
0
def get_password_hash(password):
    if password is None or len(password) == 0:
        return None

    return bcrypt.hash(password)
Ejemplo n.º 13
0
 def get_password_hash(password: str) -> str:
     return bcrypt.hash(password)
Ejemplo n.º 14
0
 def hash_password(cls, password: str) -> str:
     return bcrypt.hash(password)
Ejemplo n.º 15
0
def passHash(password):
    hashed_password = bcrypt.hash(password)
    return hashed_password
Ejemplo n.º 16
0
def hash_password(password, salt=False):
    if salt:
        return bcrypt.hash(password, salt=salt)
    return bcrypt.hash(password)
Ejemplo n.º 17
0
def generate_bcrypt_hash(ctx):
    import getpass
    from passlib.hash import bcrypt

    print(bcrypt.hash(getpass.getpass()))
Ejemplo n.º 18
0
 def _get_hash(self, password):
     return bcrypt.hash(password)
Ejemplo n.º 19
0
def getHashedPassword(password):
    return bcrypt.hash(password)
Ejemplo n.º 20
0
async def create_user(user: UserIn_Pydantic):
    user_obj = User(username=user.username,
                    password_hash=bcrypt.hash(user.password_hash))
    await user_obj.save()
    return await User_Pydantic.from_tortoise_orm(user_obj)
Ejemplo n.º 21
0
 def __init__(self, **kwargs):
     self.name = kwargs.get('name')
     self.emeil = kwargs.get('emeil')
     self.password = bcrypt.hash(kwargs.get('password'))
Ejemplo n.º 22
0
async def register(user: Users, admin: str = Depends(get_current_user)):
    ret = db.Users.insert_one({
        "Username": user.Username,
        "Password": bcrypt.hash(user.Password)
    })
    return {"result": {user.Username, bcrypt.hash(user.Password)}}
Ejemplo n.º 23
0
    def forgot_pass(self):  #forgot password function
        #retriving all user input from enteries
        new_pass = self.new_pass.get()
        conf_new_pass = self.conf_new_pass.get()
        username = self.username.get()
        passcode = self.passcode.get()

        new_pass = bcrypt.hash(new_pass)  #hashing the password
        password_verify = bcrypt.verify(
            conf_new_pass, new_pass)  #checking the the passwords match

        if (new_pass and conf_new_pass and username
                and passcode) == "":  #checks if the fields are blank
            mb.showerror("Error", "Fields cannot be blank"
                         )  #shows an erorr message if the fields are blank
        elif (new_pass and conf_new_pass and username
              and passcode) == "*":  #checks if there is an * within the field
            mb.showerror("Error",
                         "Charater not allowed")  #shows the error message
        elif (len(new_pass) and len(conf_new_pass)) < 8 or (
                len(new_pass) and len(conf_new_pass)
        ) > 21:  #checks if the password is within the range of charaters specified.
            mb.showerror("Error",
                         "Password has to be between 8 to 21 characters"
                         )  #shows an error message if this is not the case
        elif not password_verify:  #checks if the passwords do not match
            mb.showerror(
                "Error", "Passwords do not match"
            )  #shows an error message telling the user that the password do not match
        else:
            try:
                user_data = []
                count = 0
                c.execute(
                    "SELECT username, password, passcode FROM customerInformation"
                )  #selects username password and passcode from the field
                data = c.fetchall()
                for row in data:
                    user_data.append(row)
                while count < len(user_data):
                    if username == user_data[count][0]:
                        passcode_id = user_data[count][2]
                        passcode_verify = bcrypt.verify(
                            passcode, passcode_id
                        )  #checks if the passcode entered matches with the passcode in the table
                        if passcode_verify:  #checks if the variable is true
                            old_pass = user_data[count][
                                1]  #sets the old password based on the index of the passcode and username
                            c.execute(
                                "UPDATE customerInformation SET password = ? WHERE password  = ?",
                                (new_pass, old_pass)
                            )  # Changes the password where the username is specified
                            conn.commit()  #saves the changes to the database
                            mb.showinfo(
                                "Success", "Password Changed"
                            )  #tells the user that their function was successful
                            break  #breaks the loop to prevent an infincate loop
                        else:
                            mb.showerror(
                                "Error",
                                "Operation Failed")  #shows an error message.
                            break

                    elif username != user_data[count][0]:
                        count += 1
                if count >= len(user_data):
                    mb.showerror("Error", "Incorrect Username or Passcode")
            except sqlite3.OperationalError:
                mb.showerror("Error", "File Not Found Error")
Ejemplo n.º 24
0
 def update(self, data):
     """Actualiza los datos del profesor, asegurándose de que la clave va cifrada
     a la base de datos"""
     if "password" in data:
         data.update(password=bcrypt.hash(data["password"]))
     super().update(data)
Ejemplo n.º 25
0
def hash_password(password):
    return bcrypt.hash(password)
Ejemplo n.º 26
0
async def update_password(username, new_password):
    async with Connection() as conn:
        await conn.execute(SSOModels.user.update().where(
            SSOModels.user.c.username == username).values(
                password=bcrypt.hash(new_password)))
Ejemplo n.º 27
0
 def get_bcrypt_hashed_passwd(self, password):
     """ hash the password using bcrypt from passlib.hash """
     # use bcrypt to hash the password
     return bcrypt.hash(password)
Ejemplo n.º 28
0
    def change_password(user_id):
        verify_token = settings['verify_token']
        app_secret = settings['application_secret']
        auth_header = request.headers.get('Authorization')
        try:
            body = json.loads(request.data)
        except Exception as e:
            raise ErtisError(err_code="errors.invalidBodyProvided",
                             err_msg="Provided body is invalid JSON",
                             status_code=400,
                             context={'message': str(e)})

        if not auth_header:
            raise ErtisError(
                err_code="errors.authorizationHeaderRequired",
                err_msg=
                "Authorization header required for use <change_password> api",
                status_code=401)

        try:
            token = auth_header.split(' ')[1]
        except Exception as e:
            raise ErtisError(err_code="errors.providedBearerTokenIsInvalid",
                             err_msg="Invalid token provided.",
                             status_code=401,
                             context={'message': str(e)})

        security_manager = ErtisSecurityManager(app.db)
        user = security_manager.load_user(token, app_secret, verify_token)

        if user_id != str(user['_id']):
            raise ErtisError(
                err_code="errors.userNotAuthorizedForChangePassword",
                err_msg="Users can not change another user's password",
                status_code=403)

        new_password = body.get('password', None)
        if len(new_password) < 4:
            raise ErtisError(err_msg="Password must be more than 4 characters",
                             err_code="errors.passwordIsTooShort",
                             status_code=400)

        if not new_password:
            raise ErtisError(
                err_msg="Password is required for change password of user",
                err_code="errors.passwordIsRequired",
                status_code=400)

        if bcrypt.verify(new_password, user["password"]):
            raise ErtisError(
                err_msg=
                "User's password can not be same with previous password",
                err_code="errors.userPasswordCannotBeSameWithPrevious",
                status_code=400)

        hashed_password = bcrypt.hash(new_password)
        user['password'] = hashed_password

        user.pop('permissions', None)
        user['sys']['modified_by'] = user['email']
        user['sys']['modified_at'] = datetime.datetime.utcnow()

        g_service = app.generic_service
        g_service.replace(user, 'users')

        user.pop('password')

        return Response(json.dumps(user, default=bson_to_json),
                        mimetype='application/json',
                        status=200)