53 lines
		
	
	
		
			1.4 KiB
		
	
	
	
		
			Dart
		
	
	
	
	
	
			
		
		
	
	
			53 lines
		
	
	
		
			1.4 KiB
		
	
	
	
		
			Dart
		
	
	
	
	
	
// ignore_for_file: non_constant_identifier_names
 | 
						|
 | 
						|
import 'package:freezed_annotation/freezed_annotation.dart';
 | 
						|
import 'package:logging/logging.dart';
 | 
						|
import 'package:moneymgr_mobile/services/api/api_client.dart';
 | 
						|
import 'package:moneymgr_mobile/services/storage/prefs.dart';
 | 
						|
 | 
						|
part 'auth_api.freezed.dart';
 | 
						|
part 'auth_api.g.dart';
 | 
						|
 | 
						|
@freezed
 | 
						|
abstract class AuthInfo with _$AuthInfo {
 | 
						|
  const factory AuthInfo({
 | 
						|
    required int id,
 | 
						|
    required String mail,
 | 
						|
    required String name,
 | 
						|
    required int time_create,
 | 
						|
    required int time_update,
 | 
						|
  }) = _AuthInfo;
 | 
						|
 | 
						|
  factory AuthInfo.fromJson(Map<String, dynamic> json) =>
 | 
						|
      _$AuthInfoFromJson(json);
 | 
						|
}
 | 
						|
 | 
						|
/// Auth API
 | 
						|
extension AuthApi on ApiClient {
 | 
						|
  /// Get authentication information
 | 
						|
  Future<AuthInfo> authInfo() async {
 | 
						|
    final response = await execute("/auth/info", method: "GET");
 | 
						|
    return AuthInfo.fromJson(response.data);
 | 
						|
  }
 | 
						|
 | 
						|
  /// Get authentication information, returning cached information in case of failure
 | 
						|
  Future<AuthInfo> authInfoOrCache() async {
 | 
						|
    try {
 | 
						|
      final config = await authInfo();
 | 
						|
      this.prefs.setAuthInfo(config);
 | 
						|
      return config;
 | 
						|
    } catch (e, s) {
 | 
						|
      Logger.root.warning("Failed to fetch user information! $e $s");
 | 
						|
    }
 | 
						|
 | 
						|
    final cached = this.prefs.authInfo();
 | 
						|
    if (cached == null) {
 | 
						|
      throw Exception(
 | 
						|
        "Could not fetch user information, cached version is unavailable!",
 | 
						|
      );
 | 
						|
    }
 | 
						|
    return cached;
 | 
						|
  }
 | 
						|
 | 
						|
}
 |