OTP Verification in flutter without Firebase - android

After registering a new user with email and password using firebase flutter. Is there any way to verify his phone number without a firebase phone authentication so the same user will not be registered with email/password and phone number (I want to register him once using his email and password and verify his phone number)?

(Currently this package is outdated.It does not support Null Safety).
You can try flutter_otp package I think it's the best option,
You can visit https://pub.dev/packages/flutter_otp for more info,
try the bellow example
import 'package:flutter/material.dart';
import 'package:flutter_otp/flutter_otp.dart';
// Now instantiate FlutterOtp class in order to call sendOtp function
FlutterOtp otp = FlutterOtp();
class SendOtp extends StatelessWidget {
String phoneNumber = "93XXXXXXXX"; //enter your 10 digit number
int minNumber = 1000;
int maxNumber = 6000;
String countryCode ="+91"; // give your country code if not it will take +1 as default
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("send otp using flutter_otp ")),
body: Container(
child: Center(
child: RaisedButton(
child: Text("Send"),
onPressed: () {
// call sentOtp function and pass the parameters
otp.sendOtp(phoneNumber, 'OTP is : pass the generated otp here ',
minNumber, maxNumber, countryCode);
},
)),
),
);
}
}

I think you could try this package: https://pub.dev/packages/flutter_otp
and there are also a lot of websites that providers OTP SMS Services.
Tip: You can even use Firebase Auth since it also suits your case.
In firebase, you can just link (something like merge) the accounts that are created with Email and Phone using like this emailUser.getCurrentUser().linkWithCredential(phoneUserCredential)
In this case, your app will consist of one user with that Email and Phone.
Additional Benefit is that you don't want to store phone numbers in a separate database.
After linking both the accounts, you can just simply use user.displayName and user.phoneNumber to fetch your Email and Phone.
Refer:https://firebase.google.com/docs/auth/android/account-linking
https://firebase.google.com/docs/auth/web/account-linking

Related

Android: How to get device id from a Google Analytics even in firebase - functions

I am trying to get firebase device id in firebase functions (Node JS)
This is the document that I have referenced.
https://firebase.google.com/docs/reference/functions/firebase-functions.analytics.deviceinfo.md#analyticsdeviceinfo_interface
This is how I am trying to get it, but in the logs i can see that its undefined.
const deviceId = functions.analytics.DeviceInfo.deviceId;
Here is my complete code
const admin = require("firebase-admin");
admin.initializeApp();
const database = admin.firestore();
exports.appUninstall = functions.analytics.event("app_remove")
.onLog((event) => {
const deviceId = functions.analytics.DeviceInfo.deviceId;
console.log("deviceId", deviceId);
database.doc("userActivity/uninstalls"+deviceId)
.update({"device_id": deviceId});
return console.log("uninstall event called");
});
How can we get the device id through firebase functions.
I am trying to get the device id when we uninstall the app.
By default we get some information in the event object and it contains the device info as well but it does not contain the device_id. Now I am looking for ways to add the device_id to the event object.

Flutter - How to know if user shared my app or not?

I have implemented the below given code to let user share my app. It works fine, but how can I know if the user actually shared my app or not? Because my app unlocks a certain feature if the user shares the app.
[Package used:- share_plus 3.0.4 ]
onTap: () async {
const _textShareUrl =
'https://www.youtube.com/watch?v=CNUBhb_cM6E&list=PLk6qkmrzOcdx5R4-UqI_jDPYsLWNnZ1dq&index=2';
await Share.share(
'Social share test\n\n$_textShareUrl');
Future.delayed(const Duration(seconds: 10), () {
setState(() => _share = true);
});
},
There is already an open issue:
https://github.com/fluttercommunity/plus_plugins/issues/386

is there any way to pop all screens in flutter app by one click without logging the user out?

I want the user to be able to exit the app by clicking the phone back button one time (and then he gets a warning message).
but all I found is the option to call to exit(0), but this is logging the user out.
I am using firebase & flutter.
Also, when pressing the back button when I'm in the home_page (which appears after logging), I get the login view again instead of exiting the app.
How can I prevent that (because I want the user to stay logged in)
these is the code in my main.dart build() :
return StreamProvider<User?>.value(
value: logic.listenToUserAuth(),
initialData: null, //user signed out
child: MaterialApp(
//initialRoute: '/login',
//routes: this.routes,
// passing the change in stream to child widgets
home: MainWrapper(routes: this.routes,),
),
these is the code from MainWrapper build() , that determines which view to show to the user, depends if he is logged in or not, but it does not work.. the user always gets the '/login' view :
final user = Provider.of<User?>(context);
String initRout = "/login";
// the user logged in
if(user != null) {
initRout = "/home_page.dart";
}
return MaterialApp(
initialRoute: initRout,
routes: routes,
);
Thanks
For the back button issues, this libray will solve your problem
https://pub.dev/packages/back_button_interceptor
To sign out user, use this method on button clicks or after doing some logic
FirebaseAuth.instance.signOut();
To persist user auth using flutter and firebase, refer to this answer:
https://stackoverflow.com/a/45084649/11838875
I was facing the same problem, the Get package solved everything, use Get package, and then use Get.offAll("spacify the screen which should be last in the stack"); and you're done

FCM MessagingOptions restrictedPackageName implementation

We have 2 Android apps in one Firebase project container, the first app has FCM implementation on Cloud Function and it works well, but the second app will received this notification as well so using restricted_package_name in messaging option is what we are looking for. However the question is, do we need to update the app as well or just the function in Cloud Function? Thus everything related to filtering of push notif. will be handled by its API and all we need is to provide the package name for the target app.
According to documentation of restrictedPackageName
The package name of the application which the registration tokens must match in order to receive the message.
Do we need to handle token as well? Do we need to update the code in the app or just add the option in the function with NodeJs?
const options = { priority: 'high' };
exports.announcement = functions.firestore.document("Announcement/{doc_id}").onCreate((added) => {
const title = added.data().title;
const description = added.data().description;
const bigImage = added.data().bigImage;
const link = added.data().link;
const environment = added.data().environment;
const payload = {
data: {
title: title,
description: description,
bigImage: bigImage,
link: link,
environment: environment,
}
};
return admin.messaging().sendToTopic("Announcement", payload, options)
.then(val => {
console.log("Success!\n" + JSON.stringify(payload), val);
return true;
})
.catch(error => {
console.error("Failed to send notification.", error);
return true;
});
});
From Firebase side it is not recommended to use same project for 2 different applications, which was also mentioned in this blog. If you want to use restricted_package_name you need to update the code so that the object sends it in notification. You can find a small example here.

How to trigger Firebase cloud functions to update a field by a condition once a day and send push notification to Android client

I'm totally new to Cloud Functions of Firebase and I need a little support.
I would to trigger two cloud functions, one that run once a day and the other one that sends a push notification to my Android client app.
Just let me write a little representation of my Cloud Firestore (not Realtime Database), IDs are auto generated by Firebase:
/users
/uId1
/myitems
/adId1
/myinterestedusers
/uId2
/adId2
...
/uId2
...
/itemsonsale
/uId1_adId1
/uId1_adId2
/uId2_adId1
I perform all the operations to populate and update the db correctly in the client side Android app written in koltin but I need these more things.
The function I would trigger once a day has to update a field if a string in a adIdXX document, representing the date, is expired and then it should be change another field in the same documentReference with string "EXPIRED". All this operation must be done for each docRef that have a adIdXX in all the db, so for each /myitems/{id} of each /users/{id} and for each /itemsonsale/{id}.
The other one, that must be send a push notification to my client, has to listen for the same status as above but when it will be "SOLD" it must notify the interested users, so for example I thought that it's enough to watch the /itemsonsale collection and for each {id} document check this field and then following this path to send notification to that user in /users:
/itemsonsale/{id} checks fields "status"=="SOLD"
take ownerID
go to /users/ownerIdXX/myitems/adIdXX/myinterestedusers/{id}
and send a push notification for each of those {id} documents in that collection
NOTE: uIdXX_adIdXX stands for ownerId_adId
Hope I explained my idea and wait for support cause I have no idea of where to start...
EDITED: after a few hours I'm stuck on this code below...anyone can tell me how can I continue?
exports.checkItemsSold =
functions.firestore.document('/itemsonsale/{id}')
.onUpdate((change, context) => {
const after = change.after.data()
const before = change.before.data()
const oldStatus = before.itemStatus
const newStatus = after.itemStatus
console.log(`Item's owner replaced ${oldStatus} with ${newStatus}\n`)
if(newStatus === "SOLD")
{
//here I have to send push to interested users
}
})
exports.checkItemsExpirationDate =
functions.firestore.document('/users/{uid}/myitems/{iid}') //but really all the db so also /itemsonsale/{id}
.onUpdate((change, context) => {
const after = change.after.data()
const before = change.before.data()
//I'm not sure if onUpdate() is the right way for this task
//but this function has to perform the check of date expiration
//from 'expiryDate' field and in case of it's expired must set
//"EXPIRED" to 'itemStatus' field. All for each item in the db, once a day
console.log('Updated info from data: ', after)
});
After checking your code I can say that at least this section is ok:
exports.checkItemsSold =
functions.firestore.document('/itemsonsale/{id}')
.onUpdate((change, context) => {
const after = change.after.data()
const before = change.before.data()
const oldStatus = before.itemStatus
const newStatus = after.itemStatus
console.log(`Item's owner replaced ${oldStatus} with ${newStatus}\n`)
if(newStatus === "SOLD")
{
//here I have to send push to interested users
}
})
The main issue with the second one is that the triggers only happens when there is an update, write, delete or create event. As you're not waiting for an update or any of the other events but checking the status of some fields on your DB I would say that you can create an scheduled function. Here you will find an example code which is something like this for your case:
//Let's supose that you want to check the expiration date every day in the first minute of the day
const admin = require('firebase-admin');
admin.initializeApp();
let db = admin.firestore();
exports.scheduledFunctionCrontab = functions.pubsub.schedule('1 0 * * *')
.timeZone('America/New_York') // Users can choose timezone - default is America/Los_Angeles
.onRun((context) => {
//Here goes your code to change the status of the field needed in your DB to Expired.
return null;
});
Sorry if there is a mistake with the code but I'm not good with NodeJS. Good luck!

Categories

Resources