Writing data in Service Worker to Cloud Firestore - javascript

I'm working on a Firebase project and I want to receive firebase cloud messages (send from a Node.js server) in my service worker in my javascript project. This works fine, but now I want to save some data in my firebase cloud firestore from my service worker after receiving the notification. And there is the problem, I'm running in the error listed below:
Uncaught ReferenceError: XMLHttpRequest is not defined at Ln.<anonymous> (xmlhttp.js:167) at Me (channelrequest.js:512) at Ce (webchannelbase.js:1249) at Kn.xa (webchannelbase.js:1251) at re (run.js:124)
Since a few days I'm trying to find the error, but could not find a solution until now. Therefore I hope that you can help me now. I've tried to save the data in the firebase realtime database which works, but because I need to have offline persistence, I had to switch to cloud firestore which runs in the error above.
Here is the code from my node.js server for sending the notification (userID and registrationToken is defined before):
payload = {
data: {
"title": "This is a Notification",
"body": "This is the body of the notification message."
},
};
options = {
priority: "high",
timeToLive: 7200
};
// send message to the registration token
admin.messaging().sendToDevice(registrationToken, payload, options).then(function(response) {
admin.firestore().collection("Logging").doc(userID).set({active: "true"});
}).catch(function(error) {
console.log("Error sending message:", error);
});
And here is the code for receiving the notification in my firebase-messagins service worker file (userID is defined before):
self.addEventListener('notificationclick', function(event) {
event.notification.close();
const keepAlive = async() => {
firebase.firestore().collection("Logging").doc(userID).update({"open": "true"});
}
event.waitUntil(keepAlive());
});
Can anyone help me, please? I have no more ideas for solving my problem :/

You can't use XMLHttpRequest inside of a service worker. Instead, you need to use the Fetch API.
Based on your code, it's the Firebase client library that's using XMLHttpRequest under the hood. I don't think that you have any control over that (at least not based on what I see in the current JavaScript documentation for Firebase).
Instead of using the Firebase client library in your service worker, you could try using the REST API directly, using fetch() to send your HTTP requests. You'll be responsible for things like authentication and setting whatever user ids, etc. that the client library would otherwise handle for you, but I think that's your best bet inside of a service worker.

Since version 9 the Firebase Web SDK uses fetch instead of XMLHttpRequest. So it works inside a service worker.

Related

How to handle CORS error, while fetching firebase realtime database API in vue project?

I am using vue-2.And want to do shallow query for firebase realtime database by fetching API.But While running on development server ,it shows CORS blocked. What should I do?
PS: I am also using vuefire
created(){
var apiUrl = 'https://console.firebase.google.com/u/4/project/enajori-45094/database/enajori-45094/data/Admin/Data%20Collection/Paying%20Guest';
fetch(apiUrl).then(response => {
return response.json();
}).then(data => {
console.log(data);
}).catch(err => {
console.log(err);
});
}
Cors error i am receiving
Firebase REST-Api only reacts to HTTPS-Requests. If your localhost doesen't have SSL enabled your requests will fail no matter what your try. The URI also need to end with the the table's name like something.json
And you realy should use the Firebase SDK - it's the smoother way.
It's entirely unclear to me why you would want to use a URL to the Firebase console to access the database. Console URLs are for human consumption, not for programs.
You should use the provided javascript SDK to access data. It will work around CORS issues for you automatically, and give you a much cleaner way to read and write data. If you can't use the SDK, you can always try the REST API. Just don't depend on those console URLs at all.

facebook graph api node.js invalid appsecret_proof

this is my first post so please go easy on me!
I am a beginning developer working with javascript and node.js. I am trying to make a basic request from a node js file to facebook's graph API. I have signed up for their developer service using my facebook account, and I have installed the node package for FB found here (https://www.npmjs.com/package/fb). It looks official enough.
Everything seems to be working, except I am getting a response to my GET request with a message saying my appsecret_proof is invalid.
Here is the code I am using (be advised the sensitive info is just keyboard mashing).
let https = require("https");
var FB = require('fb');
FB.options({
version: 'v2.11',
appId: 484592542348233,
appSecret: '389fa3ha3fukzf83a3r8a3f3aa3a3'
});
FB.setAccessToken('f8af89a3f98a3f89a3f87af8afnafmdasfasedfaskjefzev8zv9z390fz39fznabacbkcbalanaa3fla398fa3lfa3flka3flina3fk3anflka3fnalifn3laifnka3fnaelfafi3eifafnaifla3nfia3nfa3ifla');
console.log(FB.options());
FB.api('/me',
'GET',
{
"fields": "id,name"
},
function (res) {
if(!res || res.error) {
console.log(!res ? 'error occurred' : res.error);
return;
}
console.log(res);
console.log(res.id);
console.log(res.name);
}
);
The error I am getting reads:
{ message: 'Invalid appsecret_proof provided in the API argument',
type: 'GraphMethodException',
code: 100,
fbtrace_id: 'H3pDC0OPZdK' }
I have reset my appSecret and accessToken on the developer page and tried them immediately after resetting them. I get the same error, so I don't think that stale credentials are the issue. My
console.log(FB.options())
returns an appropriate looking object that also contains a long hash for appSecretProof as expected. I have also tried this code with a number of version numbers in the options (v2.4, v2.5, v2.11, and without any version key). Facebook's documentation on this strikes me as somewhat unclear. I think I should be using v2.5 of the SDK (which the node package is meant to mimic) and making requests to v2.11 of the graph API, but ??? In any case, that wouldn't seem to explain the issue I'm having. I get a perfectly good response that says my appSecretProof is invalid when I don't specify any version number at all.
The node package for fb should be generating this appSecretProof for me, and it looks like it is doing that. My other info and syntax all seem correct according to the package documentation. What am I missing here? Thank you all so much in advance.
looks like you have required the appsecret_proof for 2 factor authorization in the advance setting in your app.
Access tokens are portable. It's possible to take an access token generated on a client by Facebook's SDK, send it to a server and then make calls from that server on behalf of the client. An access token can also be stolen by malicious software on a person's computer or a man in the middle attack. Then that access token can be used from an entirely different system that's not the client and not your server, generating spam or stealing data.
You can prevent this by adding the appsecret_proof parameter to every API call from a server and enabling the setting to require proof on all calls. This prevents bad guys from making API calls with your access tokens from their servers. If you're using the official PHP SDK, the appsecret_proof parameter is automatically added.
Please refer the below url to generate the valid appsecret_proof,and add it to each api call
https://developers.facebook.com/docs/graph-api/securing-requests
I had to deal with the same issue while working with passport-facebook-token,
I finally released that the problem had nothing to have with the logic of my codebase or the app configuration.
I had this error just because I was adding intentionally an authorization Header to the request. so if you are using postman or some other http client just make sure that the request does not contain any authorization Header.

Best way to check if Twilio authentication is successful with JS SDK

What is the best way to check if Twilio auht_token, account_sid are correct and sms can be sent, number checked? Some call which doesn't cost extra credits?
E.g. I see https://www.twilio.com/docs/api/rest/usage-records on RESTfull documentation but can't find how to get the same thing with JS SDK. Can't see dedicated endpoint for config checking so looking for anything else.
Environment: NodeJS 8.9
Twilio developer evangelist here.
Most API calls to the Twilio REST API don't cost, particularly those where you retrieve a resource or list resources. Since you mentioned SMS you could, for example, list your latest messages like this:
const client = require('twilio')(accountSid, authToken);
client.messages.list({ limit: 10 })
.then(function(messages) {
console.log("Everything is good!");
})
.catch(function(err) {
console.error("Something went wrong: ", err)
})
Take a look through the API reference and pick one that takes your fancy.
Using JS SDK might be insecure here. Because of that I think they didn't include a method in the JS API which may present the user the account_sid and the auth_token, which may be exploited. I assume you can use a server bridge between your client JS and Twilio API. Like this:
Client makes a JS AJAX request to http://my.domain.tld/checkstatus
Server connects to the Twilio API with C#, PHP, NodeJS or whatever tech it uses
Twilio returns that the credentials and tokens are still valid or expired
Server prepares the client response as true/false or 0/1
Client reads the status and continues or redirects somewhere else.
Edit There's a GET method here which you can also use with JS AJAX call:
https://www.twilio.com/docs/api/rest/usage-records#list-get
which is requested by this format:
/2010-04-01/Accounts/{AccountSid}/Usage/Records/{Subresource}

Using ''User Notifications" Graph API for Facebook

Since Graph API v2.3, the notification request have been deprecated. I am new to using the API's and I was wondering how to use the POST edge request found here: https://developers.facebook.com/docs/graph-api/reference/user/notifications/
More specifically, to retrieve the unread notification's for a user.
Here is the code I have so far:
function getInfo() {
FB.api("/me/notifications", function(response) {
console.log(response);
});
}
That endpoint is for sending notifications only, you canĀ“t get the unread notifications anymore. And you need to use an App Token with an App Scoped ID for that call. You should not use an App Token client side, so sending notifications should always be done server side.
More information: https://developers.facebook.com/docs/games/services/appnotifications

Google Analytics API access with a service account

Can I access Google Analytics data using a service account in a client-side application? If not, are there other ways of achieving the same outcome?
Must be entirely client-side, and must not require users to authenticate (hence the desire to use a service account).
Yes you can in https://code.google.com/apis/console make sure you say that its a Service account it will give you a key file to download. With that you dont need a user to click ok to give you access.
For a service acccount to work you need to have a key file. Anyone that has access to that key file will then be able to access your Analytics data. Javascript is client sided which means you will need to send the key file. See the Problem? You are handing everyone access to your account. Even if you could get a service account to work using javascript for security reasons its probably not a very good idea.
You can use the official (and alpha) Google API for Node.js to generate the token. It's helpful if you have a service account.
On the server:
npm install -S googleapis
ES6:
import google from 'googleapis'
import googleServiceAccountKey from '/path/to/private/google-service-account-private-key.json' // see docs on how to generate a service account
const googleJWTClient = new google.auth.JWT(
googleServiceAccountKey.client_email,
null,
googleServiceAccountKey.private_key,
['https://www.googleapis.com/auth/analytics.readonly'], // You may need to specify scopes other than analytics
null,
)
googleJWTClient.authorize((error, access_token) => {
if (error) {
return console.error("Couldn't get access token", e)
}
// ... access_token ready to use to fetch data and return to client
// even serve access_token back to client for use in `gapi.analytics.auth.authorize`
})
If you went the "pass the access_token back to client" route:
gapi.analytics.auth.authorize({
'serverAuth': {
access_token // received from server, through Ajax request
}
})

Categories