초기 커밋
This commit is contained in:
64
lib/core/router/auth_guard.dart
Normal file
64
lib/core/router/auth_guard.dart
Normal file
@@ -0,0 +1,64 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../../shared/models/user_role.dart';
|
||||
import '../../shared/providers/auth_provider.dart';
|
||||
import 'route_names.dart';
|
||||
|
||||
/// 인증/역할 기반 라우트 가드
|
||||
class AuthGuard {
|
||||
const AuthGuard(this.ref);
|
||||
|
||||
final Ref ref;
|
||||
|
||||
/// GoRouter redirect 콜백
|
||||
String? redirect(BuildContext context, String location) {
|
||||
final authState = ref.read(authStateProvider);
|
||||
|
||||
return authState.when(
|
||||
data: (user) {
|
||||
final isLoggedIn = user != null;
|
||||
final isAuthRoute =
|
||||
location.startsWith(RoutePaths.login) ||
|
||||
location.startsWith(RoutePaths.register);
|
||||
|
||||
// 비로그인 사용자가 인증 페이지 외 접근 시 → 로그인으로
|
||||
if (!isLoggedIn && !isAuthRoute) {
|
||||
return RoutePaths.login;
|
||||
}
|
||||
|
||||
// 로그인 사용자가 인증 페이지 접근 시 → 역할에 따라 리다이렉트
|
||||
if (isLoggedIn && isAuthRoute) {
|
||||
return _redirectByRole(user!.role);
|
||||
}
|
||||
|
||||
// 역할 기반 접근 제어
|
||||
if (isLoggedIn) {
|
||||
return _checkRoleAccess(location, user!.role);
|
||||
}
|
||||
|
||||
return null;
|
||||
},
|
||||
loading: () => null,
|
||||
error: (_, __) => RoutePaths.login,
|
||||
);
|
||||
}
|
||||
|
||||
/// 역할에 따른 기본 페이지 리다이렉트
|
||||
String _redirectByRole(UserRole role) {
|
||||
return switch (role) {
|
||||
UserRole.admin => RoutePaths.adminHome,
|
||||
UserRole.user => RoutePaths.userHome,
|
||||
};
|
||||
}
|
||||
|
||||
/// 역할 기반 접근 제어
|
||||
String? _checkRoleAccess(String location, UserRole role) {
|
||||
// 일반 사용자가 관리자 페이지 접근 시도
|
||||
if (location.startsWith(RoutePaths.admin) && role != UserRole.admin) {
|
||||
return RoutePaths.userHome;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user