feat: enhance routing logic and improve login screen validation; add guarded API call for error handling
This commit is contained in:
@@ -0,0 +1,18 @@
|
|||||||
|
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||||
|
|
||||||
|
import 'api_exception.dart';
|
||||||
|
import '../../features/auth/data/auth_providers.dart';
|
||||||
|
|
||||||
|
/// Executes [call] and automatically logs out the user if the server
|
||||||
|
/// returns 401 Unauthorized. Re-throws the exception so the calling
|
||||||
|
/// widget/provider can still display an error if needed.
|
||||||
|
Future<T> guardedApiCall<T>(Ref ref, Future<T> Function() call) async {
|
||||||
|
try {
|
||||||
|
return await call();
|
||||||
|
} on ApiException catch (e) {
|
||||||
|
if (e.type == ApiErrorType.unauthorized) {
|
||||||
|
await ref.read(authStateProvider.notifier).logout();
|
||||||
|
}
|
||||||
|
rethrow;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,12 +1,13 @@
|
|||||||
import 'package:flutter/widgets.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||||
import 'package:go_router/go_router.dart';
|
import 'package:go_router/go_router.dart';
|
||||||
|
|
||||||
import '../../core/ui/app_shell.dart';
|
import '../ui/app_shell.dart';
|
||||||
|
import '../ui/async_state_views.dart';
|
||||||
import '../../features/auth/data/auth_providers.dart';
|
import '../../features/auth/data/auth_providers.dart';
|
||||||
import '../../features/recipes/presentation/recipes_screen.dart';
|
|
||||||
import '../../features/auth/presentation/login_screen.dart';
|
import '../../features/auth/presentation/login_screen.dart';
|
||||||
import '../../features/profile/presentation/profile_screen.dart';
|
import '../../features/profile/presentation/profile_screen.dart';
|
||||||
|
import '../../features/recipes/presentation/recipes_screen.dart';
|
||||||
|
|
||||||
final appRouterProvider = Provider<GoRouter>((ref) {
|
final appRouterProvider = Provider<GoRouter>((ref) {
|
||||||
final authState = ref.watch(authStateProvider);
|
final authState = ref.watch(authStateProvider);
|
||||||
@@ -17,29 +18,39 @@ final appRouterProvider = Provider<GoRouter>((ref) {
|
|||||||
final isLoading = authState.isLoading;
|
final isLoading = authState.isLoading;
|
||||||
final token = authState.valueOrNull;
|
final token = authState.valueOrNull;
|
||||||
final isLoggedIn = token != null && token.isNotEmpty;
|
final isLoggedIn = token != null && token.isNotEmpty;
|
||||||
final isLoginRoute = state.matchedLocation == '/login';
|
final location = state.matchedLocation;
|
||||||
final isRootRoute = state.matchedLocation == '/';
|
final isSplash = location == '/';
|
||||||
|
final isLogin = location == '/login';
|
||||||
|
|
||||||
|
// Keep user on splash while auth state is being resolved from storage.
|
||||||
if (isLoading) {
|
if (isLoading) {
|
||||||
return null;
|
return isSplash ? null : '/';
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isRootRoute) {
|
// Redirect away from splash once auth is known.
|
||||||
|
if (isSplash) {
|
||||||
return isLoggedIn ? '/recipes' : '/login';
|
return isLoggedIn ? '/recipes' : '/login';
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!isLoggedIn && !isLoginRoute) {
|
// Unauthenticated user trying to reach a protected route.
|
||||||
|
if (!isLoggedIn && !isLogin) {
|
||||||
return '/login';
|
return '/login';
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isLoggedIn && isLoginRoute) {
|
// Authenticated user landing on login.
|
||||||
|
if (isLoggedIn && isLogin) {
|
||||||
return '/recipes';
|
return '/recipes';
|
||||||
}
|
}
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
},
|
},
|
||||||
routes: [
|
routes: [
|
||||||
GoRoute(path: '/', builder: (context, state) => const SizedBox.shrink()),
|
GoRoute(
|
||||||
|
path: '/',
|
||||||
|
builder: (context, state) => const Scaffold(
|
||||||
|
body: LoadingStateView(label: 'Startar...'),
|
||||||
|
),
|
||||||
|
),
|
||||||
GoRoute(
|
GoRoute(
|
||||||
path: '/login',
|
path: '/login',
|
||||||
builder: (context, state) => const LoginScreen(),
|
builder: (context, state) => const LoginScreen(),
|
||||||
|
|||||||
@@ -13,75 +13,104 @@ class LoginScreen extends ConsumerStatefulWidget {
|
|||||||
}
|
}
|
||||||
|
|
||||||
class _LoginScreenState extends ConsumerState<LoginScreen> {
|
class _LoginScreenState extends ConsumerState<LoginScreen> {
|
||||||
|
final _formKey = GlobalKey<FormState>();
|
||||||
final _usernameCtrl = TextEditingController();
|
final _usernameCtrl = TextEditingController();
|
||||||
final _passwordCtrl = TextEditingController();
|
final _passwordCtrl = TextEditingController();
|
||||||
|
final _passwordFocus = FocusNode();
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void dispose() {
|
void dispose() {
|
||||||
_usernameCtrl.dispose();
|
_usernameCtrl.dispose();
|
||||||
_passwordCtrl.dispose();
|
_passwordCtrl.dispose();
|
||||||
|
_passwordFocus.dispose();
|
||||||
super.dispose();
|
super.dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _submit() async {
|
Future<void> _submit() async {
|
||||||
if (_usernameCtrl.text.trim().isEmpty || _passwordCtrl.text.isEmpty) {
|
if (!(_formKey.currentState?.validate() ?? false)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
await ref.read(authStateProvider.notifier).login(
|
await ref.read(authStateProvider.notifier).login(
|
||||||
_usernameCtrl.text.trim(),
|
_usernameCtrl.text.trim(),
|
||||||
_passwordCtrl.text,
|
_passwordCtrl.text,
|
||||||
);
|
);
|
||||||
if (mounted) {
|
// Router redirect handles navigation when authStateProvider updates.
|
||||||
final state = ref.read(authStateProvider);
|
|
||||||
if (state is AsyncData && state.value != null) {
|
|
||||||
if (context.mounted) context.go('/recipes');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final authState = ref.watch(authStateProvider);
|
final authState = ref.watch(authStateProvider);
|
||||||
|
final isLoading = authState is AsyncLoading;
|
||||||
|
|
||||||
return Scaffold(
|
return Scaffold(
|
||||||
appBar: AppBar(title: const Text('Logga in')),
|
appBar: AppBar(title: const Text('Logga in')),
|
||||||
body: Padding(
|
body: Center(
|
||||||
|
child: SingleChildScrollView(
|
||||||
padding: const EdgeInsets.all(24),
|
padding: const EdgeInsets.all(24),
|
||||||
|
child: ConstrainedBox(
|
||||||
|
constraints: const BoxConstraints(maxWidth: 400),
|
||||||
|
child: Form(
|
||||||
|
key: _formKey,
|
||||||
child: Column(
|
child: Column(
|
||||||
mainAxisAlignment: MainAxisAlignment.center,
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
children: [
|
children: [
|
||||||
TextField(
|
TextFormField(
|
||||||
controller: _usernameCtrl,
|
controller: _usernameCtrl,
|
||||||
decoration: const InputDecoration(labelText: 'Anvandarnamn'),
|
decoration:
|
||||||
|
const InputDecoration(labelText: 'Användarnamn'),
|
||||||
textInputAction: TextInputAction.next,
|
textInputAction: TextInputAction.next,
|
||||||
|
autofocus: true,
|
||||||
|
enabled: !isLoading,
|
||||||
|
onFieldSubmitted: (_) =>
|
||||||
|
FocusScope.of(context).requestFocus(_passwordFocus),
|
||||||
|
validator: (value) {
|
||||||
|
if (value == null || value.trim().isEmpty) {
|
||||||
|
return 'Ange ditt användarnamn.';
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
},
|
||||||
),
|
),
|
||||||
const SizedBox(height: 12),
|
const SizedBox(height: 16),
|
||||||
TextField(
|
TextFormField(
|
||||||
controller: _passwordCtrl,
|
controller: _passwordCtrl,
|
||||||
|
focusNode: _passwordFocus,
|
||||||
decoration: const InputDecoration(labelText: 'Lösenord'),
|
decoration: const InputDecoration(labelText: 'Lösenord'),
|
||||||
obscureText: true,
|
obscureText: true,
|
||||||
textInputAction: TextInputAction.done,
|
textInputAction: TextInputAction.done,
|
||||||
onSubmitted: (_) => _submit(),
|
enabled: !isLoading,
|
||||||
|
onFieldSubmitted: (_) => _submit(),
|
||||||
|
validator: (value) {
|
||||||
|
if (value == null || value.isEmpty) {
|
||||||
|
return 'Ange ditt lösenord.';
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
},
|
||||||
),
|
),
|
||||||
const SizedBox(height: 24),
|
const SizedBox(height: 28),
|
||||||
if (authState is AsyncLoading)
|
if (isLoading)
|
||||||
const CircularProgressIndicator()
|
const Center(child: CircularProgressIndicator())
|
||||||
else
|
else
|
||||||
ElevatedButton(
|
FilledButton(
|
||||||
onPressed: _submit,
|
onPressed: _submit,
|
||||||
child: const Text('Logga in'),
|
child: const Text('Logga in'),
|
||||||
),
|
),
|
||||||
if (authState is AsyncError)
|
if (authState is AsyncError)
|
||||||
Padding(
|
Padding(
|
||||||
padding: const EdgeInsets.only(top: 12),
|
padding: const EdgeInsets.only(top: 16),
|
||||||
child: Text(
|
child: Text(
|
||||||
mapErrorToUserMessage(authState.error!),
|
mapErrorToUserMessage(authState.error!),
|
||||||
textAlign: TextAlign.center,
|
textAlign: TextAlign.center,
|
||||||
style: TextStyle(color: Theme.of(context).colorScheme.error),
|
style: TextStyle(
|
||||||
|
color: Theme.of(context).colorScheme.error),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||||
|
|
||||||
import '../../../core/api/api_providers.dart';
|
import '../../../core/api/api_providers.dart';
|
||||||
|
import '../../../core/api/guarded_api_call.dart';
|
||||||
import '../../../features/auth/data/auth_providers.dart';
|
import '../../../features/auth/data/auth_providers.dart';
|
||||||
import 'recipe_repository.dart';
|
|
||||||
import '../domain/recipe.dart';
|
import '../domain/recipe.dart';
|
||||||
|
import 'recipe_repository.dart';
|
||||||
|
|
||||||
final recipeRepositoryProvider = Provider<RecipeRepository>((ref) {
|
final recipeRepositoryProvider = Provider<RecipeRepository>((ref) {
|
||||||
return RecipeRepository(ref.watch(apiClientProvider));
|
return RecipeRepository(ref.watch(apiClientProvider));
|
||||||
@@ -10,5 +12,8 @@ final recipeRepositoryProvider = Provider<RecipeRepository>((ref) {
|
|||||||
|
|
||||||
final recipesProvider = FutureProvider<List<Recipe>>((ref) async {
|
final recipesProvider = FutureProvider<List<Recipe>>((ref) async {
|
||||||
final token = await ref.watch(authStateProvider.future);
|
final token = await ref.watch(authStateProvider.future);
|
||||||
return ref.watch(recipeRepositoryProvider).fetchRecipes(token: token);
|
return guardedApiCall(
|
||||||
|
ref,
|
||||||
|
() => ref.read(recipeRepositoryProvider).fetchRecipes(token: token),
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user