Code reviews shouldn't be a blocker. Sourcery can review all of your PR's instantly - letting your team stay in flow and get more done.
Trusted by thousands of engineers
class User:
def __init__(self, username, email, password):
self.username = username
self._hashed_password = self._hash_password(password)
self.is_authenticated = False
def _hash_password(self, password):
return hashlib.sha256(password.encode()).hexdigest()
def authenticate(self, password):
if self._hashed_password == self._hash_password(password):
self.is_authenticated = True
class User:
def __init__(self, username, email, password):
self.username = username
self._hashed_password = self._hash_password(password)
self.is_authenticated = False
def _hash_password(self, password):
# Generate a salt and hash the password. The bcrypt.hashpw function automatically handles salting.
return bcrypt.hashpw(password.encode(), bcrypt.gensalt())
def change_password(self, old_password, new_password):
if self.authenticate(old_password):
self._hashed_password = self._hash_password(new_password)
return True
return False
def logout(self):
self.is_authenticated = False
def authenticate(self, password):
# Compare the provided password with the stored hash. The bcrypt.checkpw function securely compares the hashes.
if bcrypt.checkpw(password.encode(), self._hashed_password):
self.is_authenticated = True
return True
else:
return False
def change_password(self, old_password, new_password):
if self.authenticate(old_password):
self._hashed_password = self._hash_password(new_password)
return True
return False
def change_password(self, old_password, new_password):
"""
Changes the user's password.
Args:
old_password (str): The old password to authenticate.
new_password (str): The new password to set.
Returns:
bool: True if the password is successfully changed, False otherwise.
"""
if self.authenticate(old_password):
self._hashed_password = self._hash_password(new_password)
return True
return False
import pytest
from demo import change_password
@pytest.mark.parametrize(
"password, old_password, new_password, expected_result,
[
("password", "password", "new_password", True),
("password", "wrong_password" , "new_password", False),
...,
]
)
def test_change_password(password, old_password, new_password, expected_result):
# Arrange
user = User("username", password)
# Act
result = user.change_password(old_password, new_password)
# Assert
assert result == expected_result
match typeOfUser:
Simple, flexible pricing
Save up to 20% with yearly subscription
For individuals
10/ mo
Flying solo?
Then this plan is for you!
GitHub code reviews on every PR for your individual private repos.
For teams
30/ mo
Team Player?
We got you covered!
Code reviews for every pull request for teams of 2 to 200.