Can I use specific token for firebase? - firebase

I am developing a React Native app and I using Firebase push notification service.
I have users and all users have their own user token, I want to use these user tokens for send push notification.
First I thought, when user login to app I can register the user token to topic but I'm not sure about that too.
So is there any way to use custom token for send push notification to specific user?

Firebase Cloud Messaging doesn't have the concept of a user. All it knows it the so called FCM token, which identifies a specific installed app on a specific device.
If you're using the react-native-firebase library, you can learn how to get the FCM token from the documentation on saving tokens. Once you have the token, you can us the token to send a message to that specific app on that specific device.
If you want to target a user across any devices where they are using (and signed in to) your app, you'll need to relate the tokens of those devices to a user yourself. In the code example linked above that is done with:
firestore()
.collection('users')
.doc(userId)
.update({
tokens: firestore.FieldValue.arrayUnion(token),
});
This code saves the token to Cloud Firestore, but it would work the same on any database: this associates the FCM token (token) with the current user (userId) in a way that allows multiple tokens to be stored per user. Then when you want to send a message to a user, you look up the tokens for that user and call FCM to send to all those tokens.
Also see:
Can we send custom push notifications to independent users using Firebase?
FCM Notification to specific wordpress user

you can send notification for a specific user:
'to' => *users token*,
'notification' => [
'body' => $message,
title' => $title,
],

Related

Firebase Auth verify this user

I am currently verifying my user using the Auth JS SDK and Admin Auth SDK combined. I am doing in the following approach:
In the front-end:
firebase.auth().onAuthStateChanged(function (user) {
if (user) {
var current_user = firebase.auth().currentUser;
current_user.getIdToken(true).then(function (idToken) {
$.getJSON('/firebase_token', { token: idToken }, function (user) {
In the back-end:
router.get("/firebase_token", (req, res, next) => {
admin.auth().verifyIdToken(req.query.token).then(function(decodedToken) {
res.send(decodedToken);
})
})
I am wondering if this is a secured approach, because the user can just send whatever token they want from the front-end. For example, an invalid user can send a valid token they copied from a valid account to pass the token verification.
I am wondering if in the admin SDK. There is a way to detect the currently signed in user. In other words, detect this user who is using this instance of the app with the admin SDK?
I am wondering if this is a secured approach, because the user can just send whatever token they want from the front-end. For example, an invalid user can send a valid token they copied from a valid account to pass the token verification.
Yes, that's possible. But then again, if the user got access to a token, that means they probably are the user represented by that token, or they know the credentials of that account. That's not a problem at all - this is the way authentication systems work.
I am wondering if in the admin SDK. There is a way to detect the currently signed in user. In other words, detect this user who is using this instance of the app with the admin SDK?
No, the Admin SDK can't possibly know what all is going on for all of the users using your application. The ID token is exactly the piece of information it needs to verify users. A valid token proves that the user is who they say they are.

Firebase Push Notification - How to keep track of user FCM tokens?

This is a general question around FCM tokens. Currently in my react-native app, as soon as I have new token, I make an API call to link this token with a user ID. And when this token is also refreshed, I make the same API call again.
We use those tokens to send 'Happy Birthday' push notifications and the likes.
I would like to know in the event that a user does not use the app, this token will get expired and we do not have a way to keep track of the token. The birthday push notifs will still be sent to the old expired token. How can we mitigate this? Any idea ?
I am actually looking for a way/strategy to still have the push notifications being delivered to the user even if they have not used the app for a while? Do you think scheduled push notifications might work?
When you send data to an expired token, you'll get a response indicating this. You can capture this response, and use that to remove the tokens from your database.
The samples repo for Cloud Functions has a great example of this. Modified from there:
var response = admin.messaging().sendToDevice(tokens, payload);
// For each message check if there was an error.
const tokensToRemove = [];
response.results.forEach((result, index) => {
const error = result.error;
if (error) {
// Cleanup the tokens who are not registered anymore.
if (error.code === 'messaging/invalid-registration-token' ||
error.code === 'messaging/registration-token-not-registered') {
tokensSnapshot.ref.child(tokens[index]).remove();
}
}
});
I would like to know in the event that a user does not use the app,
this token will get expired and we do not have a way to keep track of
the token. The birthday push notifs will still be sent to the old
expired token. How can we mitigate this? Any idea?
In my case, I register for firebase token each time my front end application gets launched. Most of the time it sends the registration token which is already stored in my database. However, when a new firebase registration token is received in my server side, I store the new token and while sending the push notification, I send the notification to all available registration token that I have.
You cannot figure out if the user has stopped using your application until you get notified about launching your application by sending the firebase registration token to the server side application. Hope that helps.
We shall drive campaigns that retain our clients. All the above answers are right though.

How can I create long-lived tokens with Firebase Node.js SDK

I'm trying to implement the Authorization Code Flow to link actions on google with my firebase users:
https://developers.google.com/actions/identity/oauth2-code-flow
So far I've understood the flow as follows:
1 - User access the application and is redirected to the authorization url endpoint
2 - User signs in and google receives an authorization token
3 - Google sends this authorization token to the token url endpoint and gets an access token a refresh_token and a expiration time
4 - Google sends the refresh token to get a new access token when the access token is going to expire and gets a new acess token and a new expiration time
Did I get everything right?
As authorization token and access token I'm using the custom tokens from Firebase. My question is, how can I implement the refresh token? I cannot get this token from the Firebase Node.js SDK server side.
How can I greate long-lived tokens with Firebase Node.js SDK?
Is there another approach?
Yes, you got the OAuth2 process right.
The Firebase Admin SDK lets you sign the user in to your Firebase service using generated custom tokens. Though the custom token expires within 1 hour, once user is signed-in, they should be authenticated indefinitely (i.e. until user signs out). As such, there is really no need for SDK to generate refresh token.
I'd suggest a different approach. Use Actions on Google's SignIn helper intent to get user's info, such as email, name etc. Using this info, you will be able to sign the user in to Firebase as follows (referenced from the "Create Custom Token" Firebase doc):
var uid = "some-uid";
admin.auth().createCustomToken(uid)
// token == custom token
.then(function(token) {
firebase.auth().signInWithCustomToken(token).catch(function(error)
{
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
});
})
.catch(function(error) {
console.log("Error creating custom token:", error);
});
References:
"How to use refresh token?" from Firebase's GitHub
"Create custom tokens" from Firebase's docs
"Request Signin helper" from Actions on Google docs

Firebase Cloud Messaging: Why do registration tokens get deleted?

In our app we use Firebase Cloud Messaging to send push notifications to our users. We save the registration tokens of our users in our SQL database and when a user logs in or out we use the Firebase API to manage his topic subscriptions.
This works out pretty well in most of the cases but now the topic subscriptions return the following error for some of our registration tokens:
The provided registration token is not registered. A previously valid registration token can be unregistered for a variety of reasons. See the error documentation for more details. Remove this registration token and stop using it to send messages
In which cases does Firebase delete previously registered registration tokens? I can not find any specific information about this in the error documentation.
Thanks for your help!
From the documentation:
A previously valid registration token can be unregistered for a variety of reasons, including:
The client app unregistered itself from FCM.
The client app was automatically unregistered. This can happen if the user uninstalls the application or, on iOS, if the APNS Feedback
Service reported the APNS token as invalid.
The registration token expired. For example, Google might decide to refresh registration tokens or the APNS token may have expired for
iOS devices.
The client app was updated, but the new version is not configured to receive messages.

Push notifications by username

I have been looking for ways to send notifications to specific users and what I found was that I need the device token to do that.
I have tried Firebase and Ionic Cloud Service to do some pushs and it worked fine, but I'm wondering if it's possible to register a service with a key -> value, for exemple, register with the username and the token. If so, how can I do it?
And what is the best service to do it?
Thank you in advance for the help.
P.S.: I'm not asking for code, just the theory.
From you question [for example, register with the username and the token. If so, how can I do it?] I understand following.
You mean to say, there is a mobile app, which user will sign up to use and you want to send the notification to registered user i.e. get send push notification by username.
To solve this, you can follow the steps mentioned below.
On app launch when you get FCM registration token, save it to some intermediate location such as local storages along with device-id, mobile details etc..
Create a backend API which can save username and registration token in DB.
When a user signs up or signs in, then fetch the registration token from local storages, post username, token to backend API to save it. You can make backend API bit intelligent to handle multiple devices of the single user, distinguishable by device-id, mobile details.
Then while sending API from the backend, you can fetch all registration ids of a single user and send the notification to that users using all tokens of that user in FCM API. Use registration ids as JSON array in "registration_id" field. FCM Document - link.

Resources