This repository has been archived by the owner on Feb 25, 2022. It is now read-only.
Route Guard (security feature)? #296
longtimedeveloper
started this conversation in
Ideas
Replies: 2 comments 2 replies
-
Check out redirection: https://gorouter.dev/redirection |
Beta Was this translation helpful? Give feedback.
1 reply
-
Here is a compose function if you want to combine multiple guards, which will let you "fall through" multiple guards until you hit one that returns a redirect or returns null by default. FYI probably isn't perfect. You want to pass typedef Next<K> = K? Function();
typedef Middleware<T, K> = K? Function(T state, Next<K> next);
K? Function(T) _compose<T, K>(List<Middleware<T, K>> middlewares) {
return (T state) {
var lastIndex = -1;
K? dispatch(int index) {
if (index <= lastIndex) {
throw Exception('next() called multiple times');
}
lastIndex = index;
if (index < middlewares.length) {
return middlewares[index](state, () => dispatch(index + 1));
}
return null;
}
return dispatch(0);
};
} usage String? privateGuard(GoRouterState state, Next<String> next) {
return ref.read(authProvider).maybeWhen(
orElse: () => LoginScreen.path,
loggedIn: () => next(),
);
}
String? adminRoleGuard(GoRouterState state, Next<String> next) {
return ref.read(roleProvider).maybeWhen(
orElse: () => LoginScreen.path,
isAdmin: () => next(),
);
}
//...
// Private routes
GoRoute(
path: HomeScreen.path,
redirect: _compose([privateGuard]),
pageBuilder: (context, state) => NoTransitionPage(
key: state.pageKey,
child: const HomeScreen(),
),
),
GoRoute(
path: SettingsScreen.path,
redirect: _compose([privateGuard,adminRoleGuard]),
pageBuilder: (context, state) => NoTransitionPage(
key: state.pageKey,
child: const SettingsScreen(),
),
),
//... |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hi Chris,
I can't find the concept of a Route Guards.
Does Go Router support route guards similar to AutoRoute Route Guards
Best regards,
Karl
Beta Was this translation helpful? Give feedback.
All reactions