<s> from __future__ import unicode_literals <EOL> from django . conf import settings <EOL> from django . utils import timezone <EOL> from django . utils . translation import ugettext_lazy as _ <EOL> import rest_framework . authentication <EOL> from rest_framework import exceptions <EOL> import nodeconductor . logging . middleware <EOL> TOKEN_KEY = settings . NODECONDUCTOR . get ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> class TokenAuthentication ( rest_framework . authentication . TokenAuthentication ) : <EOL> """<STR_LIT>""" <EOL> def get_authorization_value ( self , request ) : <EOL> auth = rest_framework . authentication . get_authorization_header ( request ) <EOL> if not auth : <EOL> auth = request . query_params . get ( TOKEN_KEY , '<STR_LIT>' ) <EOL> return auth <EOL> def authenticate_credentials ( self , key ) : <EOL> try : <EOL> token = self . model . objects . select_related ( '<STR_LIT:user>' ) . get ( key = key ) <EOL> except self . model . DoesNotExist : <EOL> raise exceptions . AuthenticationFailed ( _ ( '<STR_LIT>' ) ) <EOL> if not token . user . is_active : <EOL> raise exceptions . AuthenticationFailed ( _ ( '<STR_LIT>' ) ) <EOL> if token . created < timezone . now ( ) - timezone . timedelta ( hours = <NUM_LIT:1> ) : <EOL> raise exceptions . AuthenticationFailed ( _ ( '<STR_LIT>' ) ) <EOL> else : <EOL> token . created = timezone . now ( ) <EOL> token . save ( ) <EOL> return token . user , token <EOL> def authenticate ( self , request ) : <EOL> auth = self . get_authorization_value ( request ) . split ( ) <EOL> if not auth or auth [ <NUM_LIT:0> ] . lower ( ) != b'<STR_LIT>' : <EOL> return None <EOL> if len ( auth ) == <NUM_LIT:1> : <EOL> msg = _ ( '<STR_LIT>' ) <EOL> raise exceptions . AuthenticationFailed ( msg ) <EOL> elif len ( auth ) > <NUM_LIT:2> : <EOL> msg = _ ( '<STR_LIT>' ) <EOL> raise exceptions . AuthenticationFailed ( msg ) <EOL> return self . authenticate_credentials ( auth [ <NUM_LIT:1> ] ) <EOL> def user_capturing_auth ( auth ) : <EOL> class CapturingAuthentication ( auth ) : <EOL> def authenticate ( self , request ) : <EOL> result = super ( CapturingAuthentication , self ) . authenticate ( request ) <EOL> if result is not None : <EOL> user , _ = result <EOL> nodeconductor . logging . middleware . set_current_user ( user ) <EOL> return result <EOL> return CapturingAuthentication <EOL> SessionAuthentication = user_capturing_auth ( rest_framework . authentication . SessionAuthentication ) <EOL> TokenAuthentication = user_capturing_auth ( TokenAuthentication ) </s>
