Meteor js requestPermissions not working. I want to access google calendar, access token not permission with google calendar. How I can get access google calendar.
there are two things to consider. The right permission you need from google, and the API you use to access your data. You don't provide too many details so I don't know whether you need mobile (Cordova) too.
For your project, in Google Developer Console you need to enable the Calendar API. Once you do that, you have options to see what appId / authorization is relevant for your API so you add it to your Meteor Settings.
Then from the OAuth 2.0 scopes you need to select the exact scope you need (search for "calendar" for instance) and add that scope (the entire url) to your array of scopes.
Then you can do GET or POST with something like the native HTTP API of Meteor
example:
let data = HTTP.call('GET', `https://people.googleapis.com/v1/people/me/connections?pageToken=${res.data.nextPageToken}&personFields=emailAddresses`,
// let data = HTTP.call('GET', `https:https://www.googleapis.com/calendar/v3/calendars/{... your calendarId} `,
{
headers: {
Authorization: `Bearer ${accessToken}`,
Accept: 'application/json'
}
},
(err, res) => { handle these })
Related
Manifest version 3 for Chrome extensions have been killing me lately. Been able to navigate around it so far, but this one has really stumped me. I'm trying to use Firebase authentication for a Chrome extension, specifically with 3rd party auth providers such as Google and Facebook. I've setup the Firebase configuration for Login with Google and created a login section in the options page of the Chrome extension and setup the Firebase SDK.
Now, there are two login options when using an auth provider, signInWithRedirect and signInWithPopup. I've tried both of these and both have failed for different reasons. signInWithRedirect seems like a complete dead end as it redirects to the auth provider, and when it attempts to redirect back to the chrome-extension://.../options.html page, it just redirects to "about:blank#blocked" instead.
When attempting to use signInWithPopup, I instead get
Refused to load the script 'https://apis.google.com/js/api.js?onload=__iframefcb776751' because it violates the following Content Security Policy directive: "script-src 'self'". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.
In v2, you could simply add https://apis.google.com to the content_security_policy in the manifest. But in v3, the docs say
"In addition, MV3 disallows certain CSP modifications for extension_pages that were permitted in MV2. The script-src, object-src, and worker-src directives may only have the following values:"
self
none
Any localhost source, (http://localhost, http://127.0.0.1, or any port on those domains)
So is there seriously no way for a Google Chrome extension to authenticate with a Google auth provider through Google's Firebase? The only workaround I can think of is to create some hosted site that does the authentication, have the Chrome extension inject a content script, and have the hosted site pass the auth details back to the Chrome extension through an event or something. Seems like a huge hack though and possibly subject to security flaws. Anyone else have ideas??
Although it was mentioned in the comments that this works with the Google auth provider using chrome.identity sadly there was no code example so I had to figure out myself how to do it.
Here is how I did it following this tutorial:
(It also mentions a solution for non-Google auth providers that I didn't try)
Identity Permission
First you need permission to use the chrome identity API. You get it by adding this to your manifest.json:
{
...
"permissions": [
"identity"
],
...
}
Consistent Application ID
You need your application ID consistent during development to use the OAuth process. To accomplish that, you need to copy the key in an installed version of your manifest.json.
To get a suitable key value, first install your extension from a .crx file (you may need to upload your extension or package it manually). Then, in your user data directory (on macOS it is ~/Library/Application\ Support/Google/Chrome), look in the file Default/Extensions/EXTENSION_ID/EXTENSION_VERSION/manifest.json. You will see the key value filled in there.
{
...
"key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgFbIrnF3oWbqomZh8CHzkTE9MxD/4tVmCTJ3JYSzYhtVnX7tVAbXZRRPuYLavIFaS15tojlRNRhfOdvyTXew+RaSJjOIzdo30byBU3C4mJAtRtSjb+U9fAsJxStVpXvdQrYNNFCCx/85T6oJX3qDsYexFCs/9doGqzhCc5RvN+W4jbQlfz7n+TiT8TtPBKrQWGLYjbEdNpPnvnorJBMys/yob82cglpqbWI36sTSGwQxjgQbp3b4mnQ2R0gzOcY41cMOw8JqSl6aXdYfHBTLxCy+gz9RCQYNUhDewxE1DeoEgAh21956oKJ8Sn7FacyMyNcnWvNhlMzPtr/0RUK7nQIDAQAB",
...
}
Copy this line to your source manifest.json.
Register your Extension with Google Cloud APIs
You need to register your app in the Google APIs Console to get the client ID:
Search for the API you what to use and make sure it is activated in your project. In my case Cloud Firestore API.
Go to the API Access navigation menu item and click on the Create an OAuth 2.0 client ID... blue button.
Select Chrome Application and enter your application ID (same ID displayed in the extensions management page).
Put this client ID in your manifest.json. You only need the userinfo.email scope.
{
...
"oauth2": {
"client_id": "171239695530-3mbapmkhai2m0qjb2jgjp097c7jmmhc3.apps.googleusercontent.com",
"scopes": [
"https://www.googleapis.com/auth/userinfo.email"
]
}
...
}
Get and Use the Google Auth Token
chrome.identity.getAuthToken({ 'interactive': true }, function(token) {
// console.log("token: " + token);
let credential = firebase.auth.GoogleAuthProvider.credential(null, token);
firebase.auth().signInWithCredential(credential)
.then((result) => {
// console.log("Login successful!");
DoWhatYouWantWithTheUserObject(result.user);
})
.catch((error) => {
console.error(error);
});
});
Have fun with your Firebase Service...
I am building a web site and decided to go pure HTML+JS with full Firebase so I don't have to implement a backend system to test new ideas. The use case for this question is that all users should be authenticated in order to get access to the pages (pretty standard security feature, right?).
To accomplish that, I am taking advantage of Google Cloud Functions to check whether a user is signed in or not before allowing access to the pages.
Here is the code implemented on firebase.json:
"hosting": {
"rewrites": [ {
"source": "/home.html",
"function": "home"
} ]
}
Inside the home function, I run the following code to check whether the Id Token is a valid one:
admin.auth().verifyIdToken(idToken).then((decodedToken) => {
const userId = decodedToken.uid;
})
The problem I am facing is that the value for idToken is invalid:
Firebase ID token has incorrect algorithm. Expected "none" but got
"RS256"
I tried to copy & past the value from result.credential.accessToken, but I still get the same error message.
firebase.auth().getRedirectResult().then(function(result) {
if (result.credential) {
var token = result.credential.accessToken;
}
});
Any help will be very appreciated.
Thanks!
I understand that you direct the HTTPS requests to your home HTTPS Cloud Function.
You should pass the Firebase ID token as a Bearer token in the Authorization header of the HTTP request, as explained and demonstrated in the following official Cloud Function sample.
So I want to have a nuxt site hosted on Netlify where there's a child route whos slug is a firebase firestore document id.
Example:
https://www.example.com/users/steve
(where "steve" is the documentid)
So when the route is hit I would need to query firebase to see if it exists, and if not I would have to return a 404. Is this even possible? I can do it easy in .net or php, but I'm very unsure of a SPA.
Specifically what should I be looking for in the docs, if I can do this?
One solution is to implement an HTTPS Cloud Function that you would call like a REST API, sending an HTTP GET request to the functions endpoint.
As explained in the doc "Used as arguments for onRequest(), the Request object gives you access to the properties of the HTTP request sent by the client".
So you Cloud Function would look like:
exports.getUser = functions.https.onRequest((req, res) => {
// get the value of the user by parsing the url
const baseUrl = req.baseUrl;
//Extract the user from baseUrl
const user = ....
//query the Firestore database
admin.firestore().collection('users').doc(user).get()
.then(doc => {
if (doc.exists) {
res.status(200).end();
} else {
res.status(404).end();
}
});
See the get started page and the video series for more info on Cloud Functions.
Note that you can connect an HTTP function to Firebase Hosting, in such a way that "requests on your Firebase Hosting site can be proxied to specific HTTP functions".
I'm working on a new Meteor project which involves users logging into the site using their Google accounts through OAuth (I'm using the Meteor accounts-google package for this) and when signing in I need them to be able to see some data from the YouTube Analytics API for their YouTube channel. As of now the data I am trying to get is their total daily views, which I then hope to display on a chart for a specified time period.
I have added the following scopes to my accounts-google login system:
Meteor.loginWithGoogle({
requestPermissions: ['https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/yt-analytics.readonly', 'https://www.googleapis.com/auth/youtube.readonly'],
requestOfflineToken: true,
forceApprovalPrompt: true,
loginStyle: "popup"
});
This all seems to be working very well, once a user signs into the site and grants the site access to these I can then see the necessary info in my MongoDB database. Under user.services.google I can now see it has accessToken, idToken, expiresAt, refreshToken, etc.
I've also decided to use the google api nodejs client by implementing it through the meteorhacks:npm package for Meteor. I am using this to refresh tokens (as seen in this SO answer I found helpful).
Using the "Try It" API Explorer on the YouTube Analytics API Documentation page, I can get the type of data I'm looking for through this request:
GET https://www.googleapis.com/youtube/analytics/v1/reports?ids=channel%3D%3DMINE&start-date=2015-10-01&end-date=2015-10-31&metrics=views&dimensions=day&sort=-day&key={YOUR_API_KEY}
Now is where I've been completely stuck and really unsure of where to go from here. How can I implement this into my site? I've tried for quite some time now to make this work but everything I attempt isn't working, and there's no real direction. If anyone is willing to help out I'd greatly appreciate it. I'm fairly new to Meteor/JS/APIs so any information/examples is extremely appreciated, especially noob friendly stuff! ;)
One way to do it is to use a method and the http package: https://atmospherejs.com/meteor/http
Looking at the doc you provide, you may try something like this:
Define your method on the server side
// server-side
Meteor.methods({
getYoutubeReports: function(channelId, accessToken, params) {
params.ids = "channel=="+ channelId;
params.key = accessToken;
return HTTP.get("https://www.googleapis.com/youtube/analytics/v1/reports", {
params: params
});
}
});
You can then call it on the client side with the data you get from your the authentication (ie. CHANNEL_ID_OF_MY_USER & ACCESS_TOKEN_OF_MY_USER)
// client-side
var reports,
myParams = {
"start-date": "2015-10-01",
"end-date": "2015-10-31",
"metrics": "views",
"dimensions": "day",
"sort": "-day"
};
Meteor.call('getYoutubeReports', CHANNEL_ID_OF_MY_USER, ACCESS_TOKEN_OF_MY_USER, params, function(error, result) {
// store or do stuff with the result of the HTTP request here
console.log(result);
});
Feel free to custom myParams as your user need!
And if you want to some more tips about how to use HTTP request (really useful to call external API), The Meteor Chef wrote a really good article about it : https://themeteorchef.com/snippets/using-the-http-package/
I hope it helps!
I ended up using the percolate:google-api package to handle my API call.
I am using meteor to create a webpage with a dropdown list of Google Groups to select from and once selected, the Google contacts will be displayed.
I am using HTTP.call POST to Google's API and testing with the accessToken from mongoDB but when I use that token after some time it expires. I looked into implementing an authentication flow but it is getting very complicated since there is no sample code on Google for meteor. I am new to nodeJS, Javascript and Meteor. Am I going about this the wrong way? How would I implement this in meteor?
https://developers.google.com/accounts/docs/OAuth2?csw=1#expiration
To deal with the expiration of the accessToken, you will need to obtain the refreshToken from Google. With this refreshToken, you can obtain a new accessToken whenever necessary via a simple HTTP POST to Google's API. Here is the relevant documentation from Google. To obtain the refreshToken, you will need to request for offline access and may also need to force the approval prompt, as detailed in this SO post.
forceApprovalPrompt: {google: true},
requestOfflineToken: {google: true},
I recommend achieving all of the above using Meteor's HTTP package. All the tools are there. You've probably already figured it out:
var result = HTTP.post(
"https://www.googleapis.com/oauth2/v3/token",
{
params: {
'client_id': config.clientId,
'client_secret': config.secret,
'refresh_token': user.services.google.refreshToken,
'grant_type': 'refresh_token'
}
});
//Do some error checking here
var newAccessToken = result.data.access_token;
refresh_token - The refresh token returned from the authorization
code exchange.
client_id - The client ID obtained from the
Developers Console.
client_secret - The client secret obtained from
the Developers Console.
grant_type - As defined in the OAuth 2.0
specification, this field must contain a value of refresh_token.
result.data will be a JSON object with the following
{
"access_token":"1/fFBGRNJru1FQd44AzqT3Zg",
"expires_in":3920,
"token_type":"Bearer",
}
Have a look at this package its a little wrapper that does auto refresh for you:
here
I actually ended up building my own auth flow for with oauth handler because i needed to move away from a tokens linked to user profiles.