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

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.

Related

Amplify Cognito Admin Query listUsersInGroup not working

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;
}

Getting 405 Error when trying to add contact to my sendgrid using API

I am trying to add contacts to my sendgrid using API.
const addContactToList = async (email, listId) => {
try {
await axios.post(
`https://api.sendgrid.com/v3/marketing/contacts`,
{
list_ids: [listId],
contacts: [
{
email: email,
},
],
},
{
headers: {
Authorization: `Bearer ${SENDGRID_API_KEY}`,
'Content-Type': 'application/json',
},
}
)
console.log('Works')
} catch (error) {
console.log(error.message)
}
}
But I am getting error 405 in return. I have given this specific API key Full Permissions.
Why is the API giving 405 error?

Cookie created using express doesn't show in nextjs app

I'm using next-auth to authenticate users in a NextJS app, when authenticated the express api sets a token cookie that I want to use later for api routes protection. Now the authentication works, but the cookie doesn't get saved in the cookie storage in the browser although it does on Postman.
here's my credentials provider code
CredentialsProvider({
async authorize(credentials) {
try {
const {data} = await axios.post(`${process.env.URL}/api/v1/auth/login`, {
email: credentials.email,
password: credentials.password,
}, {
headers: {
'Content-Type': 'application/json'
}
})
if (data) {
return {
username: data.username,
email: data.email,
}
} else {
return null
}
} catch (error) {
return null
}
}
})

Shopify API returns 400 bad request when creating new custom collection

I'm trying to create a custom collection following the document. I'm getting a 400 about the request being malformed.
My code:
require('dotenv').config()
const { Shopify } = require('#shopify/shopify-api')
const client = new Shopify.Clients.Rest(
process.env.SHOPIFY_STORE,
process.env.SHOPIFY_API_SECRET_KEY
);
(async () => {
try {
const data = await client.post({
path: 'custom_collections',
body: { 'custom_collection': { 'title': 'Nike' } },
type: 'application/json',
})
} catch(err) {
console.error(JSON.stringify(err))
}
})()
And the error response from Shopify is:
{"code":400,"statusText":"Bad Request"}
Any ideas what I'm doing wrong here? My tokens are correct because I can use the same token to view collections using the https URL https://API_KEY:SECRET#SHOPIFY_STORE/admin/api/2021-07/collections.json

I can't seem to find my headers in the response from my express back-end in nativescript angular response

I can't seem to find any headers in the response from my express back-end in nativescript angular response,i previously had res.header but wasn't any different.
Express back-end :
router.post('/login', (req, res) => {
User.findOne({
email: req.body.email
})
.then((foundUser) => {
if (!foundUser) res.send('Email Or Password Is Invalid');
else {
bcrypt.compare(req.body.password, foundUser.password) //compare hashed with db string
.then((validPassword) => {
if (!validPassword) res.send('Invalid Email Or Password').status(400);
else {
const token = jwt.sign({
_userID: foundUser.userID
}, config.get('jwtPrivateKey'));
res.set({
'content-type': 'application/json',
'x-auth-token': token
}).send('Logged In').status(200);
}
});
}
}).catch((err) => {
res.send('Oops something went wrong').status(500);
});
});
Nativescript Http:
onLogin(){
console.log(this.textScrap());
this.registartion.Login(this.textScrap())
.subscribe((response) => {
console.log(response);
},(err) => {
console.log(err);
},() => {
// this.router.navigateByUrl() Navigate to homePage when ready
})
}
Then I end up with this response but no header included
{
JS: "headers": {
JS: "normalizedNames": {},
JS: "lazyUpdate": null,
JS: "headers": {}
JS: },
JS: "status": 200,
JS: "statusText": "Unknown Error",
JS: "url": null,
JS: "ok": false,
JS: "name": "HttpErrorResponse",
JS: "message": "Http failure during parsing for (unknown url)",
JS: "error": {}
JS: }
I had a similar issue in NativeScript using Angular6 (and 7), and it turned out to be the Angular HttpClient rejecting empty responses with a status code of 200 instead of 204 (no content). The log showed the same message that you receive.
Even though your server code seems to send a non-empty response on successful logins ('Logged in'), you can try to add an Interceptor in your Angular appplication
to inspect the error further.
In my case I added an Interceptor which sets the body to null in case the HttpClient encounters an error and the status code indicates a successful response:
import { Observable, of } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { Injectable } from '#angular/core';
import {
HttpInterceptor,
HttpRequest,
HttpHandler,
HttpResponse,
HttpEvent,
HttpErrorResponse
} from '#angular/common/http';
#Injectable()
export class EmptyResponseBodyErrorInterceptor implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler): Observable> {
return next.handle(req).pipe(
catchError((err: HttpErrorResponse, caught: Observable>) => {
if (err.status >= 200 && err.status &lt 300) {
const res = new HttpResponse({
body: null,
headers: err.headers,
status: err.status,
statusText: err.statusText,
url: err.url
});
return of(res);
}
throw err;
}
));
}
}
Add it to providers in your app.module.ts:
{ provide: HTTP_INTERCEPTORS, useClass: EmptyResponseBodyErrorInterceptor, multi: true },
I did not experience the same issue when running this in Chrome, Firefox or Safari, though - only in NativeScript (both Android and iOS).