I am currently in the middle of creating my authentication process for sign-up in Flutter. I have correctly signed the user up with their email and password, the user is then prompted to enter some details such as fullName and mobileNumber. Once they have entered these details they are taken to a confirm mobile page whereby they click a button to send the code. This prompts the auth_service to send the code but it never executes and returns an error.
signup.dart
import 'package:aqua_audit/decorations/input_decoration.dart';
import 'package:aqua_audit/screens/onboarding/create_account.dart';
import 'package:aqua_audit/screens/onboarding/splash_selection.dart';
import 'package:aqua_audit/services/auth_service.dart'; // Import the AuthService
import 'package:aqua_audit/services/splash_service.dart';
import 'package:aqua_audit/styles/button_style.dart';
import 'package:aqua_audit/widgets/components/custom_card.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:page_transition/page_transition.dart';
import '../../../widgets/structure/base_layout.dart';
import 'package:aqua_audit/widgets/components/splash/splash_logo.dart';
class SignUp extends StatefulWidget {
final String company;
final String accessLevel;
const SignUp({
required this.company,
required this.accessLevel,
super.key
});
@override
_SignUpState createState() => _SignUpState();
}
class _SignUpState extends State<SignUp> {
bool _isLoading = true;
String _imageURL = '';
TextEditingController _emailController = TextEditingController();
TextEditingController _passwordController = TextEditingController();
TextEditingController _confirmPasswordController = TextEditingController();
bool _obscurePassword = true;
bool _obscureConfirmPassword = true;
@override
void initState() {
super.initState();
_fetchImage();
}
Future<void> _fetchImage() async {
SplashService splashService = SplashService();
String imageURL = await splashService.fetchSplashImage();
setState(() {
_imageURL = imageURL;
_isLoading = false;
});
}
void _goBack() {
Navigator.of(context).pushReplacement(
PageTransition(
type: PageTransitionType.fade,
child: const SplashSelection(),
duration: const Duration(milliseconds: 300),
),
);
}
void _togglePasswordVisibility() {
setState(() {
_obscurePassword = !_obscurePassword;
});
}
void _toggleConfirmPasswordVisibility() {
setState(() {
_obscureConfirmPassword = !_obscureConfirmPassword;
});
}
Future<void> _signUp() async {
String email = _emailController.text.trim();
String password = _passwordController.text.trim();
String confirmPassword = _confirmPasswordController.text.trim();
if (password != confirmPassword) {
// Show error if passwords do not match
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text("Passwords do not match")),
);
return;
}
setState(() {
_isLoading = true;
});
AuthService authService = AuthService();
User? user = await authService.signUp(email, password, widget.company, widget.accessLevel);
setState(() {
_isLoading = false;
});
if (user != null) {
Navigator.of(context).pushReplacement(
PageTransition(
type: PageTransitionType.fade,
child: CreateAccount(user: user),
duration: const Duration(milliseconds: 300),
),
);
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text("Sign Up Failed")),
);
}
}
@override
Widget build(BuildContext context) {
ThemeData theme = Theme.of(context);
double screenHeight = MediaQuery.of(context).size.height;
double screenWidth = MediaQuery.of(context).size.width;
return BaseLayout(
bodyContent: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
CustomCard(
cardContent: _isLoading
? Center(child: CircularProgressIndicator())
: Stack(
children: [
Container(
height: screenHeight - 60,
child: SplashLogo(imageURL: _isLoading ? "" : _imageURL),
),
Positioned(
top: 16,
left: 16,
child: IconButton(
icon: Icon(Icons.arrow_back, color: theme.primaryColor),
onPressed: _goBack,
),
),
Positioned(
bottom: ((screenHeight - 60) / 10) * 3.5, // Adjust as needed
left: 16,
right: 16,
child: TextFormField(
decoration: customInputDecoration(
context,
"Email",
prefixIcon: Icon(Icons.email, color: theme.colorScheme.primary),
hintText: "Enter your email address",
),
controller: _emailController,
),
),
Positioned(
bottom: ((screenHeight - 60) / 10) * 2.5, // Adjust as needed
left: 16,
right: 16,
child: TextFormField(
obscureText: _obscurePassword,
decoration: customInputDecoration(
context,
"Password",
prefixIcon: Icon(Icons.lock, color: theme.colorScheme.primary),
hintText: "Enter your password",
suffixIcon: IconButton(
icon: Icon(
_obscurePassword ? Icons.visibility : Icons.visibility_off,
color: theme.colorScheme.onSurface,
),
onPressed: _togglePasswordVisibility,
),
),
controller: _passwordController,
),
),
Positioned(
bottom: ((screenHeight - 60) / 10) * 1.5, // Adjust as needed
left: 16,
right: 16,
child: TextFormField(
obscureText: _obscureConfirmPassword,
decoration: customInputDecoration(
context,
"Confirm Password",
prefixIcon: Icon(Icons.lock, color: theme.colorScheme.primary),
hintText: "Confirm your password",
suffixIcon: IconButton(
icon: Icon(
_obscureConfirmPassword ? Icons.visibility : Icons.visibility_off,
color: theme.colorScheme.onSurface,
),
onPressed: _toggleConfirmPasswordVisibility,
),
),
controller: _confirmPasswordController,
),
),
Positioned(
bottom: ((screenHeight - 60) / 10) * .375,
left: 16,
right: 16,
child: ElevatedButton(
style: customButtonStyle(((screenHeight - 60) / 10) * .75, theme),
onPressed: _signUp,
child: const Text("Sign Up"),
),
),
],
),
padding: 0,
height: screenHeight - 60,
width: screenWidth,
)
]
)
);
}
}
confirm_mobile.dart
import 'package:aqua_audit/screens/onboarding/splash_selection.dart';
import 'package:aqua_audit/services/auth_service.dart';
import 'package:aqua_audit/services/splash_service.dart';
import 'package:aqua_audit/styles/button_style.dart';
import 'package:aqua_audit/widgets/components/custom_card.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:page_transition/page_transition.dart';
import '../../../widgets/structure/base_layout.dart';
import 'package:aqua_audit/widgets/components/splash/splash_logo.dart';
import 'verify_mobile.dart';
class ConfirmMobile extends StatefulWidget {
final User? user;
final String mobileNumber;
const ConfirmMobile({
required this.user,
required this.mobileNumber,
super.key
});
@override
_ConfirmMobileState createState() => _ConfirmMobileState();
}
class _ConfirmMobileState extends State<ConfirmMobile> {
bool _isLoading = true;
String _imageURL = '';
@override
void initState() {
super.initState();
_fetchImage();
}
Future<void> _fetchImage() async {
SplashService splashService = SplashService();
String imageURL = await splashService.fetchSplashImage();
setState(() {
_imageURL = imageURL;
_isLoading = false;
});
}
void _goBack() {
Navigator.of(context).pushReplacement(
PageTransition(
type: PageTransitionType.fade,
child: const SplashSelection(),
duration: const Duration(milliseconds: 300),
),
);
}
Future<void> _sendVerificationCode() async {
AuthService authService = AuthService();
await authService.sendVerificationCode(widget.mobileNumber);
Navigator.of(context).pushReplacement(
PageTransition(
type: PageTransitionType.fade,
child: VerifyMobile(user: widget.user, mobileNumber: widget.mobileNumber),
duration: const Duration(milliseconds: 300),
),
);
}
@override
Widget build(BuildContext context) {
ThemeData theme = Theme.of(context);
double screenHeight = MediaQuery.of(context).size.height;
double screenWidth = MediaQuery.of(context).size.width;
return BaseLayout(
bodyContent: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
CustomCard(
cardContent: _isLoading
? Center(child: CircularProgressIndicator())
: Stack(
children: [
Container(
height: screenHeight - 60,
child: SplashLogo(imageURL: _isLoading ? "" : _imageURL),
),
Positioned(
top: 16,
left: 16,
child: IconButton(
icon: Icon(Icons.arrow_back, color: theme.primaryColor),
onPressed: _goBack,
),
),
Positioned(
bottom: ((screenHeight - 60) / 10) * .375,
left: 16,
right: 16,
child: ElevatedButton(
style: customButtonStyle(((screenHeight - 60) / 10) * .75, theme),
onPressed: _sendVerificationCode,
child: const Text("Send Code"),
),
),
],
),
padding: 0,
height: screenHeight - 60,
width: screenWidth,
)
]
)
);
}
}
verify_mobile.dart
import 'package:aqua_audit/decorations/input_decoration.dart';
import 'package:aqua_audit/screens/onboarding/confirm_mobile.dart';
import 'package:aqua_audit/services/auth_service.dart';
import 'package:aqua_audit/services/splash_service.dart';
import 'package:aqua_audit/styles/button_style.dart';
import 'package:aqua_audit/widgets/components/custom_card.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:page_transition/page_transition.dart';
import '../../../widgets/structure/base_layout.dart';
import 'package:aqua_audit/widgets/components/splash/splash_logo.dart';
class VerifyMobile extends StatefulWidget {
final User? user;
final String mobileNumber;
const VerifyMobile({
required this.user,
required this.mobileNumber,
super.key
});
@override
_VerifyMobileState createState() => _VerifyMobileState();
}
class _VerifyMobileState extends State<VerifyMobile> {
bool _isLoading = true;
String _imageURL = '';
TextEditingController _verifyCodeController = TextEditingController();
@override
void initState() {
super.initState();
_fetchImage();
}
Future<void> _fetchImage() async {
SplashService splashService = SplashService();
String imageURL = await splashService.fetchSplashImage();
setState(() {
_imageURL = imageURL;
_isLoading = false;
});
}
void _goBack() {
Navigator.of(context).pushReplacement(
PageTransition(
type: PageTransitionType.fade,
child: ConfirmMobile(user: widget.user, mobileNumber: widget.mobileNumber),
duration: const Duration(milliseconds: 300),
),
);
}
Future<void> _verifyVerificationCode() async {
String verificationCode = _verifyCodeController.text.trim();
AuthService authService = AuthService();
bool isVerified = await authService.verifyVerificationCode(verificationCode);
if (isVerified) {
// Navigate to the next page or home page
} else {
// Show error message
}
}
@override
Widget build(BuildContext context) {
ThemeData theme = Theme.of(context);
double screenHeight = MediaQuery.of(context).size.height;
double screenWidth = MediaQuery.of(context).size.width;
return BaseLayout(
bodyContent: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
CustomCard(
cardContent: _isLoading
? Center(child: CircularProgressIndicator())
: Stack(
children: [
Container(
height: screenHeight - 60,
child: SplashLogo(imageURL: _isLoading ? "" : _imageURL),
),
Positioned(
top: 16,
left: 16,
child: IconButton(
icon: Icon(Icons.arrow_back, color: theme.primaryColor),
onPressed: _goBack,
),
),
Positioned(
bottom: ((screenHeight - 60) / 10) * 1.5, // Adjust as needed
left: 16,
right: 16,
child: TextFormField(
decoration: customInputDecoration(
context,
"Enter Code",
prefixIcon: Icon(Icons.lock, color: theme.colorScheme.primary),
hintText: "Enter your verification code",
),
controller: _verifyCodeController,
),
),
Positioned(
bottom: ((screenHeight - 60) / 10) * .375,
left: 16,
right: 16,
child: ElevatedButton(
style: customButtonStyle(((screenHeight - 60) / 10) * .75, theme),
onPressed: _verifyVerificationCode,
child: const Text("Verify Code"),
),
),
],
),
padding: 0,
height: screenHeight - 60,
width: screenWidth,
)
]
)
);
}
}
auth_service.dart
import 'dart:io';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_storage/firebase_storage.dart';
class AuthService {
final FirebaseAuth _auth = FirebaseAuth.instance;
final FirebaseFirestore _firestore = FirebaseFirestore.instance;
final FirebaseStorage _storage = FirebaseStorage.instance;
Future<User?> signUp(String email, String password, String accessLevel, String company) async {
try {
// Create a new user with email and password
UserCredential userCredential = await _auth.createUserWithEmailAndPassword(
email: email,
password: password,
);
User? user = userCredential.user;
if (user != null) {
// Create a user document in Firestore
await _firestore.collection('users').doc(user.uid).set({
'email': user.email,
'accessLevel': accessLevel,
'company': company,
// Add other fields if needed
});
}
return user;
} catch (e) {
print("Sign Up Error: $e");
// Handle errors appropriately
return null;
}
}
Future<User?> createAccount(User? user, String imageURL, String fullName, String? mobileNumber) async {
try {
if (user != null) {
// Upload profile picture
String downloadURL = '';
if (imageURL.isNotEmpty) {
Reference ref = _storage.ref().child('profile_pictures').child(user.uid);
UploadTask uploadTask = ref.putFile(File(imageURL));
TaskSnapshot taskSnapshot = await uploadTask;
downloadURL = await taskSnapshot.ref.getDownloadURL();
}
// Create a user document in Firestore
await _firestore.collection('users').doc(user.uid).update({
'fullName': fullName,
'mobileNumber': mobileNumber,
'imageUrl': downloadURL,
// Add other fields if needed
});
}
return user;
} catch (e) {
print("Sign Up Error: $e");
// Handle errors appropriately
return null;
}
}
Future<Map<String, dynamic>?> verifyAccessCode({
required String accessCode,
}) async {
try {
QuerySnapshot querySnapshot = await FirebaseFirestore.instance
.collection('access_codes')
.where('code', isEqualTo: accessCode)
.get();
if (querySnapshot.docs.isNotEmpty) {
DocumentSnapshot documentSnapshot = querySnapshot.docs.first;
Map<String, dynamic> data = documentSnapshot.data() as Map<String, dynamic>;
await documentSnapshot.reference.delete();
return data;
}
} catch (e) {
print("Access Verification Error: $e");
return null;
}
return null;
}
Future<void> sendVerificationCode(String mobileNumber) async {
try {
await _auth.verifyPhoneNumber(
phoneNumber: mobileNumber,
verificationCompleted: (PhoneAuthCredential credential) async {
await _auth.signInWithCredential(credential);
},
verificationFailed: (FirebaseAuthException e) {
print("Verification Failed: ${e.message}");
},
codeSent: (String verificationId, int? resendToken) async {
// Store the verificationId in a secure place
},
codeAutoRetrievalTimeout: (String verificationId) {
// Auto-retrieval timeout
},
);
} catch (e) {
print("Send Verification Code Error: $e");
}
}
Future<bool> verifyVerificationCode(String verificationCode) async {
try {
// Retrieve the verificationId from a secure place
String verificationId = ''; // You need to store and retrieve this
PhoneAuthCredential credential = PhoneAuthProvider.credential(
verificationId: verificationId,
smsCode: verificationCode,
);
UserCredential userCredential = await _auth.signInWithCredential(credential);
return userCredential.user != null;
} catch (e) {
print("Verify Code Error: $e");
return false;
}
}
}
When i click the send code button on the confirm_mobile page it provides the below error.
I/zza (24972): ForceRecaptchaFlow from phoneAuthOptions = false, ForceRecaptchaFlow from firebaseSettings = false
W/System (24972): Ignoring header X-Firebase-Locale because its value was null.
W/StorageUtil(24972): Error getting App Check token; using placeholder token instead. Error: com.google.firebase.FirebaseException: No AppCheckProvider installed.
D/EGL_emulation(24972): app_time_stats: avg=704.87ms min=3.11ms max=9081.78ms count=13
W/LocalRequestInterceptor(24972): Error getting App Check token; using placeholder token instead. Error: com.google.firebase.FirebaseException: No AppCheckProvider installed.
I/aquaaudit.co.uk(24972): Background concurrent mark compact GC freed 93694(4366KB) AllocSpace objects, 12(496KB) LOS objects, 49% free, 5143KB/10MB, paused 988us,6.899ms total 53.710ms
E/StorageException(24972): StorageException has occurred.
E/StorageException(24972): User is not authenticated, please authenticate using Firebase Authentication and try again.
E/StorageException(24972): Code: -13020 HttpResult: 401
E/StorageException(24972): { “error”: { “code”: 401, “message”: “Firebase App Check token is invalid.” }}
E/StorageException(24972): java.io.IOException: { “error”: { “code”: 401, “message”: “Firebase App Check token is invalid.” }}
E/StorageException(24972): at com.google.firebase.storage.network.NetworkRequest.parseResponse(NetworkRequest.java:415)
E/StorageException(24972): at com.google.firebase.storage.network.NetworkRequest.parseErrorResponse(NetworkRequest.java:432)
E/StorageException(24972): at com.google.firebase.storage.network.NetworkRequest.processResponseStream(NetworkRequest.java:423)
E/StorageException(24972): at com.google.firebase.storage.network.NetworkRequest.performRequest(NetworkRequest.java:265)
E/StorageException(24972): at com.google.firebase.storage.network.NetworkRequest.performRequest(NetworkRequest.java:282)
E/StorageException(24972): at com.google.firebase.storage.internal.ExponentialBackoffSender.sendWithExponentialBackoff(ExponentialBackoffSender.java:76)
E/StorageException(24972): at com.google.firebase.storage.internal.ExponentialBackoffSender.sendWithExponentialBackoff(ExponentialBackoffSender.java:68)
E/StorageException(24972): at com.google.firebase.storage.GetDownloadUrlTask.run(GetDownloadUrlTask.java:77)
E/StorageException(24972): at com.google.firebase.concurrent.LimitedConcurrencyExecutor.lambda$decorate$0$com-google-firebase-concurrent-LimitedConcurrencyExecutor(LimitedConcurrencyExecutor.java:65)
E/StorageException(24972): at com.google.firebase.concurrent.LimitedConcurrencyExecutor$$ExternalSyntheticLambda0.run(Unknown Source:4)
E/StorageException(24972): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
E/StorageException(24972): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:644)
E/StorageException(24972): at com.google.firebase.concurrent.CustomThreadFactory.lambda$newThread$0$com-google-firebase-concurrent-CustomThreadFactory(CustomThreadFactory.java:47)
E/StorageException(24972): at com.google.firebase.concurrent.CustomThreadFactory$$ExternalSyntheticLambda0.run(Unknown Source:4)
E/StorageException(24972): at java.lang.Thread.run(Thread.java:1012)
I/flutter (24972): Error fetching splash image: [firebase_storage/unauthenticated] User is unauthenticated. Authenticate and try again.
Another exception was thrown: Unable to load asset: “assets/logo.png”.
I/PlayCore(24972): UID: [10215] PID: [24972] IntegrityService : requestIntegrityToken(IntegrityTokenRequest{nonce=cTuW6VpETzhdp52GbGfuYF1_vnilEcAhkqZ8dZtF6SA, cloudProjectNumber=551503664846, network=null})
I/PlayCore(24972): UID: [10215] PID: [24972] IntegrityService : Initiate binding to the service.
I/PlayCore(24972): UID: [10215] PID: [24972] IntegrityService : ServiceConnectionImpl.onServiceConnected(ComponentInfo{com.android.vending/com.google.android.finsky.integrityservice.IntegrityService})
I/PlayCore(24972): UID: [10215] PID: [24972] IntegrityService : linkToDeath
I/PlayCore(24972): UID: [10215] PID: [24972] OnRequestIntegrityTokenCallback : onRequestIntegrityToken
I/PlayCore(24972): UID: [10215] PID: [24972] IntegrityService : Unbind from service.
W/System (24972): Ignoring header X-Firebase-Locale because its value was null.
W/LocalRequestInterceptor(24972): Error getting App Check token; using placeholder token instead. Error: com.google.firebase.FirebaseException: No AppCheckProvider installed.
E/FirebaseAuth(24972): [SmsRetrieverHelper] SMS verification code request failed: unknown status code: 17028 Invalid app info in play_integrity_token
D/FirebaseAuth(24972): Invoking original failure callbacks after phone verification failure for +44 7725828485, error – This app is not authorized to use Firebase Authentication. Please verify that the correct package name, SHA-1, and SHA-256 are configured in the Firebase Console. [ Invalid app info in play_integrity_token ]
D/CompatibilityChangeReporter(24972): Compat change id reported: 247079863; UID 10215; state: ENABLED
I/flutter (24972): Verification Failed: This app is not authorized to use Firebase Authentication. Please verify that the correct package name, SHA-1, and SHA-256 are configured in the Firebase Console. [ Invalid app info in play_integrity_token ]
I have verified my SHA-1 and SHA-256 and believe that I have setup everything else as required based on available documentation, but the integration does not seem to have worked. Please help me find a solution. I’m also aware that my implementation does not currently use MFA, if any provided solution could implement MFA that would be great.