401 GET Error Trying to access Spotify tracks href - meteor

I am trying to access tracks from a playlist with xinranxiao:spotify-web-api for MeteorJS. I sign in with a spotify account and am able to access data from spotify api. I am able to obtain users playlists, tracks, and artists etc. However If I try to play a song with a direct href url I get a
``
{
"error": {
"status": 401,
"message": "This request requires authentication."
}
}
I have configured my Spotify in a server located js file:
``
ServiceConfiguration.configurations.update
(
{ "service": "spotify" },
{
$set: {
"clientId": "eeeeeeeeeeeeeeeeeeeeeeeeeeee",
"secret": "bbbbbbbbbbbbbbbbbbbbbbb"
}
},
{ upsert: true }
);
In my client side js files I access playlists successfully running.
getUserPlaylists: function() {
// Get a user's playlists
let spotifyApi = new SpotifyWebApi()
let userplaylists = spotifyApi.getUserPlaylists(Meteor.user().profile.id,function(err,data){
if(err){
console.log("Retrieval error ", err)
}
else{
console.log("Success, your playlist ", data.body)
}
})
return userplaylists
}//end getUserPlaylists
So although I can see and access the data, I am unable to point to the track href url without getting a 401 error?

Related

Unable to add chrome-extension "url" to firebase whitelisted domains

I've been loosely following the boilerplate in quickstart-js. I don't want to rely on Chrome's identify provider but rather want users to be able to sign in to my extension with their Google login using a popup so I haven't gone through the song and dance of requesting identity permissions in my manifest.json. My file is as follows:
{
"manifest_version": 2,
"name": "Firebase Auth in Chrome Extension Sample",
"description": "This sample shows how to authorize Firebase in a Chrome extension using a Google account.",
"version": "2.1",
"icons": {
"128": "firebase.png"
},
"browser_action": {
"default_icon": "firebase.png",
"default_popup": "credentials.html"
},
"background": {
"page": "background.html"
},
"content_security_policy":"script-src 'self' https://apis.google.com https://www.gstatic.com/ https://*.firebaseio.com https://www.googleapis.com; object-src 'self'"
}
I have baseline code that is similar to what's in quickstart-js. The relevant portion in my credentials.js is here:
/**
* Start the auth flow and authorizes to Firebase.
*/
async function startAuth() {
await firebase.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION);
const provider = new firebase.auth.GoogleAuthProvider();
const res = await firebase.auth().signInWithPopup(provider);
}
// Starts the sign-in process.
function startSignIn() {
document.getElementById('quickstart-button').disabled = true;
if (firebase.auth().currentUser) {
firebase.auth().signOut();
} else {
startAuth();
}
}
window.onload = function() {
initApp();
};
This seems like it should work but constantly receive the following message:
Uncaught (in promise) Error: This chrome extension ID (chrome-extension://cckmbfklaloiadcphibealkhpncehpng) is not authorized to run this operation. Add it to the OAuth redirect domains list in the Firebase console -> Auth section -> Sign in method tab.
According to the official docs, I should be able to whitelist my Chrome extension's ID in the Firebase control panel. I'm repeatedly given a success message but the extension "url" doesn't show up in my list of Authorized Domains and I keep getting the error message.
Is there somewhere else I need to add the Chrome Extension url?
This seems to have just been a regression. I reached out to Firebase support, got an answer a few days later, but by that point the bug was fixed.

Firebase.auth error with 400 bad request

I found a strange error while I developing system using Firebase with service url contains user data.
User data is below.
{
"uid": "kt9Hcp2FbYbBvvIeSHHa1RbvHcv2",
"displayName": "Anonymous 901",
"photoURL": null,
"email": null,
"emailVerified": false,
"identifierNumber": null,
"isAnonymous": true,
"providerData": [
],
"apiKey": "MyApiKeyString",
"appName": "MyAppName",
"authDomain": "my.auth.domain",
"stsTokenManager": {
"apiKey": "MyApiKeyString",
"refreshToken": "refreshTokenString",
"accessToken": "accessTokenString",
"expirationTime": 1532451863076
},
"redirectEventId": null
}
I encode the above anonymous user data and include it in the service url.
( http://myserviceurl?userdata=encodedUserData )
Inside the system receives that url, firebase creates a user object with that user data contained in the url.
The purpose of this url is to use specific user's information in any browser.
However, when I call that service url, sometimes system creates user object well, sometimes got error -
400 Bad request errors with
https://www.googleapis.com/identitytoolkit/v3/relyingparty/setAccountInfo?key=MyApiKeyString
And error data is below,
{
"error": {
"code": 400,
"message": "TOKEN_EXPIRED",
"errors": [
{
"message": "TOKEN_EXPIRED",
"domain": "global",
"reason": "invalid"
}
]
}
}
Few hours later it works well, I changed nothing though.
I could not find the exact error point, but I suspect error occurs while observing authentication state or before this step.
Here is code snipets
#bind
private makeUserLoadingPromise(): Promise<void> {
let unSubscribe: () => void;
return new Promise<void>((resolve, _reject) => {
const onInitialized = this.makeOnInitializedAuthStateChanged(resolve);
unSubscribe = this.auth.onAuthStateChanged(onInitialized);
}).then(() => {
unSubscribe();
this.auth.onAuthStateChanged(this.onAuthStateChanged);
});
}
#bind
private makeOnInitializedAuthStateChanged(resolve: () => void) {
return (user: firebase.User | null) => {
this.user = user;
resolve();
};
}
#bind
private onAuthStateChanged(user: firebase.User | null) {
this.user = user;
}
Or maybe it relates with expirationTime?
I couldn't find any hints about this situation.
Any advice would be appreciated.
It is not clear what you are doing, but it appears that you are using the API incorrectly and insecurely. The plain user object contains a refresh token that is indefinite. Passing it around via URL is a really bad idea.
First don't rely on internal implementations, it is subject to change.
To get the user's information on your backend, the right way to do it, is to get the user's ID token using officially supported API, eg user.getIdToken(), then pass it to your server.
On your server, you verify it via the Firebase Admin SDK: admin.auth().verifyIdToken(idToken). Then you know this is a real authenticated user. If you need the full user info, you can then look it up using the decoded user id in the token: admin.auth().getUser(decodedIdToken.sub).

Linkedin share on company page API is not working at all.

I am using Linking JS SDK and following below example for sharing a post on my company page:
https://developer.linkedin.com/docs/company-pages
I used blow code to share post:
// Build the JSON payload containing the content to be shared
function onSuccess(response){
console.log(response);
}
function onError(){
console.log(response);
}
var payload = {
"comment": "Check out developer.linkedin.com! http://linkd.in/1FC2PyG",
"visibility": {
"code": "anyone"
}
};
var cpnyID = 2414183;
IN.API.Raw("/companies/" + cpnyID + "/shares?format=json")
.method("POST")
.body(JSON.stringify(payload))
.result(onSuccess)
.error(onError);
in response i am getting:
{
"errorCode": 0,
"message": "Internal service error",
"requestId": "TZ1QE0M3VP",
"status": 500,
"timestamp": 1526892099561
}
i have tried with different user and many different company ids, i also tried with fresh user and fresh company pages, but every time "Internal Service Error" is returned from service.
Please Help.

Hardcoded manifest start url still not found?

I am attempting to setup a WordPress Theme as a Progressive Web App. When I run Chromes Audit tool (lighthouse?) I get an uninformative error that I don't know what exactly the problem is. The error is:
Failures: Service worker does not successfully serve the manifest start_url. Unable to fetch start url via service worker
I have hardcoded my start url which is a valid url. Any suggestions on what the issue could be?
https://mywebsite.com/wp-content/themes/mytheme/web.manifest:
...
"scope": "/",
"start_url": "https://mywebsite.com",
"serviceworker": {
"src": "dist/assets/sw/service-worker.js",
"scope": "/aw/",
"update_via_cache": "none"
},
...
}
https://mywebsite.com/wp-content/themes/mytheme/dist/assets/sw/service-worker.js:
...
// The fetch handler serves responses for same-origin resources from a cache.
// If no response is found, it populates the runtime cache with the response
// from the network before returning it to the page.
self.addEventListener('fetch', event => {
// Skip cross-origin requests, like those for Google Analytics.
if (event.request.url.startsWith(self.location.origin)) {
event.respondWith(
caches.match(event.request).then(cachedResponse => {
if (cachedResponse) {
return cachedResponse;
}
return caches.open(RUNTIME).then(cache => {
return fetch(event.request).then(response => {
// Put a copy of the response in the runtime cache.
return cache.put(event.request, response.clone()).then(() => {
return response;
});
});
});
})
);
}
});
I register my SW with the following code and it outputs that it has successfully registered the SW:
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register(Vue.prototype.$ASSETS_PATH + 'sw/service-worker.js')
.then(function(registration) {
console.log('Registration successful, scope is:', registration.scope);
})
.catch(function(error) {
console.log('Service worker registration failed, error:', error);
});
}
Please change your start_url to
"start_url": "/"
It has to be a relative url. Please see the documentaion

Unknown name "view_id" error when querying google analytics reporting API

I am trying to query the Google Analytics Reporting API from a node.js application.
I think I have set up everything correctly on the google-side of things including a service account, but I must be missing a piece.
My application successfully sends usage-data to Google, I can see it come in in the realtime view. I can also query the data using the interactive API explorer.
In my node.js code I authenticate with the API at server startup like so:
var googleapis_key = require('./config/google-api-key.json');
var googleapis = require('googleapis');
var googleapis_jwtClient = new googleapis.auth.JWT(
googleapis_key.client_email,
null,
googleapis_key.private_key,
["https://www.googleapis.com/auth/analytics.readonly"],
null);
var googleapis_analyticsreporting = googleapis.analyticsreporting('v4');
googleapis_jwtClient.authorize(function(err, tokens) {
if (err) {
lStartup.error(err);
lStartup.error("Could not authenticate with google API. Analytics not available.");
} else {
lStartup.info("Successfully authenticated with google service-account.");
lStartup.debug(googleapis_jwtClient.credentials);
}
});
(where lStartup is a log4js logger). I get a positive response back from Google, err is not set and the credentials logged to the console look convincing.
Then later when the relevant client request comes in my server tries to ask google for the data:
var reportingrequests = {
"reportRequests": [
{
"viewID": "138122972",
"dateRanges": [{"startDate": "7daysAgo", "endDate": "yesterday"}],
"metrics": [{"expression": "ga:users"}]
}
]
};
logger.debug(JSON.stringify(reportingrequests));
googleapis_analyticsreporting.reports.batchGet(
{
"resource": reportingrequests,
"auth": googleapis_jwtClient,
},
function(err, response) {
if (err) {
// Failure. Log and report to the client.
console.error("Could not query the Google Analytics reporting API");
console.error(err);
res.writeHead(500, "Internal server error. (Google analytics:" + err + ")");
res.end(JSON.stringify(err));
} else {
// Success, just serve googles result to the client.
res.end(JSON.stringify(response));
}
}
);
The response is an error
[ { message: 'Invalid JSON payload received. Unknown name "view_id" at \'report_requests[0]\': Cannot find field.',
domain: 'global',
reason: 'badRequest' } ] }
What is it trying to tell me here? I do not have properties named view_id or report_requests in my JSON. Although they look suspiciously like mine de-camelcased.
I hate self-answering, but I love solutions!
"viewID": "138122972",
should be
"viewId": "138122972",
Note the lowercase "d".
Ironically the clue to this is in the camelCase to snake_case-conversion. If the parameter name was "viewID" it would propably have been snake_cased to "view_i_d", which is not what is in the error message.
I feel stupid, but also happy to be able to go on.

Resources