Amplify Cognito Admin Query listUsersInGroup not working - amazon-cognito

I am working with AWS Amplify, specifically with Auth; I am trying to get the listUsersInGroup from Cognito pool using the next function in React:
import { Auth, API } from 'aws-amplify';
const listUsersInGroup = async (group) => {
let apiName = 'AdminQueries';
let path = '/listUsersInGroup';
let myInit = {
body: {
"groupname": group
},
headers: {
'Content-Type' : 'application/json',
Authorization: `${(await Auth.currentSession()).getAccessToken().getJwtToken()}`
}
};
const supervisorGet = await API.get(apiName, path, myInit);
}
But the API response is having code 403 and the response brings the message: {"message":"groupname is required"}
I made tests with other HTTP methods like listUsers, listGroups, listGroupsForUser and works correctly.
Can anyone help on this issue?

I found the example below in the Amplify documenation for admin actions.
It looks like the myInit object you are making is using body, but the example has queryStringParameters. That's why it's not finding the groupname key.
let nextToken;
async function listEditors(limit){
let apiName = 'AdminQueries';
let path = '/listUsersInGroup';
let myInit = {
queryStringParameters: {
"groupname": "Editors",
"limit": limit,
"token": nextToken
},
headers: {
'Content-Type' : 'application/json',
Authorization: `${(await Auth.currentSession()).getAccessToken().getJwtToken()}`
}
}
const { NextToken, ...rest } = await API.get(apiName, path, myInit);
nextToken = NextToken;
return rest;
}

Related

ReactNative: uploading image file to server using Axios is not working

I am building a mobile application using ReactNative. My app needs to upload image file to the server. I am using Axios for that. But the file is always empty on the server-side.
This is my code.
const makeMultipartFormDataRequest = async ({
path,
data = null,
headers = null
}) => {
let accessToken = await getAccessToken();
if (accessToken) {
if (headers == null) {
headers = {
'Authorization': `Bearer ${accessToken}`
}
} else {
headers.Authorization = `Bearer ${accessToken}`;
}
}
let formData = new FormData();
if (data) {
for (let prop in data) {
let field = null;
if (typeof data[prop] == "object" && data[prop]?.mime) {
field = {
uri: data[prop].uri,
name: data[prop].name,
type: data[prop].mime
}
} else {
field = data[prop];
}
// here image file is added proof_file field
formData.append(prop, field);
}
}
let url = config.apiEndpoint + path;
return axios.post(url, formData, {
headers: headers
});
}
As you see in the code, I put a comment where I put the file into the request. When I log the value in the console, I got this.
{"name": "IMG_0003.JPG", "type": "image/jpeg", "uri": "/Users/waihein/Library/Developer/CoreSimulator/Devices/ED2E89F7-F8C9-498E-9B80-41E13814A480/data/Containers/Data/Application/6AEBDAD9-A84C-4B33-95E5-0180F09B1AD5/tmp/react-native-image-crop-picker/E3B07A1B-B79D-43A0-A649-E05F8500783B.jpg"}
But the file is never sent in the request. What is wrong with my code and how can I fix it?
As you are sending form data you should specify that in the content type. Something like this,
headers: { "Content-Type": "multipart/form-data" }

Getting "Request had insufficient authentication scopes." 403 error code while importing contact from Gmail using ionic 5 & Angular 11

I am using ionic 5 and Angular 11. I want to import contacts from Gmail and display it in a ion-list.
To get the access token I am using Google-plus plugin .Below is my code to get the access token. After getting access token I am using https://developers.google.com/people/api/rest/v1/people.connections/list API to get the contacts name, phonenumber and emailAddresses.
import { GooglePlus } from '#ionic-native/google-plus/ngx';
import { HttpClient, HttpHeaders } from '#angular/common/http';
constructor(private googlePlus: GooglePlus, private http: HttpClient) { }
getContactFromGmail() {
const param = {
'scopes': 'https://www.googleapis.com/auth/contacts.readonly',
'webClientId': My webClientId,
'offline': true
};
this.googlePlus.login({ param })
.then(res => {
console.log(res);
if (res) {
let accessToken = res.accessToken;
const httpOptions = {
headers: new HttpHeaders({
'Accept': 'application/json',
'Authorization': `Bearer ${accessToken}`
})
};
var url = 'https://people.googleapis.com/v1/people/me/connections?personFields=names,emailAddresses,phoneNumbers&key=My_API_KEY'
console.log(url)
this.http.get(url, httpOptions);
}
}).catch(err => {
console.error(err)
}
}
But this is giving me 403 error.
{
"error": {
"code": 403,
"message": "Request had insufficient authentication scopes.",
"status": "PERMISSION_DENIED"
}
}
Can anybody please help me how to solve this.

React Native: Ajax error with RxJS on simple post request

I am trying to perform a simple post request in React Native with a module that I also use for my website.
I have an api.ts file where the following is defined:
import { ajax } from 'rxjs/observable/dom/ajax';
import { AjaxRequest } from 'rxjs/observable/dom/AjaxObservable';
const ApiClient = {
loginUser: (email: string, password: string) => {
let requestBody = {email, password};
let url = `${dotenv.REACT_APP_API_URL}/api/users/login`;
return createRequestOptions(url, HttpOptions.POST, requestBody);
}
}
The request options method is as follows:
const createRequestOptions = (url: string, method: string, requestBody?: object) => {
let requestOptions: AjaxRequest = {
method: method,
url: url,
crossDomain: true,
responseType: 'json',
headers: {
'Content-Type': 'application/json',
}
};
if ((method === HttpOptions.POST || method === HttpOptions.PUT) && requestBody) {
requestOptions.body = requestBody;
}
console.log(requestOptions);
return ajax(requestOptions);
};
The output of the requestOptions is as follows:
Object {
"body": Object {
"email": "myemail#gmail.com",
"password": "mypassword",
},
"crossDomain": true,
"headers": Object {
"Content-Type": "application/json",
},
"method": "POST",
"responseType": "json",
"url": "http://localhost:3001/api/users/login",
}
Finally in my epic I have the following:
const authLoginEpic: Epic = (action$, store) =>
action$.pipe(
ofType(ActionTypes.AUTH_LOGIN_REQUEST),
mergeMap((action: AuthLoginRequest) =>
ApiClient.loginUser(action.payload.username, action.payload.password).pipe(
map((res: any) => {
return AuthLoginReceive.create({response: res.response, email: action.payload.username});
}),
catchError((err) => {
console.log(JSON.stringify(err));
For some reason the catchError is triggered and I have no idea why this may be. The output of the log is:
{"message":"ajax error","name":"AjaxError","xhr":{"UNSENT":0,"OPENED":1,"HEADERS_RECEIVED":2,"LOADING":3,"DONE":4,"readyState":4,"status":0,"timeout":0,"withCredentials":false,"upload":{},"_aborted":false,"_hasError":true,"_method":"POST","_response":"","_url":"http://localhost:3001/api/users/login","_timedOut":false,"_trackingName":"unknown","_incrementalEvents":false,"_requestId":null,"_cachedResponse":null,"_headers":{"content-type":"application/json"},"_responseType":"json","_sent":true,"_lowerCaseResponseHeaders":{},"_subscriptions":[]},"request":{"async":true,"crossDomain":true,"withCredentials":false,"headers":{"Content-Type":"application/json"},"method":"POST","responseType":"json","timeout":0,"url":"http://localhost:3001/api/users/login","body":"{\"email\":\"mymail#gmail.com\",\"password\":\"mypassword\"}"},"status":0,"responseType":"json","response":null}
The Ajax error is not very descriptive. Does anyone what I may be doing wrong?
It seems that this happened due to the simple fact that the api address was set to localhost or 127.0.0.1
Ensure to have set this to your local network IP address!

Create a new script tag (Shopify) Error: Invalid URI "/"

Based on this tutorial, I tried the below code. I'm trying to add a new script to the web page.
request.post(accessTokenRequestUrl, {
json: accessTokenPayload
})
.then((accessTokenResponse) => {
const accessToken = accessTokenResponse.access_token;
// DONE: Use access token to make API call to 'shop' endpoint
const shopRequestUrl = 'https://' + shop + '/admin/shop.json';
const shopRequestHeaders = {
'X-Shopify-Access-Token': accessToken,
'Content-Type': 'application/json'
};
const createScriptTagUrl = 'https://' + shop + '/admin/script_tags.json';
const scriptTagBody = {
"script_tag": {
"event": "onload",
"src": "https:\/\/djavaskripped.org\/fancy.js"
}
}
request.get(shopRequestUrl, {
headers: shopRequestHeaders
})
.then((shopResponse) => {
res.status(200).end(shopResponse);
})
.catch((error) => {
res.status(error.statusCode).send(error.error.error_description);
});
request.post(createScriptTagUrl, {
json: scriptTagBody
}, {
headers: shopRequestHeaders
})
.then((scriptResponse) => {
res.status(200).end(scriptResponse);
})
.catch((error) => {
res.status(error.statusCode).send(error.error.error_description);
});
However, I get RequestError: Error: Invalid URI "/"
Am I missing anything? Or is the src value is having some problem?
I think you are using get method to create the script tag instead of post. Please use post method and also remove \ from the src.
Thanks
Fixed using the below code. Basically, the request body was supposed to be sent as JSON.
request.post({
url: createScriptTagUrl,
body: scriptTagBody,
headers: shopRequestHeaders,
json: true
}, function(error, response, body) {
if (!error) {
console.log(body)
}
});

Twitch title change via api

I have a little chat bot for twitch and I want to make now a function where you can change the stream title.
My function looks at the moment so:
public changeTitle = (new_title: string, callback: any): void => {
let t = this;
let request = require('request');
request.get("https://api.twitch.tv/kraken/channels/" + this.settings.current_channel + "?client_id="+this.settings.clientId, { json: true }, function (err, res) {
if (!err && res.statusCode === 200) {
let current_title = res.body.status;
console.log(current_title);
let request2 = require('request');
let options = {
url: "https://api.twitch.tv/kraken/channels/"+t.settings.current_channel+"?channel[status]="+current_title+new_title,
headers: {
"Authorization": "OAuth "+t.settings.clientId,
"Accept": "application/vnd.twitchtv.v2+json"
}
};
request2.put(options, (error: Error, response: any, body: any): void => {
console.log("Title changed?");
});
}
});
};
in the console.log(current_title) I can see the current stream title.
After the console.log("Title changed?") nothing happend.
I get the error 410 GONE. So my way to change the title is no longer supported.
Can someone show me how to change the title?
Thanks in advance :)
This looks to be covered by Update Channel
Specifically, rather than channel[status] use just status as a query param.
let options = {
url: "https://api.twitch.tv/kraken/channels/"+t.settings.current_channel+"?status="+new_title,
headers: {
"Authorization": "OAuth "+t.settings.clientId,
"Accept": "application/vnd.twitchtv.v2+json"
}
You'll also need the channel_editor scope in order to use this on a given channel.