feat: implement API client with JSON handling and error mapping; enhance routing and state management in app shell
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
import 'dart:convert';
|
||||
import '../../../core/api/api_client.dart';
|
||||
import '../../../core/api/api_exception.dart';
|
||||
import '../../../core/platform/token_storage.dart';
|
||||
|
||||
class AuthRepository {
|
||||
@@ -9,17 +9,37 @@ class AuthRepository {
|
||||
AuthRepository(this._api, this._storage);
|
||||
|
||||
Future<String> login(String username, String password) async {
|
||||
final response = await _api.post(
|
||||
'/auth/login',
|
||||
jsonEncode({'username': username, 'password': password}),
|
||||
);
|
||||
if (response.statusCode != 200 && response.statusCode != 201) {
|
||||
throw Exception('Login failed: ${response.statusCode}');
|
||||
try {
|
||||
final data = await _api.postJson(
|
||||
'/auth/login',
|
||||
body: {'username': username, 'password': password},
|
||||
);
|
||||
|
||||
if (data is! Map<String, dynamic>) {
|
||||
throw const ApiException(
|
||||
type: ApiErrorType.unknown,
|
||||
message: 'Ogiltigt svar fran servern.',
|
||||
);
|
||||
}
|
||||
|
||||
final token = data['accessToken'];
|
||||
if (token is! String || token.isEmpty) {
|
||||
throw const ApiException(
|
||||
type: ApiErrorType.unknown,
|
||||
message: 'Svar saknar access token.',
|
||||
);
|
||||
}
|
||||
|
||||
await _storage.saveToken(token);
|
||||
return token;
|
||||
} on ApiException {
|
||||
rethrow;
|
||||
} catch (_) {
|
||||
throw const ApiException(
|
||||
type: ApiErrorType.network,
|
||||
message: 'Kunde inte na servern.',
|
||||
);
|
||||
}
|
||||
final data = jsonDecode(response.body) as Map<String, dynamic>;
|
||||
final token = data['accessToken'] as String;
|
||||
await _storage.saveToken(token);
|
||||
return token;
|
||||
}
|
||||
|
||||
Future<void> logout() => _storage.deleteToken();
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
import '../../../core/api/api_error_mapper.dart';
|
||||
import '../data/auth_providers.dart';
|
||||
|
||||
class LoginScreen extends ConsumerStatefulWidget {
|
||||
@@ -72,7 +74,8 @@ class _LoginScreenState extends ConsumerState<LoginScreen> {
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 12),
|
||||
child: Text(
|
||||
'Inloggning misslyckades',
|
||||
mapErrorToUserMessage(authState.error!),
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(color: Theme.of(context).colorScheme.error),
|
||||
),
|
||||
),
|
||||
|
||||
Reference in New Issue
Block a user