<s> import jwt <EOL> from django . contrib . auth import get_user_model <EOL> from django . utils . encoding import smart_text <EOL> from django . utils . translation import ugettext as _ <EOL> from rest_framework import exceptions <EOL> from rest_framework . authentication import ( <EOL> BaseAuthentication , get_authorization_header <EOL> ) <EOL> from rest_framework_jwt . settings import api_settings <EOL> jwt_decode_handler = api_settings . JWT_DECODE_HANDLER <EOL> jwt_get_username_from_payload = api_settings . JWT_PAYLOAD_GET_USERNAME_HANDLER <EOL> class BaseJSONWebTokenAuthentication ( BaseAuthentication ) : <EOL> """<STR_LIT>""" <EOL> def authenticate ( self , request ) : <EOL> """<STR_LIT>""" <EOL> jwt_value = self . get_jwt_value ( request ) <EOL> if jwt_value is None : <EOL> return None <EOL> try : <EOL> payload = jwt_decode_handler ( jwt_value ) <EOL> except jwt . ExpiredSignature : <EOL> msg = _ ( '<STR_LIT>' ) <EOL> raise exceptions . AuthenticationFailed ( msg ) <EOL> except jwt . DecodeError : <EOL> msg = _ ( '<STR_LIT>' ) <EOL> raise exceptions . AuthenticationFailed ( msg ) <EOL> except jwt . InvalidTokenError : <EOL> raise exceptions . AuthenticationFailed ( ) <EOL> user = self . authenticate_credentials ( payload ) <EOL> return ( user , jwt_value ) <EOL> def authenticate_credentials ( self , payload ) : <EOL> """<STR_LIT>""" <EOL> User = get_user_model ( ) <EOL> username = jwt_get_username_from_payload ( payload ) <EOL> if not username : <EOL> msg = _ ( '<STR_LIT>' ) <EOL> raise exceptions . AuthenticationFailed ( msg ) <EOL> try : <EOL> user = User . objects . get_by_natural_key ( username ) <EOL> except User . DoesNotExist : <EOL> msg = _ ( '<STR_LIT>' ) <EOL> raise exceptions . AuthenticationFailed ( msg ) <EOL> if not user . is_active : <EOL> msg = _ ( '<STR_LIT>' ) <EOL> raise exceptions . AuthenticationFailed ( msg ) <EOL> return user <EOL> class JSONWebTokenAuthentication ( BaseJSONWebTokenAuthentication ) : <EOL> """<STR_LIT>""" <EOL> www_authenticate_realm = '<STR_LIT>' <EOL> def get_jwt_value ( self , request ) : <EOL> auth = get_authorization_header ( request ) . split ( ) <EOL> auth_header_prefix = api_settings . JWT_AUTH_HEADER_PREFIX . lower ( ) <EOL> if not auth or smart_text ( auth [ <NUM_LIT:0> ] . lower ( ) ) != auth_header_prefix : <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> '<STR_LIT>' ) <EOL> raise exceptions . AuthenticationFailed ( msg ) <EOL> return auth [ <NUM_LIT:1> ] <EOL> def authenticate_header ( self , request ) : <EOL> """<STR_LIT>""" <EOL> return '<STR_LIT>' . format ( api_settings . JWT_AUTH_HEADER_PREFIX , self . www_authenticate_realm ) </s>
