<s> import sys <EOL> import string <EOL> import hashlib <EOL> from datetime import datetime <EOL> from random import SystemRandom <EOL> from django . conf import settings as django_settings <EOL> from django . utils . http import int_to_base36 , base36_to_int <EOL> from serrano . conf import settings <EOL> HEX_CHARS = string . lowercase [ : <NUM_LIT:6> ] + string . digits <EOL> random = SystemRandom ( ) <EOL> def generate_random_token ( size = <NUM_LIT:32> , max_attempts = <NUM_LIT:100> , test = None ) : <EOL> """<STR_LIT>""" <EOL> for _ in xrange ( max_attempts ) : <EOL> key = '<STR_LIT>' . join ( random . choice ( HEX_CHARS ) for i in xrange ( size ) ) <EOL> if not test or test ( key ) : <EOL> return key <EOL> raise ValueError ( '<STR_LIT>' ) <EOL> class TokenGenerator ( object ) : <EOL> def _total_seconds ( self , dt ) : <EOL> """<STR_LIT>""" <EOL> SEC_PER_DAY = <NUM_LIT> * <NUM_LIT> <EOL> MICROSEC_PER_SEC = <NUM_LIT:10> ** <NUM_LIT:6> <EOL> timedelta = ( dt - datetime ( <NUM_LIT> , <NUM_LIT:1> , <NUM_LIT:1> ) ) <EOL> if sys . version_info >= ( <NUM_LIT:2> , <NUM_LIT:7> ) : <EOL> return int ( timedelta . total_seconds ( ) ) <EOL> else : <EOL> microseconds = timedelta . microseconds <EOL> microseconds += timedelta . seconds * MICROSEC_PER_SEC <EOL> microseconds += timedelta . days * SEC_PER_DAY * MICROSEC_PER_SEC <EOL> return int ( microseconds / MICROSEC_PER_SEC ) <EOL> def _make ( self , user , timestamp ) : <EOL> ts_b36 = int_to_base36 ( timestamp ) <EOL> total = ( django_settings . SECRET_KEY + unicode ( user . pk ) + <EOL> user . password + unicode ( timestamp ) ) <EOL> digest = hashlib . sha1 ( total ) . hexdigest ( ) [ : : <NUM_LIT:2> ] <EOL> return '<STR_LIT>' . format ( user . pk , ts_b36 , digest ) <EOL> @ property <EOL> def timeout ( self ) : <EOL> return settings . TOKEN_TIMEOUT or django_settings . SESSION_COOKIE_AGE <EOL> def split ( self , token ) : <EOL> try : <EOL> return token . split ( '<STR_LIT:->' , <NUM_LIT:1> ) [ <NUM_LIT:0> ] , token <EOL> except AttributeError : <EOL> return None , token <EOL> def make ( self , user ) : <EOL> return self . _make ( user , self . _total_seconds ( datetime . now ( ) ) ) <EOL> def check ( self , user , token ) : <EOL> try : <EOL> pk , ts_b36 , hash = token . split ( '<STR_LIT:->' ) <EOL> except ValueError : <EOL> return False <EOL> try : <EOL> ts = base36_to_int ( ts_b36 ) <EOL> except ValueError : <EOL> return False <EOL> if self . _make ( user , ts ) != token : <EOL> return False <EOL> if ( self . _total_seconds ( datetime . now ( ) ) - ts ) > self . timeout : <EOL> return False <EOL> return True <EOL> token_generator = TokenGenerator ( ) <EOL> def get_request_token ( request ) : <EOL> "<STR_LIT>" <EOL> if '<STR_LIT>' in request . REQUEST : <EOL> return request . REQUEST [ '<STR_LIT>' ] <EOL> if '<STR_LIT>' in request . META : <EOL> return request . META [ '<STR_LIT>' ] <EOL> return '<STR_LIT>' </s>
