Facebook js api - "unsupported get request" error - facebook-javascript-sdk

I'm trying to get some (I think allowed) information in my app. I have an access token that has the following info:
App ID: <my app id> : iHOUSEListingPoster - Test 001
Type: User
App-Scoped User ID: <user id> : Joe Webb
Valid: True
Scopes: email, pages_show_list, pages_read_engagement, pages_manage_posts, public_profile
I'm trying this:
FB.api( "/me",
"GET",
{fields: 'name'},
function(get_fb_info_response) {
console.log("Here: ", get_fb_info_response
});
And getting this error:
"Unsupported get request. Object with ID 'me' does not exist, cannot be loaded due to missing permissions, or does not support this operation"
I have tried with both "/me" and "/me/". And while I want name, picture and email, I tried limiting it to just name, and still. What am I missing here?

Try this:
FB.api('/me?fields=name', function(response) {
console.log('me', response);
});
I'm not sure if api function from FB does have this signature you're using.
Edit
After searching at Facebook docs, found that the signature you were using is valid as well. Then, I went to do some tests here. And I was able to reproduce the same error you have mentioned when calling the function like this:
FB.api("/<123>/", "GET", { fields: 'name' }, function(response) {
console.log('response', response);
});
To fix it, you need to remove < and >, for example:
FB.api("/123/", "GET", { fields: 'name' }, function(response) {
console.log('response', response);
});
Calling /me and /me/ endpoint returned no error in my test.
In this screenshot you can see the tests I have run directly at my browser's console.

Ok, I finally figured out what the problem is/was here (sheepish face). We have a couple of Facebook accounts here at the company. One is the container for my app and it's test app, the other is a more general company account. I was logged into the general company account. When I tried my app, it grabbed some random app from that account, which wasn't the app that matched the access token (which I think is possible wrong on Facebook's part), therefore this error was thrown.
Once I logged into the correct Facebook account, all works as expected.

Related

AWS Cognito Respond to New_Password_Required challenge returns "Cannot modify an already provided email"

An app that has been working successfully for a couple years has started throwing the following error whenever trying to respond to the NEW_PASSWORD_REQUIRED challenge with AWS Cognito:
{"__type":"NotAuthorizedException","message":"Cannot modify an already provided email"}
I'm sending the below, which all seems to match the docs.
{
"ChallengeName": "NEW_PASSWORD_REQUIRED",
"ClientId": <client_id>,
"ChallengeResponses": {
"userAttributes.email": "test#example.com",
"NEW_PASSWORD": "testP#55w0rd",
"USERNAME": "testfake"
},
"Session": <session_id>
}
Nothing has changed on the front end; is there a configuration change we might have done on the Cognito/AWS side that might cause this error?
I started getting the same error recently. I'm following Use case 23 Authenticate a user and set new password for a user. After some investigation, I found that it is the email attribute in userAttributes that's causing completeNewPasswordChallenge to throw the error. The userAttributes I get from authenticateUser used to be an empty object {}, but it now looks like this:
{ email_verified: 'true', email: 'test#example.com' }
I had to delete the email attribute (as well as the email_verified attribute as shown in the example code in Use case 23) before using the userAttribute for a completeNewPasswordChallenge. So my code is now like this:
cognitoUser.authenticateUser(authenticationDetails, {
...
newPasswordRequired: function(userAttributes, requiredAttributes) {
// the api doesn't accept this field back
delete userAttributes.email_verified;
delete userAttributes.email; // <--- add this line
// store userAttributes on global variable
sessionUserAttributes = userAttributes;
}
});
// ... handle new password flow on your app
handleNewPassword(newPassword) {
cognitoUser.completeNewPasswordChallenge(newPassword, sessionUserAttributes);
}
I guess aws changed their api recently, but I haven't found any doc about this change. Even though the value of the email attribute is the same as the actual email of the user, it throws the Cannot modify an already provided email error if you include it in the request. Deleting it solves the issue.

Strapi doesn't authorize JWT

Good morning,
I've encountered a weird issue with my strapi-project.
I have a standard user model which I query for info on the user's profile page via the /users/me endpoint. This was all working fine last week but as I tried logging in this morning, the authorization appeared to not work anymore. I log my user in via this code:
....
async submitForm() {
axios.post('http://localhost:1337/auth/local', {
'identifier': this.email,
'password': this.password
})
.then((response) => {
const { jwt, user } = response.data;
window.localStorage.setItem('jwt', jwt);
window.localStorage.setItem('userData', JSON.stringify(user));
router.push('/dashboard');
})
.catch((e) => {
this.$store.commit('LOGIN_ERROR', e)
});
},
...
Which then redirects to my dashboard which queries the /users/me endpoint like so:
let token = localStorage.jwt;
axios.get(`http://localhost:1337/users/me`, {
headers: {
Authorization: `Bearer ${token}`
}
})
.then((response) => {
console.log(response.data);
})
A few days ago this was working fine, also the token variable used in the post contais the token returned from the backend after logging in. Now strapi gives me an error in the console:
[2021-10-16T07:16:52.568Z] debug GET /users/me (5 ms) 500
[2021-10-16T07:17:03.231Z] debug POST /auth/local (76 ms) 200
[2021-10-16T07:17:24.915Z] error TypeError: Cannot read property 'type' of null
at module.exports (/home/user/WebstormProjects/strapi-project/node_modules/strapi-plugin-users-permissions/config/policies/permissions.js:35:14)
at async /home/user/WebstormProjects/strapi-project/node_modules/strapi-utils/lib/policy.js:68:5
at async serve (/home/user/WebstormProjects/strapi-project/node_modules/koa-static/index.js:59:5)
at async /home/user/WebstormProjects/strapi-project/node_modules/strapi/lib/middlewares/parser/index.js:48:23
at async /home/user/WebstormProjects/strapi-project/node_modules/strapi/lib/middlewares/xss/index.js:26:9
My first guess was that maybe something with axios was wrong e.g. that the token wasn't sent correctly in the request so I tried the same thing with webstorm's http client:
POST http://localhost:1337/auth/local
Content-Type: application/json
{
"identifier": "test#test.com",
"password": "..."
}
Which returns the user and token:
"jwt": "<TOKEN>",
If I try using this token to authenticate the user, however a get a 401
GET http://localhost:1337/users/me
Authorization: "Bearer <token>"
Accept: application/json
returns
{
"statusCode": 401,
"error": "Unauthorized",
"message": "Invalid token."
}
So I tried figuring out what was going on there and after an hour I noticed that when looking at the user in the backend the user didn't have the authenticated role assigned. When I changed this manually in the backend, the request authorization works again.
So can anyone maybe tell me what is going on here? Because from my understanding, when POSTing valid credentials to /auth/local the user's role should change to Authenticated, which was working some days back.
Is there something I'm missing?
Any help would be greatly appreciated,
greetings, derelektrischemoench
Okay, so let me reply to your first part:
"Because from my understanding, when POSTing valid credentials to /auth/local the user's role should change to Authenticated"
Answer is, not really. When you send valid credentials to the auth/local, Strapi just checks the database for matching username/email and password. If a user is found, then it fetches the role assigned that user and puts all the data in ctx.state.user.role. So you could have many other roles, like Viewer, Commenter etc with each having different set of access limits.
The different roles can be created here:
http://localhost:1337/admin/settings/users-permissions/roles
So depending on the roles assigned, Strapi will just fetch and store the values in ctx.state.user.role on each request via the strapi-plugin-users-permissions plugin for your convenience, so that you can easily check which user it is and which role it has in any controller or service file using the ctx from the request to provide any additional functionality.
You can check how it does it in the following file:
node_modules/strapi-plugin-users-permissions/config/policies/permissions.js
Now coming to what could have caused it:
Well it could have been you yourself. Possibly while saving the user or viewing user details you could have removed the role from the user and saved the record.
The other possibility could be a database switch.
It can also be a Strapi version upgrade that caused, but it's highly unlikely.
You could have a update query in the your code that updates the user model, where you might have missed the role parameter. So check your code once.
Nevertheless, it can simply be solved by re-assigning the user roles via the users module.

How to fix "The OAuth client was not found" error from a Bing Ads script

We've got scripts on Bing to automatically adjust ad bids based on ad performance and client goals, which are stored in a Google spreadsheet.
We had a contractor set this up initially, and it worked. But I guess that the contractor was using a temp Google account and when it went away the bidders stopped working. Because it did work before, it's likely a configuration error on my part that's breaking it now, but the contractor pointed us to the steps I was already following to no avail (https://learn.microsoft.com/en-us/advertising/scripts/examples/authenticating-with-google-services#option2).
Stuff already tried
double checked for errant whitespace around the client ID and client secret
created new client secrets
created new client IDs
made sure that the project name, application name, and OAuth client id name were all the same
created whole new projects from scratch (configured to match the article cited above) to see if that would kick something loose
tried a different token URL (https://oauth2.googleapis.com/token) that appears in the client_secret JSON downloaded from Google
function main() {
const credentials = {
accessToken: '',
client_id: 'REDACTED.apps.googleusercontent.com', // from Google developer console
client_secret: 'REDACTED', // from Google developer console
refresh_token: 'REDACTED' // created at https://developers.google.com/oauthplayground
};
var access_token = '';
if (credentials.accessToken) {
access_token = credentials.accessToken;
}
var tokenResponse = UrlFetchApp.fetch('https://www.googleapis.com/oauth2/v4/token', { method: 'post', contentType: 'application/x-www-form-urlencoded', muteHttpExceptions: true, payload: { client_id: credentials.clientId, client_secret: credentials.clientSecret, refresh_token: credentials.refreshToken, grant_type: 'refresh_token' } });
var responseCode = tokenResponse.getResponseCode();
var responseText = tokenResponse.getContentText();
if (responseCode >= 200 && responseCode <= 299) {
access_token = JSON.parse(responseText)['access_token'];
}
throw responseText;
// use the access token to get client targets from the spreadsheet
A JSON encoded access token is the expected response, but instead, we get HTTP 400 with the message "The OAuth client was not found."
Manually creating an access token on the OAuth playground (https://developers.google.com/oauthplayground) works as a stopgap, but this should work. This has worked. :P
The fix in this case switching the Application Type on console.developers.google.com > Credentials > OAuth consent screen to Internal instead of Public.
That wasn't in the steps provided by Microsoft, and I'm not sure if that will have implications down the road, but at least we're off the manual process for now.

Using the Rally API to pull user profile

I am trying to use the Rally web service API to get some data. Code as blow. On IE it will pop out a login window, after entry login name and password, I am about to get some data. But when I use chrome, it response 401, not sure what I missing. I know there is SDK available, but due to some limitation, not able to use it. Any suggestions please?
var url = https://rally1.rallydev.com/slm/webservice/v2.0/users;
$.ajax({
url: url,
type: 'GET',
heards: { zsessionid: apiKey },
success: function(json) {
console.log(JSON.stringify(json));
}
},
error: function( req, status, err ) { console.log( 'something went wrong', status, err );
}
});
I'd love to know more about why you can't use the SDK. Anyway, in this case your config likely needs headers instead of heards to pass the api key.

Linkedin token not valid

Here is a strange thing I am fighting against.
First of all I am using this simple-linkedinphp lib to perform API calls from my php backend.
I got a user access token from our IOS app which has the following structure:
{"access_token":"lettersAndSymbols","expires_in":5183999}
I store it in a variable called $token.
Then I try to get the user's profile with this token like this:
$linkedin = new \LinkedIn($this->linkedin_config);
$linkedin->setResponseFormat($linkedin::_RESPONSE_JSON);
$linkedin->setTokenAccess(array('oauth_token' => $token["access_token"], 'oauth_token_secret' => ""));
$linkedinUserJson = $linkedin->profile("~");
Then I get the response with error:
array(5) {
["linkedin"]=>
string(358) "{
"errorCode": 0,
"message": "[unauthorized]. The token used in the OAuth request is not valid. sameLettersAndSymbols",
"requestId": "74T6SY6ML6",
"status": 401,
"timestamp": 1376043937705
}
But when I try to open an api url in a browser with the same LettersAndSymbols like https://api.linkedin.com/v1/people/~?oauth2_access_token=LettersAndSymbols, I get the correct response with user object.
How can that be? Am I doing something wrong with the API lib?
I can see a problem in this line
$linkedin->setTokenAccess(array('oauth_token' => $token["access_token"], 'oauth_token_secret' => ""));
your must provide a secret to set the token access.
I found a nice example about Linkedin Integration, wich I like to share with you, I tested and it works just fine.
How to Integrate login with LinkedIn oAuth in PHP