feat: add RouteGuard for authentication
This commit is contained in:
45
lib/src/standards/route_guard.dart
Normal file
45
lib/src/standards/route_guard.dart
Normal file
@@ -0,0 +1,45 @@
|
||||
import 'package:get/get.dart';
|
||||
import 'package:mom_kitchen/src/standards/app_pages.dart';
|
||||
import 'package:mom_kitchen/src/controllers/profile_controller.dart';
|
||||
|
||||
enum AuthLevel { none, optional, required }
|
||||
|
||||
class RouteGuard {
|
||||
static bool canAccess(String route, {String? userId}) {
|
||||
final pageInfo = PageRegistry.getPage(route);
|
||||
if (pageInfo == null) return false;
|
||||
|
||||
final authLevel = pageInfo.metadata?['authLevel'] as AuthLevel? ?? AuthLevel.none;
|
||||
|
||||
switch (authLevel) {
|
||||
case AuthLevel.none:
|
||||
return true;
|
||||
case AuthLevel.optional:
|
||||
return true;
|
||||
case AuthLevel.required:
|
||||
return userId != null && userId.isNotEmpty;
|
||||
}
|
||||
}
|
||||
|
||||
static String? getRedirectRoute(String route, {String? userId}) {
|
||||
if (canAccess(route, userId: userId)) return null;
|
||||
|
||||
return '/login';
|
||||
}
|
||||
|
||||
static Future<bool> checkAuth(String route) async {
|
||||
final profileController = Get.find<ProfileController>();
|
||||
await profileController.checkLoginStatus();
|
||||
|
||||
final userId = profileController.user.value?.id;
|
||||
return canAccess(route, userId: userId);
|
||||
}
|
||||
|
||||
static Future<String?> getAuthRedirect(String route) async {
|
||||
final profileController = Get.find<ProfileController>();
|
||||
await profileController.checkLoginStatus();
|
||||
|
||||
final userId = profileController.user.value?.id;
|
||||
return getRedirectRoute(route, userId: userId);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user