Flutter qraphQl issue with setting requesting data from body of api - flutter

I am trying to connect to an graphQl api that uses the token as the password in the Basic auth section of the header. I have tried using flutter_graphql but as I only get the token back after the user logs in. I have managed to get logged in using:
String username = "";
String password = token;
String basicAuth = 'Basic' + base64Encode(utf8.encode("$username:$password"));
String projects = "query Projects{Projects{id name}}";
Uri newUri = Uri.parse("$link");
var newResponse = await http.post(newUri, headers: {
"Authorization": basicAuth,
"Content-Type": "application/graphql"
}, body: //I need to get projects here.
);
var newNonJsonData = newResponse.body;
group("Testing the graph ql data after logging in: ", () {
test("Logged in", () {
expect(newResponse.statusCode, 200);
});
test("getting the data from the api", () {
print("non json return:" + newNonJsonData);
});
});
I have tried to set the body as
jsonEncode({
'query' : prjects
})
but the moment I request the data it asks to log in.
Please could someone help!!!

Related

When making a request to the Vision API Product Search an error occurs "message": "The request is missing a valid API key."

When I register a service account for the Vision API Product Search there's a json file downloaded into my desktop that has the private key. However, when making a request into this api there's no place to send that JSON. I'll show you the documentation and my code.
I didn't understand also what is the curl request and how to send it using the http post request.
And This is my code:
Future<void> uploadProductSet() async {
var projectId = 'estoOne';
var locationId = 'europe-west1';
var url = 'https://vision.googleapis.com/v1/projects/$projectId/locations/$locationId/productSets';
final responseOne = await http
.post(Uri.parse(url),
body: json.encode({
'displayName': 'Product-Set-One',
}))
.catchError((error) {
throw error;
});
print(resoinseOne.body);
}
You have to send your access token with the Authorization header.
The API seems to use the Bearer authentication method.
So set the following header in your http request: Bearer $authToken
You should get the auth-token from the credentials file you've downloaded
So your code should look something like this: (untested)
await http.post(Uri.parse(url),
headers: { 'Authorization': 'Bearer $authToken' },
body: json.encode({
'displayName': 'Product-Set-One',
})).catchError((error) {
throw error
})

Google Storage REST get with axios

I want to get a list of images in a bucket using REST and axios.
ref: https://cloud.google.com/storage/docs/listing-objects#list-objects-json
The documentation gives this curl request
curl -X GET -H "Authorization: Bearer OAUTH2_TOKEN" \
"https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/o"
reqConfig: this is a token I use in my REST firestore queries to authenticate the user. I'm using that same token for here. I'm guessing it's the problem but not sure how to fix it.
My result is consistently 404 for a bucket path that I know exists, using the URL from their docs. I should be getting a json list of the files in the bucket.
Error: Request failed with status code 404
Where am I going wrong?
export async function getCompanyStorage(context, apikey, companyId) {
const url = `https://storage.googleapis.com/storage/v1/b/uploads/${companyId}/o?key=${apikey}`;
const cookies = nookies.get(context);
const reqConfig = {
headers: new Headers({
Authorization: "Bearer " + cookies.token,
"Content-Type": "application/json",
}),
};
const result = axios
.get(url, { headers: { Authorization: `Bearer ${reqConfig}` } })
.then((res) => {
return res.data;
})
.catch((error) => {
console.error("error using axios", error);
});
}
Edit: a path to a bucket in the firebase console looks like this
gs://projectname.appspot.com/uploads/WhmDZyQdLVk7n0qR7aTg
I suggest reviewing the documentation you linked to. In particular:
OAUTH2_TOKEN is the access token you generated in Step 1.
BUCKET_NAME is the name of the bucket whose objects you want to list. For example, my-bucket.
You can use a prefix=PREFIX query string parameter to limit results to
objects that have the specified prefix.
Your URL does not contain the name of the bucket as required by the URL pattern. Use the unique name of the bucket where you see "BUCKET_NAME". It looks like, given your example, that it would be "projectname.appspot.com". BUCKET_NAME is not the path of the object within that bucket. If you want to list files under the "uploads" prefix, then you would use the prefix query string parameter to specify that, as documented in the last line of the quoted text.
You can use this function to create Get request with axios for Google Cloud Storage
export const UploadVideo = async (form_data, file, signedurl, asset_uuid) => {
let resultState = { state: '', data: {} };
console.log(signedurl)
/*
const xhr = new XMLHttpRequest();
xhr.open("PUT", signedurl);
xhr.setRequestHeader('Content-Type', "application/octet-stream");
xhr.send(file);
*/
let config = {
headers: {
'Content-Type': 'application/octet-stream',
},
};
await axios.get(signedurl, file, config).then(function (response) {
resultState.state = 'success';
}).catch(function (error) {
resultState.state = 'error';
resultState.data.message = error.message;
window.toastr.error(error.message);
console.log(error)
})
return resultState;
}

GraphQL query to GitHub failing with HTTP 422 Unprocessable Entity

I am currently working on a simple GitHub GraphQL client in NodeJS.
Given that GitHub GraphQL API is accessible only with an access token, I set up an OAuth2 request to grab the access token and then tried to fire a simple GraphQL query.
OAuth2 flow gives me the token, but when I send the query, I get HTTP 422.
Here below simplified snippets from my own code:
Prepare the URL to display on UI side, to let user click it and perform login with GitHub
getGitHubAuthenticationURL(): string {
const searchParams = new URLSearchParams({
client_id,
state,
login,
scope,
});
return `https://github.com/login/oauth/authorize?${searchParams}`;
}
My ExpressJs server listening to GitHub OAuth2 responses
httpServer.get("/from-github/oauth-callback", async (req, res) => {
const {
query: { code, state },
} = req;
const accessToken = await requestGitHubAccessToken(code as string);
[...]
});
Requesting access token
async requestToken(code: string): Promise<string> {
const { data } = await axios.post(
"https://github.com/login/oauth/access_token",
{
client_id,
client_secret,
code
},
{
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
}
);
return data.access_token;
}
Firing simple graphql query
const data = await axios.post(
"https://graphql.github.com/graphql/proxy",
{ query: "{ viewer { login } }"},
{
headers: {
Authorization: `Bearer ${accessToken}`,
"Content-Type": "application/json",
},
}
);
Do you guys have any clue?
Perhaps I am doing something wrong with the OAuth2 flow? As in most of the examples I found on the web, a personal token is used for this purpose, generated on GitHub, but I would like to use OAuth2 instead.
Thanks in advance for any help, I really appreciate it!
EDIT
I changed the query from { query: "query { viewer { login } }"} to { query: "{ viewer { login } }"}, nonetheless, the issue is still present.
I finally found the solution:
Change the URL from https://graphql.github.com/graphql/proxy to https://api.github.com/graphql, see here
Add the following HTTP headers
"Content-Type": "application/json"
"Content-Length"
"User-Agent"
Hope this will help others out there.

How to pass basic authentication in flutter?

In my flutter app I would like to implement basic authentication. The project is like user need to login to the app, after the login they have to give a test. After successful login using Django knox authentication(a token is generated for login) when the Test page comes, Basic authentication need to implement.
Here is the following code snippet.
import 'package:http/http.dart' as http;
import 'dart:convert';
Future TestAPI(String question1, String question2, String question3, String question4) async{
String url = 'https://someapi.com/api/test/';
String username = "myusername";
String password = "mypassword";
String basicAuth =
'Basic ' + base64Encode(utf8.encode('$username:$password'));
var response = await http.post(url,
headers: {
"Content-type": "application/json",
"Authorization": basicAuth
},
body: jsonEncode(
{
"question1":question1,
"question2":question2,
"question3":question3,
"question4":question4,
}
)
);
var convertedDataToJson = json.decode(response.body);
return convertedDataToJson;
I want to use dynamic username and password. How can I implement the logic??
I have gone through this logic but this is not what I am looking for. Can anyone help to solve this problem?

Twilio IP Messaging user not found

I'm trying to add a users identity to a channel using the REST API using instructions here: https://www.twilio.com/docs/api/ip-messaging/rest/members#action-create
I'm posting to the /Channels/channelId/Members endpoint - I'm certain my request is structured correctly.
I get an error back from Twilio IP Messaging saying:
{"code": 50200, "message": "User not found", "more_info": "https://www.twilio.com/docs/errors/50200", "status": 400}
My understanding was that we can provide our own identity when we want to add someone to a Channel. How can I 'register' the user (with an email) before adding them to the Channel?
EDIT - The code:
var _getRequestBaseUrl = function() {
return 'https://' +
process.env.TWILIO_ACCOUNT_SID + ':' +
process.env.TWILIO_AUTH_TOKEN + '#' +
TWILIO_BASE + 'Services/' +
process.env.TWILIO_IPM_SERVICE_SID + '/';
};
var addMemberToChannel = function(memberIdentity, channelId) {
var options = {
url: _getRequestBaseUrl() + 'Channels/' + channelId + '/Members',
method: 'POST',
headers: {
'content-type': 'application/x-www-form-urlencoded',
},
form: {
Identity: memberIdentity,
},
};
request(options, function(error, response, body) {
if (error) {
// Getting the error here
}
// do stuff with response.
});
};
addMemberToChannel('test1#example.com', <validChannelId>);
Twilio developer evangelist here.
In order to add a user to be a member of a channel, you do indeed need to register them first. Check out the documentation for creating a user in IP Messaging.
With your code you'd need a function like:
var createUser = function(memberIdentity) {
var options = {
url: _getRequestBaseUrl() + 'Users',
method:'POST',
headers: {
'content-type': 'application/x-www-form-urlencoded',
},
form: {
Identity: memberIdentity,
}
};
request(options, function(error, response, body) {
if (error) {
// User couldn't be created
}
// do stuff with user.
});
}
Could I also suggest you take a look at the Twilio helper library for Node.js. It handles the creation of URLs like you're doing for you. The code looks cleaner too, you can create a user with the helper library like this:
var accountSid = 'ACCOUNT_SID';
var authToken = 'AUTH_TOKEN';
var IpMessagingClient = require('twilio').IpMessagingClient;
var client = new IpMessagingClient(accountSid, authToken);
var service = client.services('SERVICE_SID');
service.users.create({
identity: 'IDENTITY'
}).then(function(response) {
console.log(response);
}).fail(function(error) {
console.log(error);
});
Let me know if this helps at all.