示例#1
0
    async def authenticate(
        self, request: Request
    ) -> typing.Tuple[AuthCredentials, BaseUser]:

        auth = request.session.pop("auth", None)
        if auth:
            sun, spw = state.items.storage().split(":", 1)
            aun, apw = auth.split(":", 1)
            if sun and sun == aun and hasher.verify(apw, spw):
                request.session.update(user=hasher.hash(auth))
                messages.add(
                    request=request,
                    text="Logged in successfully",
                    type=messages.SUCCESS,
                )
                return AuthCredentials(scopes=["authenticated"]), SimpleUser("admin")
            messages.add(
                request=request, text="Invalid credentials", type=messages.DANGER
            )

        if "user" not in request.session:
            return AuthCredentials(scopes=["anonymous"]), UnauthenticatedUser()

        user = request.session["user"]
        if hasher.identify(user):
            return AuthCredentials(scopes=["authenticated"]), SimpleUser("admin")

        request.session.pop("user")
        return AuthCredentials(scopes=["anonymous"]), UnauthenticatedUser()
    def hash_passwords(self, data):
        """Change the content of the users database"""
        import time
        #TODO: remove printing passwords into log 
        _log.debug("hash_passwords\n\tdata={}".format(data))
        updates_made = False
        start = time.time()
        for username in data:
            user_data = data[username]
            try:
                is_pbkdf2 = pbkdf2_sha256.identify(user_data['password'])
            except Exception as err:
                _log.error("Failed to identify if password is PBKDF2 or not:"
                           "\n\tusername={}"
                           "\n\tuser_data={}"
                           "\n\terr={}".format(username, user_data, err))
                raise

            #If the password is in clear, let's hash it with a salt and store that instead
            if ('password' in user_data) and not (is_pbkdf2):
                try:
                    hash = pbkdf2_sha256.encrypt(user_data['password'], rounds=200000, salt_size=16)
                except Exception as err:
                    _log.error("Failed to calculate PBKDF2 of password, err={}".format(err))
                    raise
                user_data['password']=hash
                updates_made = True
        _log.debug("hashed_passwords"
                   "\n\tdata={}"
                   "\n\ttime it took to hash passwords={}".format(data, time.time()-start))
        return updates_made
def Key_Verification(keys: List[A], encrypted_keys: List[A]) -> bool:
    """

    :param keys:
    :type encrypted_keys: object
    """
    if all([pbkdf2_sha256.identify(i) for i in encrypted_keys]):
        return all([pbkdf2_sha256.verify(i, j) for i in keys for j in encrypted_keys])
    return False
 def update_users_db(self, data):
     """Change the content of the users database"""
     for user in data['users_db']:
         #If the password is stored in clear, let's hash it with a salt and store that instead
         if not pbkdf2_sha256.identify(user['password']):
            hash = pbkdf2_sha256.encrypt(user['password'], rounds=200000, salt_size=16)
            user['password']=hash    
     file_path = os.path.join(self.path, "users.json")
     if os.path.isfile(file_path):
         with open(file_path, "w") as file:
             json.dump(data, file)
     else:
         raise IOError  # Raise exception if policy named filename doesn't exist
示例#5
0
 def update_users_db(self, data):
     """Change the content of the users database"""
     for user in data['users_db']:
         #If the password is stored in clear, let's hash it with a salt and store that instead
         if not pbkdf2_sha256.identify(user['password']):
             hash = pbkdf2_sha256.encrypt(user['password'],
                                          rounds=200000,
                                          salt_size=16)
             user['password'] = hash
     file_path = os.path.join(self.path, "users.json")
     if os.path.isfile(file_path):
         with open(file_path, "w") as file:
             json.dump(data, file)
     else:
         raise IOError  # Raise exception if policy named filename doesn't exist
    def hash_passwords(self, data):
        """Change the content of the users database"""
        import time
        #TODO: remove printing passwords into log
        _log.debug("hash_passwords\n\tdata={}".format(data))
        updates_made = False
        start = time.time()
        for username in data:
            user_data = data[username]
            try:
                is_pbkdf2 = pbkdf2_sha256.identify(user_data['password'])
            except Exception as err:
                _log.error("Failed to identify if password is PBKDF2 or not:"
                           "\n\tusername={}"
                           "\n\tuser_data={}"
                           "\n\terr={}".format(username, user_data, err))
                raise

            #If the password is in clear, let's hash it with a salt and store that instead
            if ('password' in user_data) and not (is_pbkdf2):
                try:
                    hash = pbkdf2_sha256.encrypt(user_data['password'],
                                                 rounds=200000,
                                                 salt_size=16)
                except Exception as err:
                    _log.error(
                        "Failed to calculate PBKDF2 of password, err={}".
                        format(err))
                    raise
                user_data['password'] = hash
                updates_made = True
        _log.debug("hashed_passwords"
                   "\n\tdata={}"
                   "\n\ttime it took to hash passwords={}".format(
                       data,
                       time.time() - start))
        return updates_made
示例#7
0
    def validate(self):
        """
        Checks whether the object is a valid user object that can be written
        to the database.

        Raises:
            InvalidCredentialException if a credential is invalid.\n
            InvalidRoleException if an ancestor role is not valid.
        """
        logging.info("Validating User object:\n" + repr(self))

        # Raises an InvalidCredentialException if username not valid.
        if self.state == 'new':
            User.validate_username(self.username)
        else:
            if not User.check_username(self.username):
                raise InvalidCredentialException(
                    'username',
                    self.username,
                    'Username must match a username in the database.'
                )

        # Check that the password is a hash.
        if not pbkdf2_sha256.identify(self.password):
            raise InvalidCredentialException(
                'password',
                self.password,
                ('Password must be hashed according '
                 'to the specified hashing policy.')
            )

        # Raises an InvalidRoleException if role, or ancestor doesn't exist.
        User.validate_roles(self.countries, self.roles)

        # Raises an InvalidCredentialException if the email is not valid.
        if not User.EMAIL_REGEX.match(self.email):
            raise InvalidCredentialException('email', self.email)
    def authenticate(self, request):
        if not self._users:
            return True

        auth = request.authorization

        if not auth:
            return False

        if auth.username not in self._users:
            return False

        # Check the pbkdf2-sha256 encrypted password
        hashed_password = self._users[auth.username]
        if not pbkdf2_sha256.identify(hashed_password):
            logging.warning('Hashed password for user {} is not '
                            'valid for pbkdf2-sha256 algorithm'.format(
                                auth.username))
            return False

        if not pbkdf2_sha256.verify(auth.password, hashed_password):
            return False

        return True
示例#9
0
 def _validate(self, value):
     if not isinstance(value, (str, unicode)):
         raise TypeError('expected a string, got %s' % repr(value))
     if not pw_hasher.identify(value):
         return pw_hasher.hash(is_password(self, value))
示例#10
0
 def test_hashing_password(self):
     hashed = hashing_password("password")
     self.assertTrue(pbkdf2_sha256.identify(hashed))
示例#11
0
 def validate(self, val, obj=None, entity=None, from_db=False):
     val = super().validate(val, obj, entity, from_db)
     if not (val == '' or pw_hasher.identify(val)):
         val = pw_hasher.hash(val)
     return val
def is_it_hashed(password: str):
    return sha256.identify(password)
示例#13
0
def is_hashed(string: str) -> bool:
    return pbkdf2_sha256.identify(string)