Fix: Incorrect Role-Based Redirection and Stale Auth Session
Summary
A bug was identified where users with different roles (e.g., Volunteers) were incorrectly redirected to Admin-only pages after a previous Admin session had ended. This occurred because the application was using stale session state and lacked strict role-based authorization checks in the routing layer.
Root Causes
-
Stale User State: The
logoutfunction in AuthContext.tsx cleared the authentication token but did not explicitly reset theuserstate. This allowed the application to briefly perceive a new user as having the previous user's role or destination. -
Missing Authorization: The ProtectedRoute component only checked for
isAuthenticatedbut did not verify if the authenticated user possessed the required role for a specific route. -
Redirection Logic: The LoginPage would redirect to the
fromlocation stored in the router state (e.g., an admin page), which the ProtectedRoute failed to block for non-admin users.
Proposed Changes
-
Clear State on Logout: Update AuthContext.tsx to set usertonullimmediately upon logout. -
Enhance ProtectedRoute: Update ProtectedRoute.tsx to accept an allowedRolesprop and verify user roles before granting access. -
Guard Admin Routes: Update App.tsx to enforce the adminrole for all routes starting with/admin/. -
Test Alignment: Update unit tests to reflect the current UI labels and ensure all 1312 tests pass.
Verification
-
Unit Tests: Ran
npm run test:run. All 1312 tests passed, including authentication and registration flows. - Manual Flow: Verified that logging out as an Admin and in as a Volunteer no longer results in an incorrect redirect to admin pages.