From 6fd8c365f6ad68325a53b5dd24d0cb615ca99899 Mon Sep 17 00:00:00 2001 From: Reimar Date: Thu, 22 Aug 2024 09:17:36 +0200 Subject: [PATCH] Add authorization header --- Mobile/lib/api.dart | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/Mobile/lib/api.dart b/Mobile/lib/api.dart index 4a4276c..5f8ad2a 100644 --- a/Mobile/lib/api.dart +++ b/Mobile/lib/api.dart @@ -10,17 +10,22 @@ enum ApiService { Future request(BuildContext context, ApiService service, String method, String path, Object? body) async { final messenger = ScaffoldMessenger.of(context); + final prefs = await SharedPreferences.getInstance(); final host = switch (service) { ApiService.auth => const String.fromEnvironment('AUTH_SERVICE_HOST'), ApiService.app => const String.fromEnvironment('APP_SERVICE_HOST'), }; + final token = prefs.getString('token'); + final Map headers = {}; + if (token != null) headers.addAll({'Authorization': 'Bearer $token'}); + final http.Response response; try { if (method == 'GET') { - response = await http.get(Uri.parse(host + path)); + response = await http.get(Uri.parse(host + path), headers: headers); } else { final function = switch (method) { 'POST' => http.post, @@ -29,9 +34,11 @@ Future request(BuildContext context, ApiService service, String method, _ => throw const FormatException('Invalid method'), }; + headers.addAll({'Content-Type': 'application/json'}); + response = await function( Uri.parse(host + path), - headers: {'Content-Type': 'application/json'}, + headers: headers, body: body != null ? jsonEncode(body) : null, ); }