comparison pylons_app/lib/auth.py @ 415:04e8b31fb245

Changed password crypting scheme to bcrypt, added dependency for setup
author Marcin Kuzminski <marcin@python-works.com>
date Fri, 20 Aug 2010 10:59:18 +0200
parents b6a25169c005
children 3ed2d46a2ca7
comparison
equal deleted inserted replaced
414:27f801e03489 415:04e8b31fb245
28 from pylons_app.lib.utils import get_repo_slug 28 from pylons_app.lib.utils import get_repo_slug
29 from pylons_app.model import meta 29 from pylons_app.model import meta
30 from pylons_app.model.db import User, RepoToPerm, Repository, Permission 30 from pylons_app.model.db import User, RepoToPerm, Repository, Permission
31 from sqlalchemy.exc import OperationalError 31 from sqlalchemy.exc import OperationalError
32 from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound 32 from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
33 import hashlib 33 import bcrypt
34 from decorator import decorator 34 from decorator import decorator
35 import logging 35 import logging
36 36
37 log = logging.getLogger(__name__) 37 log = logging.getLogger(__name__)
38 38
39 def get_crypt_password(password): 39 def get_crypt_password(password):
40 """Cryptographic function used for password hashing based on sha1 40 """Cryptographic function used for password hashing based on sha1
41 @param password: password to hash 41 @param password: password to hash
42 """ 42 """
43 hashed = hashlib.sha1(password).hexdigest() 43 return bcrypt.hashpw(password, bcrypt.gensalt(10))
44 return hashed[3:] + hashed[:3] 44
45 def check_password(password, hashed):
46 return bcrypt.hashpw(password, hashed) == hashed
45 47
46 @cache_region('super_short_term', 'cached_user') 48 @cache_region('super_short_term', 'cached_user')
47 def get_user_cached(username): 49 def get_user_cached(username):
48 sa = meta.Session 50 sa = meta.Session
49 try: 51 try:
51 finally: 53 finally:
52 meta.Session.remove() 54 meta.Session.remove()
53 return user 55 return user
54 56
55 def authfunc(environ, username, password): 57 def authfunc(environ, username, password):
56 password_crypt = get_crypt_password(password)
57 try: 58 try:
58 user = get_user_cached(username) 59 user = get_user_cached(username)
59 except (NoResultFound, MultipleResultsFound, OperationalError) as e: 60 except (NoResultFound, MultipleResultsFound, OperationalError) as e:
60 log.error(e) 61 log.error(e)
61 user = None 62 user = None
62 63
63 if user: 64 if user:
64 if user.active: 65 if user.active:
65 if user.username == username and user.password == password_crypt: 66 if user.username == username and check_password(password, user.password):
66 log.info('user %s authenticated correctly', username) 67 log.info('user %s authenticated correctly', username)
67 return True 68 return True
68 else: 69 else:
69 log.error('user %s is disabled', username) 70 log.error('user %s is disabled', username)
70 71