skantravels/Mobile/lib/api.dart

92 lines
2.5 KiB
Dart
Raw Normal View History

2024-08-21 09:03:03 +01:00
import 'package:flutter/material.dart';
2024-08-21 11:49:38 +01:00
import 'package:shared_preferences/shared_preferences.dart';
2024-08-21 09:03:03 +01:00
import 'package:http/http.dart' as http;
import 'dart:convert';
2024-08-22 07:51:13 +01:00
import 'dart:developer';
2024-08-21 09:03:03 +01:00
enum ApiService {
auth,
app,
}
2024-08-22 07:51:13 +01:00
Future<String?> request(BuildContext context, ApiService service, String method,
String path, Object? body) async {
log('hello');
2024-08-21 09:03:03 +01:00
final messenger = ScaffoldMessenger.of(context);
final host = switch (service) {
ApiService.auth => const String.fromEnvironment('AUTH_SERVICE_HOST'),
ApiService.app => const String.fromEnvironment('APP_SERVICE_HOST'),
};
2024-08-22 07:51:13 +01:00
log('hello');
log(const String.fromEnvironment('AUTH_SERVICE_HOST'));
2024-08-21 09:03:03 +01:00
final http.Response response;
try {
if (method == 'GET') {
response = await http.get(Uri.parse(host + path));
} else {
final function = switch (method) {
'POST' => http.post,
'PUT' => http.put,
'DELETE' => http.delete,
_ => throw const FormatException('Invalid method'),
};
response = await function(
Uri.parse(host + path),
headers: {'Content-Type': 'application/json'},
body: body != null ? jsonEncode(body) : null,
);
}
} catch (_) {
2024-08-22 07:51:13 +01:00
messenger.showSnackBar(
const SnackBar(content: Text('Unable to connect to server')));
2024-08-21 09:03:03 +01:00
return null;
}
if (response.statusCode < 200 || response.statusCode >= 300) {
try {
final json = jsonDecode(response.body);
messenger.showSnackBar(SnackBar(content: Text(json['message'])));
} catch (_) {
2024-08-22 07:51:13 +01:00
messenger.showSnackBar(SnackBar(
content: Text('Something went wrong (HTTP ${response.statusCode})')));
2024-08-21 09:03:03 +01:00
}
return null;
}
return response.body;
2024-08-21 11:49:38 +01:00
}
Future<bool> isLoggedIn(BuildContext context) async {
final messenger = ScaffoldMessenger.of(context);
final prefs = await SharedPreferences.getInstance();
final token = prefs.getString('token');
if (token == null) return false;
try {
String base64 = token.split('.')[1];
base64 += List.filled(4 - base64.length % 4, '=').join();
final payload = jsonDecode(String.fromCharCodes(base64Decode(base64)));
if (payload['exp'] < DateTime.now().millisecondsSinceEpoch / 1000) {
2024-08-22 07:51:13 +01:00
messenger.showSnackBar(
const SnackBar(content: Text('Token expired, please sign in again')));
2024-08-21 11:49:38 +01:00
prefs.remove('token');
return false;
}
} catch (e) {
2024-08-22 07:51:13 +01:00
messenger.showSnackBar(
const SnackBar(content: Text('Invalid token, please sign in again')));
2024-08-21 11:49:38 +01:00
prefs.remove('token');
return false;
}
return true;
}