<s> from functools import wraps <EOL> from peewee import DoesNotExist <EOL> from tornado . web import HTTPError <EOL> from tornado . ioloop import IOLoop <EOL> from tornado . gen import Return , coroutine , maybe_future <EOL> from pypi_server . cache import Cache <EOL> from pypi_server . db . users import Users <EOL> from pypi_server . handlers import route <EOL> from pypi_server . handlers . api import JSONHandler , threaded <EOL> SESSION_DAYS = <NUM_LIT:3> <EOL> SESSION_SECS = SESSION_DAYS * <NUM_LIT> <EOL> @ threaded <EOL> @ Cache ( <NUM_LIT:10> ) <EOL> def find_user ( uid , is_admin = False ) : <EOL> cond = ( <EOL> Users . disabled == False , <EOL> Users . id == uid , <EOL> ) <EOL> if is_admin : <EOL> cond += ( Users . is_admin == is_admin , ) <EOL> q = Users . select ( ) . where ( * cond ) <EOL> if not q . count ( ) : <EOL> raise DoesNotExist ( "<STR_LIT>" ) <EOL> return q . limit ( <NUM_LIT:1> ) [ <NUM_LIT:0> ] <EOL> def reject ( self , reason ) : <EOL> self . clear_all_cookies ( ) <EOL> self . set_status ( <NUM_LIT> ) <EOL> raise Return ( self . response ( { <EOL> '<STR_LIT:error>' : reason <EOL> } ) ) <EOL> def authorization_required ( is_admin = False ) : <EOL> def decorator ( func ) : <EOL> @ wraps ( func ) <EOL> @ coroutine <EOL> def wrap ( self , * args , ** kwargs ) : <EOL> io_loop = IOLoop . current ( ) <EOL> uid , remote_ip , start_time = self . get_secure_cookie ( '<STR_LIT>' , ( None , None , None ) ) <EOL> if not all ( ( uid , remote_ip , start_time ) ) : <EOL> raise Return ( reject ( self , '<STR_LIT>' ) ) <EOL> if not ( start_time + SESSION_SECS ) > io_loop . time ( ) : <EOL> raise Return ( reject ( self , '<STR_LIT>' ) ) <EOL> self . current_user = yield find_user ( uid , is_admin = is_admin ) <EOL> if self . current_user . disabled : <EOL> raise Return ( reject ( self , '<STR_LIT>' ) ) <EOL> result = yield maybe_future ( func ( self , * args , ** kwargs ) ) <EOL> raise Return ( result ) <EOL> return wrap <EOL> return decorator <EOL> @ route ( "<STR_LIT>" ) <EOL> class LoginHandler ( JSONHandler ) : <EOL> @ authorization_required ( ) <EOL> def get ( self ) : <EOL> raise Return ( self . response ( { <EOL> '<STR_LIT>' : self . current_user . login , <EOL> '<STR_LIT>' : self . current_user . is_admin , <EOL> } ) ) <EOL> @ threaded <EOL> def post ( self ) : <EOL> try : <EOL> login , password = self . json [ '<STR_LIT>' ] , self . json [ '<STR_LIT:password>' ] <EOL> except KeyError : <EOL> raise HTTPError ( <NUM_LIT> ) <EOL> try : <EOL> user = Users . check ( login , password ) <EOL> except DoesNotExist : <EOL> raise HTTPError ( <NUM_LIT> ) <EOL> self . set_secure_cookie ( <EOL> '<STR_LIT>' , <EOL> ( <EOL> user . id , <EOL> self . request . remote_ip , <EOL> IOLoop . current ( ) . time ( ) <EOL> ) , <EOL> SESSION_DAYS <EOL> ) <EOL> return self . response ( { <EOL> '<STR_LIT>' : user . login , <EOL> '<STR_LIT>' : user . is_admin , <EOL> } ) </s>
