Podio POST request returns unauthorized - podio

I'm working on a Podio integration as a Slack bot.
I'm starting to use it just for use for my company to test it, then I could share it with everybody.
I've used the podio-js platform with Node JS, and started locally with a "web app" by starting from this example: https://github.com/podio/podio-js/tree/master/examples/password_auth
I need to do a post request, so I maintained all the code of the example in order to log in with user and password. The original code worked, then I changed the code to make a post request, in particular I change the lines of index.js into this:
router.get('/user', function(req, res) {
podio.isAuthenticated().then(function () {
var requestData = { "title": "sample_value" };
return podio.request('POST', '/item/app/15490175', requestData);
})
.then(function(responseData) {
res.render('user', { data: responseData });
})
.catch(function () {
res.send(401);
});
});
But in the end is giving a "Unauthorized" response.
It seems like the password auth doesn't let to make POST request to add new items! Is that possible?
I've already read all the documentation but I'm not able to explain why and how I can solve this.
Regards

Related

Playwright: unable to login via API setting cookie (able to do it with Cypress)

I'm trying to implemented login via API following Playwright's guidelines but somehow nothing seems to be working.
As a comparison I've built the same in Cypress and it works out of the box:
Context:
Playwright Version: 1.30
Operating System: Mac
Node.js version: v16.19.0
Browser: Chromium
I am unable to make a simple API login that works perfectly using Cypress instead. Let me share the 2 code snippets for comparison:
Simple test case:
API request to the login end-point - Auth token is retrieved
set the auth token as a cookie
navigate to a page that is accessible only if authenticated
Code Snippet
Cypress (working fine)
const body = {
username: 'username...',
password: 'password',
rememberMe: true,
};
describe('Login via API to management console', () => {
it('Login via API to management console', () => {
cy.request({
method: 'POST',
url: loginEndPoint,
headers: {
'Content-Type': 'application/json',
},
body,
}).then((response) => {
cy.setCookie('Authorization', `Token ${response.body.data.token}`);
});
cy.visit(`/management`);
});
});
Playwright (not working)
test('Login via API', async ({ browser }) => {
const context = await browser.newContext();
const page = await context.newPage();
const loginResponse = await context.request.post(`https://${process.env.MANAGEMENT_URL}/web/api/v2.1/users/login`, {
data: {
username: process.env.MANAGEMENT_USER,
password: process.env.MANAGEMENT_PASSWORD,
rememberMe: true,
}
});
const {
data: { token },
} = await loginResponse.body().then((b) => {
return JSON.parse(b.toString());
});
expect(token).toMatch(/^[a-z0-9]{80}$/)
await context.addCookies([{ name: 'Authorization', value: `Token ${token}`, path: '/', domain: `https://${process.env.MANAGEMENT_URL}` }]);
await page.goto(`https://${process.env.MANAGEMENT_URL}/management/`);
await expect(page).toHaveURL(/management/);
});
Describe the bug
Both scripts are successful at retrieving the authentication token but somehow either I'm doing something wrong with setting the cookie in Playwright or there is an issue. I'd assume the 2 scripts should be comparable.
Furthermore: I've tried to execute login via UI using global-setup, saving the storage-state, loading it before running the test and it fails also in this case... so there is something that is not setting properly the state in this case or the cookie in the previous one.
Not entirely sure why the cookie approach wasn’t working, perhaps the https:// part should be removed from the domain?
That being said, in Playwright you shouldn’t even need to do that especially within a single test, looking at the Playwright docs on signing in via the API and related page about the request context particularly under cookie management. The associated request and browser contexts share cookies, so once you complete the login request, the browser should already have the cookie state too and be logged in, so you should be able to just remove getting the token and adding the cookie. Or you can login with the API in the global setup even, as that doc showed. Just make sure in that case to save the storage state, and specify the same file in your config.
I see you tried the global setup approach (through the UI, but you can use the API since you have it), not sure what happened there. I would say to ensure that you specified the storageState in the config; I would be curious how you loaded it as mentioned, and if you’re still having problems maybe share the code you’re using for that piece?
Hope that helps or we can troubleshoot further!

how solve 404 error in axios post request in vue?

i want send request to an api but i have 404 erro and i have nothing in network
can you help me?
my code:
loginMethod() {
const config = {
userName: "test#gmail.com",
password: "1234test",
};
return new Promise((resolve) => {
ApiService.post("api/authentication/login", config)
.then(({ data }) => {
console.log(data);
resolve(data);
})
.catch(({ response }) => {
console.log(response);
});
});
},
and ApiService function:
post(resource, params) {
console.log(params);
const headers = {
"E-Access-Key": "bb08ce8",
};
return Vue.axios.post(`${resource}`, params, { headers: headers });
},
Based only on what I can see in your code, you are not telling axios the complete URL if I'm right about it, and you didn't declare it somewhere else do this:
axios.post('yourdomain.com/api/authentication/login',params)
or
axios({
url:'yourdomain.com/api/authentication/login',
method:post,
data:{}
})
or
in your main js file or any other file that you import axios (if you are sharing an instance of it globali):
axios({baseurl:'yourdomain.com'})
and then you don't need to write the complete url everywhere and just insert the part you need like you are doing now and axios will join that address with the baseurl,I hope it helps
I guess the URL "api/authentication/login" might be wrong and the correct one would be "/api/authentication/login" that starts with /.
404 error means the resource referred by the URL does not exist. It happens when the server has deleted the resource, or you requested a wrong URL accidentally, or any wrong ways (e.g. GET vs POST)
To make sure if you were requesting to the correct URL (and to find where you're requesting actually), open Google Chrome DevTools > Network panel. You might need reload.
The url api/xxx is relatively solved from the URL currently you are at. If you were at the page http://example.com/foo/bar, the requested URL becomes http://example.com/foo/bar/api/xxx. Starting with / means root so http://example.com/api/xxx.
This answer might help to understand the URL system: https://stackoverflow.com/a/21828923/3990900
"404" means your API Endpoint is not found. You need to declare the location of your API Endpoint exactly. For example: http://localhost:8080/api/authentication/login.

Display data from Twitter API using axios

I got stuck with a Vue project. I need to display 10 tweets in a component with the hashtag "Vue", so I am trying to pull data (username, tweet, date) from Twitter API. I read the twitter dev documentation, googled for hours, but it all suggested a php or python script for handling this request. Isn't it possible with axios? I got the following code, but the server always responds 400.
Here is my sample code (the keys are mocked):
import axios from "axios";
var api_url = "https://api.twitter.com/1.1/search/tweets.json?q=from%3Atwitterdev&result_type=mixed&count=2";
var AUTH_OBJ = {
oauth_consumer_key: "CONSUMER_KEY",
oauth_nonce: "kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg",
oauth_signature: "tnnArxj06cWHq44gCs1OSKk%2FjLY%3D",
oauth_signature_method: "HMAC-SHA1",
oauth_timestamp: "1318622958",
oauth_token: "TOKEN_FROM TWITTER_DEV",
oauth_version: "1.0"
};
axios.defaults.headers.common["Authorization"] = AUTH_OBJ;
function getData() {
axios.get(api_url)
.then(function (response) {
console.log(response)
});
}
Could someone please help?

Using Cypress to Test an App That Relies on OAuth

I've inherited a Node.js web app that uses relies on OAuth. Whenever you visit a page the app ensures you've authenticated. Please note, there no Angular, React, Vue, etc here. Each page is straight up HTML.
I want to test this site using Cypress. My problem is, I'm stuck on the initial redirect from the auth provider. Cypress acknowledge OAuth is a challenge.
commands.js
Cypress.Commands.add('login', (credentials) => {
var settings = {
'clientId':'<id>',
'scope':'<scope-list>',
...
};
var body = `client_id=${settings.clientId}&scope=${settings.scope}...`;
var requestOptions = {
method: 'POST',
url: 'https://login.microsoftonline.com/...',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: body
}
cy.request(requestOptions);
});
Then, in my test, I have:
context('Home', () => {
it('Visits Successfully', () => {
cy.login();
cy.title().should('include', 'welcome');
});
});
In the test runner, I see the login POST request is occurring. I confirmed that an access token is being received using a console.log, however, my title is empty. It's like the redirect after OAuth isn't happening in Cypress. However, when I visit the site in the browser, the redirect is happening as expected.
What am I missing?
What you might be missing is confusing between the actual UI flow and the programmatic flow of doing OAuth with a 3rd party website.
What you would want to do is to complete the programmatic login and then send the required parameters to your OAuth callback URL for your app manually in the test code.
an example is given here (though it uses a different grant type it gives you an idea) https://auth0.com/blog/end-to-end-testing-with-cypress-and-auth0/#Writing-tests-using-Cypress-Login-Command
another issue on the cypress github that deals with a similar problem
https://github.com/cypress-io/cypress/issues/2085
this also might help:
https://github.com/cypress-io/cypress-example-recipes/blob/master/examples/logging-in__single-sign-on/cypress/integration/logging-in-single-sign-on-spec.js

Call API with Another Api response data in Nuxtjs

Im making a website with Nuxtjs, i want when i open any page of the website to get user information from the server using Axios, and i want to use these information to call another API's from the website.
For example: i will get the User id and Client id from the server and use them on the API URL, lets say i got User id = 5, Client id = 10
i will call another API's and use these informations
http://****/getItems?userid=5&clientid=10
Now my problem is the second API call before the first API finished so i didn't got the user informations yet.
Could you please help me with this issue, note that i want to get the user information on all pages. so if i reload the page in any page i want to get user informations.
So i call the user information API from a Layout and call the other API's from another components.
Thanks.
First you should use Axios module officially provided by Nuxt.js here, https://github.com/nuxt-community/axios-module. They have make the integration between Axios and Nuxt.js easier.
Axios uses promise so you can easily chaining method to do it. Let say you wanna get information from /get/product with data gotten from the url you mention before http://****/getItems?userid=5&clientid=10, you can easily do that like this
this.$axios.$get('/getItems?userid=5&clientid=10')
.then(data => {
// You can use your data received from first request here.
return this.$axios.$post('/get/product', {
id: data.id,
clientId: data.clientId
})
})
.then(data => {
// You can use your data received from second request here.
console.log(data)
})
Explanation
This part,
this.$axios.$get('/getItems?userid=5&clientid=10')
the axios will get the data from the url provided, when the data is received, we can use it within then() block as it accept callback as a parameter.
.then(data => {
// You can use your data received from first url here.
...
})
After that, if you wanna use your data you can easily return the axios request again with proper parameter you wanna send.
return this.$axios.$post('/get/product', {
id: data.id,
clientId: data.clientId
})
And again you can use the data received from second axios request within then() block.
.then(data => {
// You can use your data received from second request here.
console.log(data)
})
Updated
Oke, based on the clarification on the comment section below. We can return the axios promise in first action and then on the second method we can dispatch the first action,
actions: {
callFirst ({ commit }) {
return this.$axios.$get('/get/first')
.then(firstResult => {
commit('SET_FIRST', firstResult)
return firstResult
})
},
callSecond ({ dispatch, commit }) {
return dispatch('callFirst').then(firstResult => {
return this.$axios.$post(`/get/${firstResult.userId}`)
.then(secondResult => {
commit('SET_SECOND', secondResult)
return secondResult
})
})
}
}
Using that way, you just need to put the callSecond() action whereever you want get the second data. And you also don't need to put the callFirst() action on default.vue.