import 'package:aitrainer_app/model/customer.dart'; import 'package:shared_preferences/shared_preferences.dart'; enum SharePrefsChange { login, registration, logout, } /* Auth flow of the app 1. During the login screen the authentication will be executed - if not successful: message: Network error, try again later - if successful - get the stored shared preferences and customer id - if customer_id not present -> registration page - if present, check if the expiration_date > 10 days -> login page - else get the API customer by the stored customer_id - After registration / login store the preferences: - AuthToken - customer_id - last_store_date - is_registered - is_logged_in */ class Auth { static final Auth _singleton = Auth._internal(); // Keys to store and fetch data from SharedPreferences static final String authTokenKey = 'auth_token'; static final String customerIdKey = 'customer_id'; static final String lastStoreDateKey = 'last_date'; static final String isRegisteredKey = 'is_registered'; static final String isLoggedInKey = 'is_logged_in'; static final String _baseUrl = 'http://andio.eu:8888/api/'; static final String username = 'bosi'; static final String password = 'andio2009'; String authToken = ""; Customer userLoggedIn; bool firstLoad = true; factory Auth() { return _singleton; } Auth._internal(); String getAuthToken() { return this.authToken; } static String getToken(SharedPreferences prefs) { return prefs.getString(authTokenKey); } static String getBaseUrl() { return _baseUrl; } afterRegistration(Customer customer) { Future prefs = SharedPreferences.getInstance(); userLoggedIn = customer; setPreferences(prefs, SharePrefsChange.registration, customer.customerId); } afterLogin(Customer customer) { Future prefs = SharedPreferences.getInstance(); userLoggedIn = customer; setPreferences(prefs, SharePrefsChange.login, customer.customerId); } logout(){ userLoggedIn = null; authToken = ""; //firstLoad = true; Future prefs = SharedPreferences.getInstance(); setPreferences(prefs, SharePrefsChange.logout, 0); } setPreferences(Future prefs, SharePrefsChange type, int customerId) async { SharedPreferences sharedPreferences; sharedPreferences = await prefs; DateTime now = DateTime.now(); sharedPreferences.setString(Auth.lastStoreDateKey, now.toString()); if ( type == SharePrefsChange.registration ) { sharedPreferences.setInt(Auth.customerIdKey, customerId); sharedPreferences.setBool(Auth.isRegisteredKey, true); sharedPreferences.setBool(Auth.isLoggedInKey, true); } else if ( type == SharePrefsChange.login ) { sharedPreferences.setInt(Auth.customerIdKey, customerId); sharedPreferences.setBool(Auth.isLoggedInKey, true); } else if ( type == SharePrefsChange.login ) { sharedPreferences.setBool(Auth.isLoggedInKey, false); sharedPreferences.setInt(Auth.customerIdKey, 0); } } }