I was building an email verification page on my flutter app for users to verify their emails before they can sign in. So in the verification page, I have a button that allows the users to resend the verfication email after 5 seconds from the time they sent.
Future sendVerificationEmail() async {
try{
final user = FirebaseAuth.instance.currentUser!;
await user.sendEmailVerification();
setState(() => canResendEmail = false);
await Future.delayed(const Duration(seconds: 5));
canResendEmail = true;
}catch (e) {
Utils.showSnackBar(e.toString());
}
}
...............................
ElevatedButton.icon(
icon: const Icon(Icons.email, size: 32),
label: const Text("Resend email"
),
onPressed: canResendEmail ? sendVerificationEmail : null,
),
But then the problem is when I try to resend the email again, most of the time i get the error which says:
[firebase-auth/too many requests] We have blocked all requests from this device due to unusual activity. Try again later.
Well, I understand that this is great for security but its just not consistent at all. Like sometimes I can resend 5 emails within 30 seconds and sometimes it will keep showing this error for more than 2 minuetes.
My question is whether i can set some rules in the firebase to make that I can like send certain number of email requests per seconds or like at least get to know what is the exact time that I need to wait before I can send a request again instead of this random situation where sometimes I can send multiple requests within short time.
Related
I want to display a snackbar that says "your internet connection is slow" when an api request takes more than 4 seconds even while the request is still running in the background, just to notify the user that his connection is too slow. I've tried wrapping the request with a stopwatch but that only works after the connection gets a response, which is too late. As the Future request is running, i'd like to know how many seconds its taking so i can run the snackbar display to view. I'd appreciate any help please.
Hie there Moyosola.
1. If you want it to just check the 4 second period
To achieve this you can use a timer then cancel it once the time has passed, and notify the user. Check the code below. Call the method startTimer() when you start calling you api.
Timer _timer; // set as global variable
int _timeElapsed = 0;
void startTimer() {
const period = const Duration(seconds: 4);
_timer = new Timer.periodic(
period,
(Timer timer) {
if (_timeElapsed == 5) {
_timer.cancel();
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text('Your Internet Connection Is Slow')));
} else {
setState(() {
_timeElapsed++;
});
}
},
);
}
2. If you want it to timeout
To achieve that you need to wrap your code or whatever you want to run in a try-catch block on throw an onTimeoutException error after your set time has expired. See the code below:
try {
//put whatever you are running here and add timeout to http request
await http.get(url).timeout(Duration(seconds: 4));
} on TimeoutException catch (e, s) {
//show any error after timeout here
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text('Your Internet Connection Is Slow')));
}
}
I debug and answer people's questions also on my youtube channel, Mufungo Geeks Programming, which might help you in other related queries. Good Day!
I am trying to implement a password reset function that incorporates a SnackBar to display either success or error messages. The code shown below produces both the success message and the various error messages, as appropriate - but I never receive the password reset email from the Firebase service. I'm not sure if it's a Firebase setup issue or an issue with the code.
Future resetPassword() async {
try {
await FirebaseAuth.instance
.sendPasswordResetEmail(email: _emailController.text.trim());
_showSnackBar('Password reset link sent');
} on FirebaseAuthException catch (e) {
_showSnackBar(e.message.toString());
return;
}
}
Future<void> _showSnackBar(String msg) async {
final snackBar = SnackBar(
content: Text(msg),
);
ScaffoldMessenger.of(context).showSnackBar(snackBar);
}
Disregard. Code seems to work fine - problem was either with Firebase Auth service or my internet service provider last night. All good now.
Make sure to check your spam, because if did not add authorize rules in firebase then the reset link goes in spam mail.
.
This question already has answers here:
How to implement phone number verification in flutter using firebase? (Not Authentication)
(3 answers)
Closed 11 months ago.
is there a way to verify phone number without authenticate using firebase??
i tried this on init state of sms screen verification
_verifyPhone() async{
await _auth.verifyPhoneNumber(
phoneNumber: widget.phoneNumber,
verificationCompleted: (PhoneAuthCredential credential) async {
print("yes yes");
},
verificationFailed: (FirebaseAuthException e) {
print(e.message);
},
codeSent: (String verficationID, int resendToken) {
setState(() {
_verificationCode = verficationID;
});
},
codeAutoRetrievalTimeout: (String verificationID) {
setState(() {
_verificationCode = verificationID;
});
},
timeout: Duration(seconds: 120)
);
}
ElevatedButton(
child: Text('Verify', style: TextStyle(color: Colors.white, fontSize: 20),),
onPressed: () async{
print("pressed");
if(_verificationCode == textController.text)
print("yes"); // plus navigate to home screen
else
print("no"); // resend or something im trying
}
),
i tried the above code but no sms sent to me.
is that because i didnt turn on the phone number authenticate option in firebase?
but i dont want to authenticate using phone Number
is there a way to use firebase verify phone number without authenticate using the number?
No, this is not possible. Firebase's phone number verification is part of the authentication flow, and not a feature outside of that.
i tried the above code but no sms sent to me. is that because i didnt turn on the phone number authenticate option in firebase?
Phone number verification will indeed not work when phone number authentication is turned off on the project.
Also see:
Firebase user phone number verification
How to implement phone number verification in flutter using firebase? (Not Authentication)
How to add or update phone_number in Firebase Auth
For a flutter app I’m using Firebase Cloud Messaging and cloud functions to send push notifications to users, using their FCM registration tokens. The app has a settings page where users should be able to turn off certain push notifications. The notifications are user specific, so a topic to subscribe or unsubscribe to wouldn’t work, but the notifications can be classified in certain categories.
For example in a chat app when user A send a message to user B that push notification could be in a category of ‘chat messages’, while user A could also delete the chat with user B and that push notification could be in a category of ‘deleted chats’.
How can I make it so that user B can turn off notifications for ‘deleted chats’, while still receiving notifications for ‘chat messages’? Is it possible to use a condition with a topic and a user’s registration token on one way or the other? Any ideas are greatly appreciated!
Thanks to a big nudge in the right direction from Doug, I was able to figure it out! Posting my code below to help anyone take the same step in the right direction.
So, in my flutter app' settings page the user can turn notifications on and off for a few categories. The user's preference is then stored in a user specific document in my Cloud Firestore users collection. See the below code for an example of the SwitchListTile I used on the settings page.
SwitchListTile(
title: Text('Admin notifications'),
subtitle: Text('Maintenance and general notes'),
onChanged: (value) {
setState(() {
adminNotifications = value;
Firestore.instance
.collection('users')
.document(loggedInUser.uid)
.updateData({
'adminNotifications': value,
});
});
save('adminNotifications', value);
},
value: adminNotifications,
),
In my cloud function I added a reference to the document in the users collection and a check to see if the value of the field adminNotifications is equal to true. If so, a notification is send, otherwise a notification is not send to the user. Below I've added the cloud function. Please do note that the cloud function renders 'nested promises' warnings, but it works for now! I'm still a Flutter beginner so I was pretty happy to get it working. Big thanks again to Doug!
exports.userNotifications = functions.firestore.document('notifications/{any}').onCreate((change, context) => {
const userFcm = change.data().fcmToken;
const title = change.data().title;
const body = change.data().body;
const forUser = change.data().for;
const notificationContent = {
notification: {
title: title,
body: body,
badge: '1',
click_action: 'FLUTTER_NOTIFICATION_CLICK',
}
};
var usersRef = db.collection('users');
var queryRef = usersRef.where('login', '==', forUser).limit(1).get()
.then(snapshot => {
snapshot.forEach(doc => {
const adminNotifications = doc.data().adminNotifications;
console.log(adminNotifications);
if(swapNotifications === true){
return admin.messaging().sendToDevice(userFcm, notificationContent)
.then(() => {
console.log('notification sent')
return
})
.catch(error =>{
console.log('error in sending notification', error)
})
} else {
console.log('message not send due to swapNotification preferences')
}
return console.log('reading user data success');
})
.catch(err => {
console.log('error in retrieving user data:', err)
})
});
i want little ask about sending email with flutter . I using https://pub.dev/packages/flutter_email_sender#-readme-tab- for sending email.
Sending Function
Future sendEmail(String subject,String body,List<String> recipients) async{
final Email email = Email(body: body,subject: subject,recipients: recipients);
String platformResponse;
try {
await FlutterEmailSender.send(email);
platformResponse='success';
} catch (e) {
platformResponse = e.toString();
}
print(platformResponse);
}
View.dart
Center(
child: RaisedButton(
onPressed: () => _sendMail(),
child: Text('send'),
),
)
void _sendMail() async {
return await api.sendEmail(widget.namaUpdate, widget.jurusanUpdate,['zefry.reynando#gmail.com']);
}
it's possible sending email automatic without open gmail app first ? (Like in codeigniter)
i trying using another package but always open gmail app first. or this how it works?
Thanks
You're not likely to find a package that sends email out without either configuration or a visible mail client. That app would not by approved by either Apple or Google, because it might be a source of SPAM.