<s> from django . http import HttpResponse , HttpResponseBadRequest <EOL> def is_admin ( user ) : <EOL> """<STR_LIT>""" <EOL> from api . models import db_model <EOL> dbc = db_model . connect ( ) <EOL> user = dbc . hbuser . find_one ( { "<STR_LIT:username>" : user [ '<STR_LIT:username>' ] , "<STR_LIT>" : { "<STR_LIT>" : [ "<STR_LIT>" ] } } ) <EOL> if user is None : <EOL> return False <EOL> else : <EOL> return True <EOL> class RequireLogin ( object ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , role = None ) : <EOL> self . f = None <EOL> self . required_role = role <EOL> self . token_string = "<STR_LIT>" <EOL> self . username = None <EOL> self . user = None <EOL> def __call__ ( self , f ) : <EOL> def wrapped_f ( request , * pargs , ** kwargs ) : <EOL> from django . http import HttpResponseForbidden <EOL> self . f = f <EOL> if '<STR_LIT>' in request . META : <EOL> self . token_string = request . META [ '<STR_LIT>' ] <EOL> if self . valid_token ( ) : <EOL> user = self . fetch_user ( ) <EOL> if user is None : <EOL> return HttpResponseBadRequest ( "<STR_LIT>" ) <EOL> if ( self . required_role is not None ) and ( self . required_role not in user [ '<STR_LIT>' ] ) : <EOL> return HttpResponseForbidden ( ) <EOL> request . user = user <EOL> request . token_string = self . token_string <EOL> return self . f ( request , * pargs , ** kwargs ) <EOL> return HttpResponse ( status = <NUM_LIT> ) <EOL> return wrapped_f <EOL> def fetch_user ( self ) : <EOL> """<STR_LIT>""" <EOL> from api . models import db_model <EOL> dbc = db_model . connect ( ) <EOL> return dbc . hbuser . find_one ( { "<STR_LIT:username>" : self . username } ) <EOL> def valid_token ( self ) : <EOL> """<STR_LIT>""" <EOL> from api . models import redis_wrapper <EOL> from django . conf import settings <EOL> r = redis_wrapper . init_redis ( ) <EOL> username = r . get ( self . token_string ) <EOL> if username is None : <EOL> return False <EOL> else : <EOL> self . username = username <EOL> r . expire ( self . token_string , settings . TOKEN_TTL ) <EOL> return True </s>
