This commit is contained in:
Tibor Bossanyi 2023-03-01 17:47:36 +01:00
commit f34a57e931
3 changed files with 85 additions and 74 deletions

View File

@ -3,6 +3,9 @@ Workout Test and Diet 4 You Common Util Functions
Version 1.0.12 Version 1.0.12
CustomerProperty and CustomerMembership fromJson CustomerProperty and CustomerMembership fromJson
Version 1.0.11
No FCM on Web
Version 1.0.11 Version 1.0.11
Sentry and logging only in debugMode Sentry and logging only in debugMode

View File

@ -33,70 +33,67 @@ class FirebaseApi with logger.Logging {
// Define an async function to initialize FlutterFire // Define an async function to initialize FlutterFire
Future<void> initializeFlutterFire() async { Future<void> initializeFlutterFire() async {
try { try {
if (kIsWeb) {
if (kIsWeb) { await Firebase.initializeApp(
await Firebase.initializeApp( options: const FirebaseOptions(
options: const FirebaseOptions(
apiKey: "AIzaSyBLn7Bz73Z1hB-OhqphBDsskOyGmpI7J8E", apiKey: "AIzaSyBLn7Bz73Z1hB-OhqphBDsskOyGmpI7J8E",
authDomain: "diet4you-cb540.firebaseapp.com", authDomain: "diet4you-cb540.firebaseapp.com",
projectId: "diet4you-cb540", projectId: "diet4you-cb540",
storageBucket: "diet4you-cb540.appspot.com", storageBucket: "diet4you-cb540.appspot.com",
messagingSenderId: "534189506381", messagingSenderId: "534189506381",
appId: "1:534189506381:web:e885436c9be71ab4998104", appId: "1:534189506381:web:e885436c9be71ab4998104",
measurementId: "G-9YY4B98J99" measurementId: "G-9YY4B98J99"),
), );
);
} else {
await Firebase.initializeApp();
}
} on Exception catch(e) {
Track().trackError(e);
log("Error in Firebase init: $e");
}
appleSignInAvailable = await SignInWithApple.isAvailable();
if (kIsWeb) {
final fcmToken = await FirebaseMessaging.instance.getToken(vapidKey: "BKqkxyTqlGGI6m4gFLa-fFu9kYflyCbLkDKRKihWLqhDyR8oy1ymGzbk9lGcSDW1fd7XZiN2XYA2sDF8yjHdFPg");
FirebaseMessaging.instance.onTokenRefresh
.listen((fcmToken) {
// Note: This callback is fired at each app startup and whenever a new
// token is generated.
log('FCM token generated');
})
.onError((err) {
Track().trackError(err);
log("Error initializing Firebase Messaging for Web $err");
});
} else { } else {
try { await Firebase.initializeApp();
await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions( }
alert: true, // Required to display a heads up notification } on Exception catch (e) {
badge: true, Track().trackError(e);
sound: true, log("Error in Firebase init: $e");
); }
firebaseRegToken = await FirebaseMessaging.instance.getToken();
Cache().firebaseMessageToken = firebaseRegToken;
log("FirebaseMessaging token $firebaseRegToken");
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler); appleSignInAvailable = await SignInWithApple.isAvailable();
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
log('Got a message whilst in the foreground!');
log('Message data: ${message.data}');
if (message.notification != null) { if (kIsWeb) {
log('Message also contained a notification: ${message.notification}'); /* final fcmToken = await FirebaseMessaging.instance.getToken(
} vapidKey:
}); "BKqkxyTqlGGI6m4gFLa-fFu9kYflyCbLkDKRKihWLqhDyR8oy1ymGzbk9lGcSDW1fd7XZiN2XYA2sDF8yjHdFPg");
} catch (e) { FirebaseMessaging.instance.onTokenRefresh.listen((fcmToken) {
Track().trackError(e); // Note: This callback is fired at each app startup and whenever a new
log("Error initializing Firebase Messaging $e"); // token is generated.
} log('FCM token generated');
}).onError((err) {
Track().trackError(err);
log("Error initializing Firebase Messaging for Web $err");
}); */
} else {
try {
await FirebaseMessaging.instance
.setForegroundNotificationPresentationOptions(
alert: true, // Required to display a heads up notification
badge: true,
sound: true,
);
firebaseRegToken = await FirebaseMessaging.instance.getToken();
Cache().firebaseMessageToken = firebaseRegToken;
log("FirebaseMessaging token $firebaseRegToken");
FirebaseMessaging.onBackgroundMessage(
_firebaseMessagingBackgroundHandler);
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
log('Got a message whilst in the foreground!');
log('Message data: ${message.data}');
if (message.notification != null) {
log('Message also contained a notification: ${message.notification}');
}
});
} catch (e) {
Track().trackError(e);
log("Error initializing Firebase Messaging $e");
}
} }
} }
@ -109,7 +106,8 @@ class FirebaseApi with logger.Logging {
} }
String rc = SIGN_IN_OK; String rc = SIGN_IN_OK;
try { try {
userCredential = await FirebaseAuth.instance.signInWithEmailAndPassword(email: email, password: password); userCredential = await FirebaseAuth.instance
.signInWithEmailAndPassword(email: email, password: password);
Cache().firebaseUid = userCredential.user!.uid; Cache().firebaseUid = userCredential.user!.uid;
} on FirebaseAuthException catch (e) { } on FirebaseAuthException catch (e) {
Track().trackError(e); Track().trackError(e);
@ -129,7 +127,8 @@ class FirebaseApi with logger.Logging {
Future<String> registerEmail(String email, String password) async { Future<String> registerEmail(String email, String password) async {
String rc = SIGN_IN_OK; String rc = SIGN_IN_OK;
try { try {
userCredential = await FirebaseAuth.instance.createUserWithEmailAndPassword(email: email, password: password); userCredential = await FirebaseAuth.instance
.createUserWithEmailAndPassword(email: email, password: password);
Cache().firebaseUid = userCredential.user!.uid; Cache().firebaseUid = userCredential.user!.uid;
} on FirebaseAuthException catch (e) { } on FirebaseAuthException catch (e) {
Track().trackError(e); Track().trackError(e);
@ -151,9 +150,11 @@ class FirebaseApi with logger.Logging {
} }
String generateNonce([int length = 32]) { String generateNonce([int length = 32]) {
const charset = '0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._'; const charset =
'0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._';
final random = math.Random.secure(); final random = math.Random.secure();
return List.generate(length, (_) => charset[random.nextInt(charset.length)]).join(); return List.generate(length, (_) => charset[random.nextInt(charset.length)])
.join();
} }
/// Returns the sha256 hash of [input] in hex notation. /// Returns the sha256 hash of [input] in hex notation.
@ -165,7 +166,7 @@ class FirebaseApi with logger.Logging {
Future<Map<String, dynamic>> signInWithApple() async { Future<Map<String, dynamic>> signInWithApple() async {
Map<String, dynamic> userData = {}; Map<String, dynamic> userData = {};
// To prevent replay attacks with the credential returned from Apple, we // To prevent replay attacks with the credential returned from Apple, we
// include a nonce in the credential request. When signing in with // include a nonce in the credential request. When signing in with
// Firebase, the nonce in the id token returned by Apple, is expected to // Firebase, the nonce in the id token returned by Apple, is expected to
@ -191,8 +192,9 @@ class FirebaseApi with logger.Logging {
try { try {
// Sign in the user with Firebase. If the nonce we generated earlier does // Sign in the user with Firebase. If the nonce we generated earlier does
// not match the nonce in `appleCredential.identityToken`, sign in will fail. // not match the nonce in `appleCredential.identityToken`, sign in will fail.
userCredential = await FirebaseAuth.instance.signInWithCredential(oauthCredential); userCredential =
} on FirebaseAuthException catch(e) { await FirebaseAuth.instance.signInWithCredential(oauthCredential);
} on FirebaseAuthException catch (e) {
Track().trackError(e); Track().trackError(e);
throw Exception(e); throw Exception(e);
} }
@ -207,7 +209,7 @@ class FirebaseApi with logger.Logging {
Future<Map<String, dynamic>> registerWithApple() async { Future<Map<String, dynamic>> registerWithApple() async {
Map<String, dynamic> userData = {}; Map<String, dynamic> userData = {};
final rawNonce = generateNonce(); final rawNonce = generateNonce();
final nonce = sha256ofString(rawNonce); final nonce = sha256ofString(rawNonce);
@ -229,8 +231,9 @@ class FirebaseApi with logger.Logging {
try { try {
// Sign in the user with Firebase. If the nonce we generated earlier does // Sign in the user with Firebase. If the nonce we generated earlier does
// not match the nonce in `appleCredential.identityToken`, sign in will fail. // not match the nonce in `appleCredential.identityToken`, sign in will fail.
userCredential = await FirebaseAuth.instance.signInWithCredential(oauthCredential); userCredential =
} on FirebaseAuthException catch(e) { await FirebaseAuth.instance.signInWithCredential(oauthCredential);
} on FirebaseAuthException catch (e) {
Track().trackError(e); Track().trackError(e);
throw Exception(e); throw Exception(e);
} }
@ -260,7 +263,8 @@ class FirebaseApi with logger.Logging {
} }
// Obtain the auth details from the request // Obtain the auth details from the request
final GoogleSignInAuthentication googleAuth = await googleUser.authentication; final GoogleSignInAuthentication googleAuth =
await googleUser.authentication;
// Create a new credential // Create a new credential
final OAuthCredential credential = GoogleAuthProvider.credential( final OAuthCredential credential = GoogleAuthProvider.credential(
@ -268,7 +272,8 @@ class FirebaseApi with logger.Logging {
idToken: googleAuth.idToken, idToken: googleAuth.idToken,
); );
UserCredential userCredential = await FirebaseAuth.instance.signInWithCredential(credential); UserCredential userCredential =
await FirebaseAuth.instance.signInWithCredential(credential);
Cache().firebaseUid = userCredential.user!.uid; Cache().firebaseUid = userCredential.user!.uid;
log("GoogleUser: $googleUser"); log("GoogleUser: $googleUser");
@ -298,7 +303,8 @@ class FirebaseApi with logger.Logging {
} }
// Obtain the auth details from the request // Obtain the auth details from the request
final GoogleSignInAuthentication googleAuth = await googleUser.authentication; final GoogleSignInAuthentication googleAuth =
await googleUser.authentication;
// Create a new credential // Create a new credential
final OAuthCredential credential = GoogleAuthProvider.credential( final OAuthCredential credential = GoogleAuthProvider.credential(
@ -306,7 +312,8 @@ class FirebaseApi with logger.Logging {
idToken: googleAuth.idToken, idToken: googleAuth.idToken,
); );
final userCredential = await FirebaseAuth.instance.signInWithCredential(credential); final userCredential =
await FirebaseAuth.instance.signInWithCredential(credential);
log("Google credentials: $credential GoogleUser: $googleUser"); log("Google credentials: $credential GoogleUser: $googleUser");
Cache().firebaseUid = userCredential.user!.uid; Cache().firebaseUid = userCredential.user!.uid;
@ -350,10 +357,12 @@ class FirebaseApi with logger.Logging {
log("FB user data: $userData"); log("FB user data: $userData");
// Create a credential from the access token // Create a credential from the access token
final OAuthCredential facebookAuthCredential = FacebookAuthProvider.credential(accessToken.token); final OAuthCredential facebookAuthCredential =
FacebookAuthProvider.credential(accessToken.token);
// Once signed in, return the UserCredential // Once signed in, return the UserCredential
final userCredential = await FirebaseAuth.instance.signInWithCredential(facebookAuthCredential); final userCredential = await FirebaseAuth.instance
.signInWithCredential(facebookAuthCredential);
log("Email by FB: ${userData['email']} FB credential: $userCredential"); log("Email by FB: ${userData['email']} FB credential: $userCredential");
Cache().firebaseUid = userCredential.user!.uid; Cache().firebaseUid = userCredential.user!.uid;

View File

@ -1,10 +1,9 @@
name: workouttest_util name: workouttest_util
description: Workout Test app and web functions. description: Workout Test app and web functions.
version: 1.0.12 version: 1.0.12
homepage:
environment: environment:
sdk: '>=2.18.6 <3.0.0' sdk: ">=2.18.6 <3.0.0"
flutter: ">=1.17.0" flutter: ">=1.17.0"
dependencies: dependencies:
@ -35,7 +34,7 @@ dependencies:
shared_preferences: ^2.0.17 shared_preferences: ^2.0.17
posthog_session: posthog_session:
git: git:
url: https://bossanyit@git.workouttest.org/bossanyit/posthog_session.git url: https://bossanyit@git.workouttest.org/bossanyit/posthog_session.git
ref: 6a620a202a47402cbc57a5896a32cff73ce2e24f ref: 6a620a202a47402cbc57a5896a32cff73ce2e24f