<s> """<STR_LIT>""" <EOL> import binascii <EOL> from datetime import date <EOL> from aspen import Response <EOL> from gratipay . models . participant import Participant <EOL> from gratipay . security import csrf <EOL> from gratipay . security . crypto import constant_time_compare <EOL> from gratipay . security . user import User , SESSION <EOL> ANON = User ( ) <EOL> def _get_user_via_api_key ( api_key ) : <EOL> """<STR_LIT>""" <EOL> user = User ( Participant . _from_thing ( '<STR_LIT>' , api_key ) ) <EOL> if user . participant : <EOL> p = user . participant <EOL> today = date . today ( ) <EOL> if p . old_auth_usage != today : <EOL> Participant . db . run ( """<STR_LIT>""" , ( today , p . id ) ) <EOL> return user <EOL> def _get_user_via_basic_auth ( auth_header ) : <EOL> """<STR_LIT>""" <EOL> try : <EOL> creds = binascii . a2b_base64 ( auth_header [ len ( '<STR_LIT>' ) : ] ) . split ( '<STR_LIT::>' , <NUM_LIT:1> ) <EOL> except binascii . Error : <EOL> raise Response ( <NUM_LIT> , '<STR_LIT>' ) <EOL> if len ( creds ) != <NUM_LIT:2> : <EOL> raise Response ( <NUM_LIT> ) <EOL> userid , api_key = creds <EOL> if len ( userid ) == <NUM_LIT> and '<STR_LIT:->' in userid : <EOL> user = _get_user_via_api_key ( userid ) <EOL> else : <EOL> try : <EOL> userid = int ( userid ) <EOL> except ValueError : <EOL> raise Response ( <NUM_LIT> ) <EOL> user = User . from_id ( userid ) <EOL> if user . ANON or not constant_time_compare ( user . participant . api_key , api_key ) : <EOL> raise Response ( <NUM_LIT> ) <EOL> return user <EOL> def _turn_off_csrf ( request ) : <EOL> """<STR_LIT>""" <EOL> csrf_token = csrf . _get_new_token ( ) <EOL> request . headers . cookie [ '<STR_LIT>' ] = csrf_token <EOL> request . headers [ '<STR_LIT>' ] = csrf_token <EOL> def start_user_as_anon ( ) : <EOL> """<STR_LIT>""" <EOL> return { '<STR_LIT:user>' : ANON } <EOL> def authenticate_user_if_possible ( request , user ) : <EOL> """<STR_LIT>""" <EOL> if request . line . uri . startswith ( '<STR_LIT>' ) : <EOL> pass <EOL> elif '<STR_LIT>' in request . headers : <EOL> header = request . headers [ '<STR_LIT>' ] <EOL> if header . startswith ( '<STR_LIT>' ) : <EOL> user = _get_user_via_basic_auth ( header ) <EOL> if not user . ANON : <EOL> _turn_off_csrf ( request ) <EOL> elif SESSION in request . headers . cookie : <EOL> token = request . headers . cookie [ SESSION ] . value <EOL> user = User . from_session_token ( token ) <EOL> return { '<STR_LIT:user>' : user } <EOL> def add_auth_to_response ( response , request = None , user = ANON ) : <EOL> if request is None : <EOL> return <EOL> if request . line . uri . startswith ( '<STR_LIT>' ) : <EOL> return <EOL> if SESSION in request . headers . cookie : <EOL> if not user . ANON : <EOL> user . keep_signed_in ( response . headers . cookie ) </s>
