<s> import cherrypy <EOL> import hashlib <EOL> import re <EOL> import six <EOL> from girder import events <EOL> from girder . utility import config <EOL> from . model_base import Model , ValidationException <EOL> from . token import genToken <EOL> class Password ( Model ) : <EOL> """<STR_LIT>""" <EOL> def initialize ( self ) : <EOL> self . name = '<STR_LIT:password>' <EOL> def _digest ( self , alg , password , salt = None ) : <EOL> """<STR_LIT>""" <EOL> cur_config = config . getConfig ( ) <EOL> if alg == '<STR_LIT>' : <EOL> return hashlib . sha512 ( ( password + salt ) . encode ( '<STR_LIT:utf8>' ) ) . hexdigest ( ) <EOL> elif alg == '<STR_LIT>' : <EOL> try : <EOL> import bcrypt <EOL> except ImportError : <EOL> raise Exception ( <EOL> '<STR_LIT>' ) <EOL> password = password . encode ( '<STR_LIT:utf8>' ) <EOL> if salt is None : <EOL> rounds = int ( cur_config [ '<STR_LIT>' ] [ '<STR_LIT>' ] ) <EOL> return bcrypt . hashpw ( password , bcrypt . gensalt ( rounds ) ) <EOL> else : <EOL> if isinstance ( salt , six . text_type ) : <EOL> salt = salt . encode ( '<STR_LIT:utf8>' ) <EOL> return bcrypt . hashpw ( password , salt ) <EOL> else : <EOL> raise Exception ( '<STR_LIT>' % alg ) <EOL> def validate ( self , doc ) : <EOL> if not doc . get ( '<STR_LIT>' , '<STR_LIT>' ) : <EOL> raise Exception ( '<STR_LIT>' ) <EOL> return doc <EOL> def hasPassword ( self , user ) : <EOL> """<STR_LIT>""" <EOL> return '<STR_LIT>' in user <EOL> def authenticate ( self , user , password ) : <EOL> """<STR_LIT>""" <EOL> if not self . hasPassword ( user ) : <EOL> e = events . trigger ( '<STR_LIT>' , { <EOL> '<STR_LIT:user>' : user , <EOL> '<STR_LIT:password>' : password <EOL> } ) <EOL> if len ( e . responses ) : <EOL> return e . responses [ - <NUM_LIT:1> ] <EOL> raise ValidationException ( <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' ) <EOL> hash = self . _digest ( salt = user [ '<STR_LIT>' ] , alg = user [ '<STR_LIT>' ] , <EOL> password = password ) <EOL> if user [ '<STR_LIT>' ] == '<STR_LIT>' : <EOL> if isinstance ( user [ '<STR_LIT>' ] , six . text_type ) : <EOL> user [ '<STR_LIT>' ] = user [ '<STR_LIT>' ] . encode ( '<STR_LIT:utf8>' ) <EOL> return hash == user [ '<STR_LIT>' ] <EOL> else : <EOL> return self . load ( hash , False ) is not None <EOL> def encryptAndStore ( self , password ) : <EOL> """<STR_LIT>""" <EOL> cur_config = config . getConfig ( ) <EOL> if not re . match ( cur_config [ '<STR_LIT>' ] [ '<STR_LIT>' ] , password ) : <EOL> raise ValidationException ( <EOL> cur_config [ '<STR_LIT>' ] [ '<STR_LIT>' ] , '<STR_LIT:password>' ) <EOL> alg = cherrypy . config [ '<STR_LIT>' ] [ '<STR_LIT>' ] <EOL> if alg == '<STR_LIT>' : <EOL> """<STR_LIT>""" <EOL> salt = self . _digest ( alg = alg , password = password ) <EOL> else : <EOL> """<STR_LIT>""" <EOL> salt = genToken ( ) <EOL> hash = self . _digest ( salt = salt , alg = alg , password = password ) <EOL> self . save ( { '<STR_LIT>' : hash } ) <EOL> return salt , alg </s>
