React Native Firebase v4.0 - Notification Module - javascript

I just installed react-native-firebase v4.0 and I'm trying to detect when someone opens a notification that I sent from google console.
But when I put the example from documentation into my code, I get
Parsing error: Unexpected token, expected : (Fatal)
at "action"
What am I missing here? I never used this kind of syntax before.
componentDidMount() {
this.notificationOpenedListener = firebase.notifications().onNotificationOpened(notificationOpen: NotificationOpen => {
// Get the action triggered by the notification being opened
const action = notificationOpen.action;
// Get information about the notification that was opened
const notification: Notification = notificationOpen.notification;
});
}

All I needed to do was to put notificationOpen: NotificationOpen around parenthesis.
(notificationOpen: NotificationOpen)

Related

Writing to Firestore Database Results in Firestore net::ERR_BLOCKED_BY_CLIENT Error

I am trying to write to my firestore database and I get a net::ERR_BLOCKED_BY_CLIENT. I have a user save info from a form and writing it to a database.
Here is the request:
// react app
const referenceDescriptionTextArea = useRef();
const proposalsCollectionReference = collection(db, "proposals");
const handleProposalSubmit = async (event) => {
event.preventDefault();
var data = {
author: getCurrentUser().uid,
timestamp: Timestamp.now(),
tokenid: tokenid,
type: "bio",
description: referenceDescriptionTextArea.current.value,
};
addDoc(proposalsCollectionReference, data).then(
(docRef) => {
console.log(docRef.id); //saf89hnasHJADH9
closeModal();
},
(err) => {
console.log(err);
}
);
};
Console Error after trying to submit a proposal:
channelrequest.js:1086 POST https://firestore.googleapis.com/google.firestore.v1.Firestore/Write/channel?VER=8&database=projects%2FREDACTED%2Fdatabases%2F(default)&gsessionid=sdaf7uOt-NfCFKX32b-Mw3sJBli_ssdsdfkaNw&SID=Q-mrJ98YFSsadflZRPA&RID=20557&TYPE=terminate&zx=pyjwqxvmw7j9 net::ERR_BLOCKED_BY_CLIENT
Some things I have tried are the following :
Double checked the firestore rules to make sure it is value. In this case I only want authenticated users to write to the doc like so. Error persists.
match /proposals/{proposal} {
allow read, write: if request.auth != null;
}
I was convinced this was a firestore rule so I changed the firestore rule to allow anyone to write to it (on my local deployment). Error persists.
match /proposals/{proposal} {
allow read, write: if true; // on local deployment but not working
}
Some users state this error is due to Adblockers. To check against this I opened up a new instance of Chrome without extensions but I get the same results. I tried other browsers and ran into similar issues. Error persists.
I found out it was Brave Shield on Brave. I did more research and heres what I gathered.
Edge, Chrome and Firefox: By default I use chrome. It is typical for other browsers like Edge and Firefox to prompt and auto import your settings (this includes bookmarks and extensions and only done once after install). Remove extensions like uBlockOrigin or HTTPS Everywehere. Once they were uninstalled I was able to make a request without an error
Brave Browser: By default it will have an adblocker called BraveShield. At the top right corner, click on the icon>Disable. The Error should now go away.

firebase auth/operation-not-allowed

This is an angular web app.
Added the screenshot of the permission page
I'm trying to authenticate mobile using firebase.
In my firebase console > Authentication > signIn Method, I've enabled the phone and saved it.
But when I try to login It throws me an error saying that
auth/operation-not-allowed
sendLoginCode() {
const appVerifier = this.windowRef.recaptchaVerifier;
const num = this.firstFormGroup.value.mobileNo
console.log('num',num);
firebase.auth().signInWithPhoneNumber(num, appVerifier)
.then(result => {
this.windowRef.confirmationResult = result;
})
.catch(error => console.log(error));
}
verifyLoginCode() {
this.windowRef.confirmationResult
.confirm(this.verificationCode)
.then(result => {
this.user = result.user;
console.log('Login Successfull')
})
.catch(error => console.log(error, "Incorrect code entered?"));
}
It looks like you haven't enabled the Google sign in method in your firebase console. To solve the issue do the following:
Enter to the firebase console (https://console.firebase.google.com/).
Select your project.
On the right side of the screen you'll see a panel, click where it says "Authentication".
Once you've entered to the Authentication menu, go to Sign-in method.
After that look for the google access provider in the list that appears below the header and click on it.
Then click on the enable button.
It is probable that you'll have to configure a secure project ID (you'll see a dropdown below the enable button). What you have to do is, enter the android and/or ios client ID from your project, and hit save. This will tell firebase that it is secure to handle sign in operations with that client.
To be able to use the phone sign in method, you need to have a paid plan active.
Original author of answer: https://stackoverflow.com/a/65598080/6310260

How do I save user account information to firebase?

I've made a Google Log in for my actions on google project, and I want to save the account info to a firestore database.
I looked at Google's example of how to do this (example here, at the very bottom under heading "Handle Data Access Requests"), but when you actually try to deploy it to firebase, you realize that it's actually has invalid syntax (or at least that's what the dialogflow inline editor is saying.....)
Here's what the error says specifically when I try to deploy this code:
The deployment of your Cloud Function failed:
Function load error: Code in file index.js can't be loaded.
Is there a syntax error in your code?
Detailed stack trace: /user_code/index.js:34
app.intent('Get Sign In', async (conv, params, signin) => {
^
SyntaxError: Unexpected token (
Any suggestions?
Thanks for the help!
Please note: I am using only the code that the tutorial has said to PLUS
I added the actions on google library and the fulfillment line (ie:
// Other libraries...
const {
dialogflow,
BasicCard,
Permission,
Suggestions,
Carousel,
SignIn
} = require('actions-on-google');
// ** code from tutorial / link **
exports.dialogflowFirebaseFulfillment = functions.https.onRequest(app)
I figured out how to do this, however it was a different method than the actions on google example. If anyone knows how to do this easier or knows what was wrong with the code in the link I posted (if anything..) please let me know / add an answer!
I decided to just write to firestore directly and put it under a "Get Signin" function (also mentioned in the tutorial for dialogflow).
Here is the function I used to get the user to sign in and also log the information into firestore:
app.intent('Get Signin', (conv, params, signin) => {
if (signin.status === 'OK') {
const payload = conv.user.profile.payload;
conv.ask(`Welcome back ${payload.name}. What can I help you with??`);
const databaseEntry = conv.user.profile.payload; // Account info, loaded to firestore
const accountRef = db.collection('Accounts').doc('account_info'); //How you want the info in firestore to appear
return db.runTransaction(t => {
t.set(accountRef, {entry: databaseEntry});
return Promise.resolve('Write complete');
}).then(doc => {
}).catch(err => {
console.log(`Error writing to Firestore: ${err}`);
});
} else {
conv.close(`To continue, you need to make an account with the app.`);
}

Stay logged in when using msal.js

I'm building a small JS app for my Microsoft ToDo tasks and use the msal.js library to accommodate the authentication process.
This works perfectly fine, I get a popup, I authenticate my profile, the popup closes and my tasks appear on my screen.
But: It doesn't seem to remember that I authenticated before; Every time I run my webpack app and the page is booted it shows the popup and asks for authentication. Once I've authenticated and just refresh my page, it just shows me the tasks without showing the popup again. I haven't tried waiting for an hour but I think it has something to do with not properly refreshing my access token. I'm not that involved with the Outlook/Microsoft API that I can really figure out if I'm using it correctly.
In short: How can I authenticate once so that the next time I start my app the tasks are shown without having to authenticate again?
My init function
this.userAgentApplication = new Msal.UserAgentApplication(microsoftTasksClientId, null, function (errorDes, token, error, tokenType) {
// this callback is called after loginRedirect OR acquireTokenRedirect (not used for loginPopup/aquireTokenPopup)
console.log(token)
})
let user = this.userAgentApplication.getUser()
if (!user) {
const self = this
// this.userAgentApplication = new Msal.UserAgentApplication(microsoftTasksClientId)
this.userAgentApplication.loginPopup([`${this.apiRootUrl}Tasks.readwrite`]).then(function (token) {
self.idToken = token
user = self.userAgentApplication.getUser()
if (user) {
self.getSilentToken()
}
}, function (error) {
console.log(error)
})
} else {
this.getSilentToken()
}
And my getSilentToken function
const self = this
this.userAgentApplication.acquireTokenSilent([`${this.apiRootUrl}Tasks.readwrite`]).then(function (token) {
console.log('ATS promise resolved', token)
self.accessToken = token
self.getTasks()
}, function (err) {
console.log(err)
})
Please not that my code isn't refactored AT ALL! ;-)
What version of MSAL are you using?
There is a problem in 0.1.1 version that storage is 'sessionStorage' by default and can't be really changed. In that case your login is saved just for currently opened window and you will be forced to relogin even when opened new browser window.
You should use 'localStorage' to achieve what you want and pass it as a constructor parameter for UserAgentApplication.
Here is a fix in their repo for this:
https://github.com/AzureAD/microsoft-authentication-library-for-js/commit/eba99927ce6c6d24943db90dfebc62b948355f19

Send FCM to all Android devices using Cloud Functions

Just trying to understand the process for sending a Firebase Cloud Message using Cloud Functions to notify all users who have my app installed on their phone. This would fire whenever a new event has been added at a particular branch, as follows:
var functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const payload = {
notification: {
title: 'New event added'
}
};
exports.bookingsChanged = functions.database.ref("/Events")
.onWrite(event => {
return admin.messaging().sendToDeviceGroup("latest_events", payload);
});
The above function I've uploaded doesn't appear to send the message to the Android device I'm using at all, despite setting up and testing FCM using the Firebase Console option to send messages. I've noticed there is little documentation for this at the moment, so any help would be greatly appreciated!
EDIT
I may've missed this, but I've replaced the string 'latest_events' with my Android application package name that I assume is required, as per the console to target a 'User Segment'.
Ended up solving this by waiting for a topic I had set up to appear in the Firebase Notifications dashboard. I then changed the following code to send to this topic directly:
return admin.messaging().sendToTopic("latest_events", payload);
I also found out that you have to provide a token when using 'sendToDevicegroup' after coming across the API documentation. Therefore, topics are more effective in my use case as I do not wish to obtain tokens to send to specific user devices.
Hope this helps someone who experiences a similar problem!
ADDITIONAL EDIT
If like me, you would like to alert users only of new events that have been added to a specific branch, typically including a push id, I've created the following code to implement this.
With a little help from the examples in the documentation, this will evaluate the number of records at the location compared to the previous location. Thus, this will only alert users of new child records that are added, rather than every time a record is edited and deleted.
var functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.bookingsChanged = functions.database.ref("/Bookings").onWrite(event
=> {
var payload = {
notification: {
title: "A new event has been added!"
}
};
if (event.data.previous.exists()) {
if (event.data.previous.numChildren() < event.data.numChildren()) {
return admin.messaging().sendToTopic("latest_events", payload);
} else {
return;
}
}
if (!event.data.exists()) {
return;
}
return admin.messaging().sendToTopic("latest_events", payload);
});

Categories