authRedirect function
Determines the redirect path based on authentication state, MFA level, and (optionally) the user's last-used mode.
Returns /login when unauthenticated (unless on a public auth page),
/mfa-verify when authenticated at AAL1 but MFA is enrolled, a
/org/:orgId path when the user is admin-eligible and their last-used
mode is 'org', / when fully authenticated, or null for no redirect.
When provided, lastMode, adminOrgIds, and lastActiveOrgId control
the post-login landing for admins. The caller reads these from Riverpod
(they're async) and passes whatever is currently resolved; if any are
null (provider still loading) we skip the org-mode redirect and send the
user to / as before — they can toggle into org mode manually.
Implementation
@visibleForTesting
String? authRedirect(
Session? session,
GoRouterState state, {
String? lastMode,
List<String>? adminOrgIds,
String? lastActiveOrgId,
}) {
final location = state.matchedLocation;
final isOnLogin = location == '/login' || location == '/forgot-password';
// `/reset-password` is the destination of the password-reset email deep
// link. It must be reachable both unauthenticated (recovery token in URL
// hash hasn't established a session yet) and authenticated (user changing
// their password from a logged-in state) — so it's excluded from both the
// "send to /login" and "send home" branches below.
final isOnResetPassword = location == '/reset-password';
final isOnMfaVerify = location == '/mfa-verify';
// Unauthenticated: allow public auth pages only.
if (session == null && !isOnLogin && !isOnResetPassword) {
return '/login';
}
// Authenticated on login/forgot-password: check MFA before going home.
if (session != null && isOnLogin) {
final aal = Supabase.instance.client.auth.mfa
.getAuthenticatorAssuranceLevel();
if (aal.currentLevel == AuthenticatorAssuranceLevels.aal1 &&
aal.nextLevel == AuthenticatorAssuranceLevels.aal2) {
return '/mfa-verify';
}
return _landingForAuthenticatedUser(
lastMode: lastMode,
adminOrgIds: adminOrgIds,
lastActiveOrgId: lastActiveOrgId,
);
}
// Authenticated on MFA verify: redirect home once at AAL2.
if (session != null && isOnMfaVerify) {
final aal = Supabase.instance.client.auth.mfa
.getAuthenticatorAssuranceLevel();
if (aal.currentLevel == AuthenticatorAssuranceLevels.aal2) {
return _landingForAuthenticatedUser(
lastMode: lastMode,
adminOrgIds: adminOrgIds,
lastActiveOrgId: lastActiveOrgId,
);
}
return null;
}
return null;
}