<s> """<STR_LIT>""" <EOL> from aiorest_ws . abstract import AbstractMiddleware <EOL> from aiorest_ws . auth . user . models import UserSQLiteModel <EOL> from aiorest_ws . auth . user . abstractions import User <EOL> from aiorest_ws . auth . token . backends import InMemoryTokenBackend <EOL> from aiorest_ws . auth . token . exceptions import TokenNotProvidedException <EOL> from aiorest_ws . auth . token . managers import JSONWebTokenManager <EOL> from aiorest_ws . utils . modify import add_property <EOL> __all__ = ( '<STR_LIT>' , '<STR_LIT>' , ) <EOL> class BaseTokenMiddleware ( AbstractMiddleware ) : <EOL> """<STR_LIT>""" <EOL> def init_credentials ( self , request ) : <EOL> """<STR_LIT>""" <EOL> pass <EOL> def authenticate ( self , request , handler ) : <EOL> """<STR_LIT>""" <EOL> pass <EOL> def process_request ( self , request , handler ) : <EOL> """<STR_LIT>""" <EOL> self . init_credentials ( request ) <EOL> self . authenticate ( request , handler ) <EOL> class JSONWebTokenMiddleware ( BaseTokenMiddleware ) : <EOL> """<STR_LIT>""" <EOL> storage_backend = InMemoryTokenBackend <EOL> manager = JSONWebTokenManager <EOL> user_model = UserSQLiteModel <EOL> def __init__ ( self ) : <EOL> super ( JSONWebTokenMiddleware , self ) . __init__ ( ) <EOL> self . storage_backend = self . storage_backend ( ) <EOL> self . user_model = self . user_model ( ) <EOL> self . manager = self . manager ( ) <EOL> def get_user_by_token ( self , token ) : <EOL> """<STR_LIT>""" <EOL> token_data = self . storage_backend . get ( token ) <EOL> if token_data : <EOL> user = self . user_model . get_user_by_token ( token_data ) <EOL> else : <EOL> user = User ( ) <EOL> return user <EOL> def init_credentials ( self , request ) : <EOL> """<STR_LIT>""" <EOL> token = getattr ( request , '<STR_LIT>' , None ) <EOL> if token : <EOL> token_payload = self . manager . verify ( token ) <EOL> user = self . get_user_by_token ( token ) <EOL> else : <EOL> token_payload = None <EOL> user = User ( ) <EOL> add_property ( request , '<STR_LIT:user>' , user ) <EOL> add_property ( request , '<STR_LIT>' , token_payload ) <EOL> def authenticate ( self , request , view ) : <EOL> """<STR_LIT>""" <EOL> auth_required = getattr ( view , '<STR_LIT>' , False ) <EOL> permission_classes = getattr ( view , '<STR_LIT>' , ( ) ) <EOL> if auth_required : <EOL> if hasattr ( request , '<STR_LIT>' ) and request . token : <EOL> for permission in permission_classes : <EOL> permission . check ( request , view ) <EOL> else : <EOL> raise TokenNotProvidedException ( ) </s>
