<s> from u2fval . model import User , Transaction <EOL> from u2fval . core . exc import BadInputException <EOL> from datetime import datetime , timedelta <EOL> from binascii import b2a_hex <EOL> class DBStore ( object ) : <EOL> def __init__ ( self , session , max_transactions = <NUM_LIT:5> , ttl = <NUM_LIT> ) : <EOL> self . _session = session <EOL> self . _max_transactions = max_transactions <EOL> self . _ttl = ttl <EOL> def _delete_expired ( self ) : <EOL> expiration = datetime . utcnow ( ) - timedelta ( seconds = self . _ttl ) <EOL> self . _session . query ( Transaction ) . filter ( Transaction . created_at < expiration ) . delete ( ) <EOL> def store ( self , client_id , user_id , transaction_id , data ) : <EOL> transaction_id = b2a_hex ( transaction_id ) <EOL> user = self . _session . query ( User ) . filter ( User . client_id == client_id ) . filter ( User . name == user_id ) . first ( ) <EOL> if user is None : <EOL> user = User ( user_id ) <EOL> user . client_id = client_id <EOL> self . _session . add ( user ) <EOL> else : <EOL> self . _delete_expired ( ) <EOL> for transaction in user . transactions . offset ( self . _max_transactions - <NUM_LIT:1> ) . all ( ) : <EOL> self . _session . delete ( transaction ) <EOL> user . transactions . append ( Transaction ( transaction_id , data ) ) <EOL> def retrieve ( self , client_id , user_id , transaction_id ) : <EOL> transaction_id = b2a_hex ( transaction_id ) <EOL> self . _delete_expired ( ) <EOL> transaction = self . _session . query ( Transaction ) . filter ( Transaction . transaction_id == transaction_id ) . first ( ) <EOL> if transaction is None : <EOL> raise BadInputException ( '<STR_LIT>' ) <EOL> if transaction . user . name != user_id or transaction . user . client_id != client_id : <EOL> raise BadInputException ( '<STR_LIT>' <EOL> % user_id ) <EOL> self . _session . delete ( transaction ) <EOL> return transaction . data </s>
