@@ -707,6 +707,105 @@ def test_wrong_cookie_value(self):
707707 )
708708
709709
710+ ###############################################################################
711+
712+ EXCLUDED_PATHS_APP = Router (
713+ routes = [
714+ Route ("/" , EchoEndpoint ),
715+ Route (
716+ "/foo/" ,
717+ EchoEndpoint ,
718+ ),
719+ Route (
720+ "/foo/1/" ,
721+ EchoEndpoint ,
722+ ),
723+ Route (
724+ "/bar/" ,
725+ EchoEndpoint ,
726+ ),
727+ Route (
728+ "/bar/1/" ,
729+ EchoEndpoint ,
730+ ),
731+ ]
732+ )
733+
734+
735+ class TestExcludedPaths (SessionTestCase ):
736+ """
737+ Make sure that if `excluded_paths` is set, then the middleware allows the
738+ request to continue without a cookie.
739+ """
740+
741+ def create_user_and_session (self ):
742+ user = BaseUser (
743+ ** self .credentials , active = True , admin = True , superuser = True
744+ )
745+ user .save ().run_sync ()
746+ SessionsBase .create_session_sync (user_id = user .id )
747+
748+ def setUp (self ):
749+ super ().setUp ()
750+
751+ # Add a session to the database to make it more realistic.
752+ self .create_user_and_session ()
753+
754+ def test_excluded_paths (self ):
755+ """
756+ Make sure that only the `excluded_paths` are accessible
757+ """
758+ app = AuthenticationMiddleware (
759+ EXCLUDED_PATHS_APP ,
760+ SessionsAuthBackend (
761+ allow_unauthenticated = False ,
762+ excluded_paths = ["/foo/" ],
763+ ),
764+ )
765+ client = TestClient (app )
766+
767+ for path in ("/" , "/foo/1/" , "/bar/" , "/bar/1/" ):
768+ response = client .get (path )
769+ self .assertEqual (response .status_code , 400 )
770+ self .assertEqual (response .content , b"No session cookie found." )
771+
772+ response = client .get ("/foo/" )
773+ assert response .status_code == 200
774+ self .assertDictEqual (
775+ response .json (),
776+ {"is_unauthenticated_user" : True , "is_authenticated" : False },
777+ )
778+
779+ def test_excluded_paths_wildcard (self ):
780+ """
781+ Make sure that wildcard paths work correctly.
782+ """
783+ app = AuthenticationMiddleware (
784+ EXCLUDED_PATHS_APP ,
785+ SessionsAuthBackend (
786+ allow_unauthenticated = False ,
787+ excluded_paths = ["/foo/*" ],
788+ ),
789+ )
790+ client = TestClient (app )
791+
792+ for path in ("/" , "/bar/" , "/bar/1/" ):
793+ response = client .get (path )
794+ self .assertEqual (response .status_code , 400 )
795+ self .assertEqual (response .content , b"No session cookie found." )
796+
797+ for path in ("/foo/" , "/foo/1/" ):
798+ response = client .get (path )
799+ self .assertEqual (response .status_code , 200 )
800+ self .assertDictEqual (
801+ response .json (),
802+ {"is_unauthenticated_user" : True , "is_authenticated" : False },
803+ )
804+
805+
806+ ###############################################################################
807+
808+
710809class TestHooks (SessionTestCase ):
711810 def test_hooks (self ):
712811 # TODO Replace these with mocks ...
0 commit comments