This is how I've modified the default XXX/model/auth.py in order to expose password hashing as a classmethod. This is so as to make it easier to generate hashed passwords from a Python prompt. Then, applications where the users list is known in advance can hardcode those users in the deployment scripts without any fear of leaking clear-text passwords :-)
@classmethod
def hash_password(cls, password):
"""From a clear text password, return a hashed password."""
hashed_password = password
if isinstance(password, unicode):
password_8bit = password.encode('UTF-8')
else:
password_8bit = password
salt = sha1()
salt.update(os.urandom(60))
hash = sha1()
hash.update(password_8bit + salt.hexdigest())
hashed_password = salt.hexdigest() + hash.hexdigest()
# make sure the hased password is an UTF-8 object at the end of the
# process because SQLAlchemy _wants_ a unicode object for Unicode columns
if not isinstance(hashed_password, unicode):
hashed_password = hashed_password.decode('UTF-8')
return hashed_password
def _set_password(self, password):
"""Hash password on the fly."""
self._password = self.hash_password(password)
03/18/09 15:44:22 changed by Gustavo
keywords set to authentication, model.
owner set to Gustavo.
status changed from new to assigned.
milestone changed from 2.0rc1 to 2.1.
Sounds good.
Delete (follow-up: ↓ 4 ) 03/18/09 20:26:00 changed by mramm
Why not go the whole way and make it a static method? Not that it makes a big difference, but hash_password doesn't need cls or self...
Delete 03/19/09 05:37:15 changed by pitrou
Well, I can't think of a case where a staticmethod would be more useful than a classmethod. I find classmethods generally more flexible (but since the calling convention is the same I agree it doesn't make much of a difference, it can be changed back later).
Delete (in reply to: ↑ 2 ) 03/19/09 06:01:25 changed by Gustavo
Replying to mramm:
Why not go the whole way and make it a static method? Not that it makes a big difference, but hash_password doesn't need cls or self...
+1