While trying to authenticate users in shopify, getting error: Field 'CustomerAccessTokenCreateInput' doesn't exist on type 'Mutation' - shopify

I am using node.js in my application, with shopify-api-node (v3.2.0), to authenticate customer login along with other features if shopify. As per shopify documentation (https://shopify.dev/docs/storefront-api/reference/mutation/customeraccesstokencreate) I am using GraphQL to access shopify API.
My code looks something like this below :-
const Shopify = require('shopify-api-node');
const shopify = new Shopify({
shopName: process.env.SHOPIFY_DOMAIN_NAME,
apiKey: process.env.SHOPIFY_API_KEY,
password: process.env.SHOPIFY_API_KEY_PASSWORD
});
const query = `mutation {
customerAccessTokenCreate (input: {
email: "user#mail.com",
password: "password123"
}
)
{
customerAccessToken {
accessToken
expiresAt
}
customerUserErrors {
code
field
message
}
}
}`;
shopify
.graphql(query)
.then((output) => {
console.log(output);
})
.catch((err) => {
console.error(err)
});
After this I am getting below error :-
Error: Field 'customerAccessTokenCreate' doesn't exist on type 'Mutation'
at got.then (/Users/admin/Documents/Code/shopify-node-app/node_modules/shopify-api-node/index.js:239:19)
at process._tickCallback (internal/process/next_tick.js:68:7)
locations: [ { line: 2, column: 5 } ],
path: [ 'mutation', 'customerAccessTokenCreate' ],
extensions:
{ code: 'undefinedField',
typeName: 'Mutation',
fieldName: 'customerAccessTokenCreate' }
Even I am getting the same thing from postman itself.
Any help would be appreciated.

There are two types of GraphQL:
the storefront GraphQL - https://shopify.dev/docs/storefront-api/reference
the admin GraphQL - https://shopify.dev/docs/admin-api/graphql/reference
While they seems similar the strorefront is much more limited but can be used on the front-end, while the admin one is more rich in method and functionality but can't be used safely on the font-end.
The documentation and the method you are trying to make is referring to the Storefront API, but the package you are using is for the Admin GraphQL API.
You can create a storefront access token via the storefrontAccessToken method if you want to make storefront request but the Admin API GraphQL allows for more customization.
So you need to make sure you are using the proper API.
If you plan to use the storefront API, you shouldn't use NodeJS and just create a private app ( from Admin -> APP -> Private App) which will provide you a Store Front Access Token (if you enable it at the bottom and select the proper scopes) that can be used directly on the front-end.
If you plan to use the Admin API, you will need to create a public app and host it, then you can use NodeJS and pass the information via a Proxy in Shopify.
Summary
You are making a request to the Storefront API, while using a library for the Admin API.

Related

Aws-amplify integration with React Native Token - unauthorized

I have configured my React Native application to use a Cognito user pool that is used for user identity management and authentication using AWS Amplify. I am using Custom Authentication for user management. I am able to register, log in and perform other user management-related tasks. I also have an API gateway and a few Lambda Functions which I want to access through my React Native app. When I sign in, I receive a JWT Token which I want to send to the API gateway to access my Lambdas, but no matter what I do I get an 'unauthorized' 403 or 401 message from my API Gateway.
My question is: How can I expose the API gateway/ Lambdas to the Cognito user pool users and Why the token generated by Cognito itself is unauthorized to access my api gateway.
P.S. - I used postman with the right Auth URL and settings, the postman token itself is authorized to access the API gateway and lambdas. (The user credentials are the same as I use with the React Native app)
I have spent a few days, any pointers in the right direction would be very helpful.
Thanks in advance.
NPN
Amplify Config:
const awsmobile = {
aws_project_region: 'us-XXXX-X',
aws_cognito_region: 'us-XXXX-X',
aws_user_pools_id: 'us-XXXX-XXXXXX',
aws_user_pools_web_client_id: 'XXXXh1i5nXXXX',
//aws_user_pools_web_client_secret: 'XXXXXoofuu0lXXXX',
oauth: {
domain: 'XXXXXXXX.us-XXXX-X.amazoncognito.com',
scope: ["email", "openid", "aws.cognito.signin.user.admin"]
},
aws_cognito_username_attributes: ['EMAIL'],
aws_cognito_social_providers: ['GOOGLE'],
aws_cognito_signup_attributes: ['XXXXX', 'XXXXX', 'EMAIL', 'XXXXXX'],
aws_cognito_mfa_configuration: 'OFF',
aws_cognito_mfa_types: [],
aws_cognito_password_protection_settings: {
passwordPolicyMinLength: 8,
passwordPolicyCharacters: ['REQUIRES_LOWERCASE', 'REQUIRES_UPPERCASE', 'REQUIRES_NUMBERS', 'REQUIRES_SYMBOLS'],
},
aws_cognito_verification_mechanisms: ['EMAIL'],
};
export default awsmobile;
import { Auth } from 'aws-amplify';
const login = async (username: string, password: string) => {
const response = await Auth.signIn(username, password);
console.log(response.data.signInUserSession.accessToken.jwtToken);
return response;
};

Strapi 4 - User pemissions plugin policy extension

I'm attempting to migrate from Strapi 3 -> 4
I've managed to restructure my folder structure to get the schema working for all my content types.
However, in v3 I had an extra policy on the user-permissions plugin the verified the users jwt token with auth0.
I took the v3 implementation from these docs.
I'm attempting to get it to apply the same logic in v4 and i'm a bit lost since the new docs don't seem fully up-to-date.
I'm adding a new policy in /src/extensions/users-permissions/strapi-server.js
Taken from the docs here
module.exports = (plugin) => {
plugin.policies["permissions"] = async (ctx) => {
let role;
console.log("IN HERE");
if (ctx.state.user) {
// request is already authenticated in a different way
return true;
}
// ... A bunch more logic
return false
}
return plugin
}
If I run yarn strapi policies:list then my 'permissions' policy is listed.
However, when trying to use that policy anywhere, I don't see my console log to see that it's being applied.
I've tried to specify that policy in the routes setup:
module.exports = {
routes: [
{
method: "GET",
path: "/addition-requests",
handler: "addition-request.find",
},
{
method: "GET",
path: "/addition-requests/:id",
handler: "addition-request.findOne",
},
{
method: "POST",
path: "/addition-requests",
config: {
policies: ["plugin::users-permissions.permissions"],
},
handler: "addition-request.create",
},
],
};
Is there anything obvious I'm missing?
And is there a way to apply a policy to every request that requires auth rather than specifying a policy on the route?
It appears from reading this comment it appears as though any request made to a Strapi endpoint that contains a Bearer token is treated like a request that requires auth.
That seems to be why the policy isn't being run as if I remove the Authorization header the policy does run. The question of how to execute a policy on an endpoint that requires auth still remains however.
It appears that the issue around being able to do custom validation on a users jwt is an issue that a few people are facing with v4 Strapi. See my topic on their forum.

Accessing secured FeatureLayer on ArcGIS online with JavaScript API

I am building a web app in a low code platform (Mendix). I am connecting the web app with ArcGIS online resources via the ArcGIS JavaScript API v4.19, which all goes pretty smoothely.
The challenge arises when I want to load specific secured ArcGIS online content via the ArcGIS JavaScript API, specifically from some FeatureLayers which are secured. I looked into the documentation and it seems the best way forward would be a so-called 'application login'. For this I want to setup an OAuth application login based on CLient ID and Client Secret. With these two I can get a valid token via AOuth and use that token to access the content by feeding the token to the IdentityManager via the JavaScript API.
This is were it goes wrong currently, I can't seem to figure out where to make it explicit on the ArcGIS online side that this specific secured FeatureLayer can be accessed via this application login, hence currently I am getting errors that the valid token and app id don't have access to the resource, being the end-point of the secured FeatureLayer.
Does anybody know how to associate a secured FeatureLayer in ArcGIS online to a application login?
EDIT 10-6-2021: Added code sample
After succesfully retrieving a valid token on the server side based on client id and client secret I use the client ID (=AppID) and token in the ArcGIS JavaScript API like below:
const token = {
server: "http://www.arcgis.com",
userId: <AppID>,
token:
<valid token retrieved via OAuth generateToken request,
ssl: true,
expires: 7200
};
IdentityManager.registerToken(token);
Only implementing this gives me an error whilst trying to access the secured feature layer:
identity-manager:not-authorized. "You are currently signed in as:
AppID. You do not have access to this resource:
https://server/someid/arcgis/rest/services/somefeatureserver/FeatureServer/0
I also read that sometimes below could be needed so added as well:
const idString = JSON.stringify(IdentityManager.toJSON());
console.debug("idString: " + idString);
IdentityManager.initialize(idString);
This resolves the error but makes a login popup appear again.
The layer is afterwards declared like below:
const layer = new FeatureLayer({
// URL to the service
url: layerObj.layerURLStatic
definitionExpression: queryDefinition,
featureReduction: clusterConfig && { type: "cluster" },
popupTemplate: {
title: "{" + inAttributeTitle + "}",
content: [
{
type: "fields", // FieldsContentElement
fieldInfos
}
],
actions: [
{
title: props.intButtonLabel,
id: btnId,
className: props.intButtonClass + intButtonIconClass,
type: "button"
}
]
},
outFields: ["*"]
});
webMap.add(layer);
Here is a snippet to generate the token and then register it with IdentityManager:
IdentityManager = require('esri/identity/IdentityManager')
function login(user, password){
var serverInfo = {
"server": "https://www.arcgis.com",
"tokenServiceUrl" : "https://www.arcgis.com/sharing/generateToken"
};
var userInfo = {
username : user,
password : password
}
IdentityManager.generateToken(serverInfo, userInfo).then(function (response){
response.server = serverInfo.server;
response.userId = user;
IdentityManager.registerToken(response);
});
}
I'm not sure how you are going to fit this in you app, but the sample should work if you paste it in your developer tools console when the app is running.
Also, it seems to me that userId property is for arcgis online username, not for appId.
As pointed out by Shaked, if you append '?token=[token_value]' int the layer URL you probably don't even need to register the token to query the layer.

Using node-spotify-web-api to grant user access and fetch data

So I'm new to using OAuth and I honestly got quite lost trying to make this work. I looked up the documentation for Spotify's Authorization code and also found a wrapper for node which I used.
I want to be able to log in a user through spotify and from there do API calls to the Spotify API.
Looking through an example, I ended up with this code for the /callback route which is hit after the user is granted access and Spotify Accounts services redirects you there:
app.get('/callback', (req, res) => {
const { code, state } = req.query;
const storedState = req.cookies ? req.cookies[STATE_KEY] : null;
if (state === null || state !== storedState) {
res.redirect('/#/error/state mismatch');
} else {
res.clearCookie(STATE_KEY);
spotifyApi.authorizationCodeGrant(code).then(data => {
const { expires_in, access_token, refresh_token } = data.body;
// Set the access token on the API object to use it in later calls
spotifyApi.setAccessToken(access_token);
spotifyApi.setRefreshToken(refresh_token);
// use the access token to access the Spotify Web API
spotifyApi.getMe().then(({ body }) => {
console.log(body);
});
res.redirect(`/#/user/${access_token}/${refresh_token}`);
}).catch(err => {
res.redirect('/#/error/invalid token');
});
}
});
So above, at the end of the request the token is passed to the browser to make requests from there: res.redirect('/#/user/${access_token}/${refresh_token}');
What if insted of redirecting there, I want to redirect a user to a form where he can search for artists. Do I need so somehow pass the token around the params at all time? How would I redirect a user there? I tried simply rendering a new page and passing params there but it didn't work.
you could store the tokens in a variety of places, including the query parameters or cookies - but I'd recommend using localstorage. When your frontend loads the /#/user/${access_token}/${refresh_token} route, you could grab the values and store them in localstorage (e.g. localstorage.set('accessToken', accessToken)) and retrieve them later when you need to make calls to the API.

Access to Calendar API return 401 Unauthorized

I'm new to office 365 and having problem with accessing rest api.
I'm trying to test the rest api of Calendar and Mail API, so I decided to use Postman. However, to test those APIs, I need an access token in Authorization header. To figure out how to get a token, I decided to get the sample project here , configure, run and sign in on this local site to get the token cached in local storage and use that token for further requests in Postman. However, all requests I tested returned '401 unauthorized request'.
What I did:
Register a new app on Azure ADD associated with O365 account
Add full app permissions and delegated permissions.
Update 'oauth2AllowImplicitFlow' to true in manifest file.
Clone sample project
In app.js, I change the alter the content of config function as following
function config($routeProvider, $httpProvider, adalAuthenticationServiceProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/home.html',
controller: 'HomeController',
controllerAs: 'home',
requireADLogin: true
})
.otherwise({
redirectTo: '/'
});
// The endpoints here are resources for ADAL to get tokens for.
var endpoints = {
'https://outlook.office365.com': 'https://outlook.office365.com'
};
// Initialize the ADAL provider with your tenant name and clientID (found in the Azure Management Portal).
adalAuthenticationServiceProvider.init(
{
tenant: 'mytenantname.onmicrosoft.com',
clientId: '<my cliend Id>',
endpoints: endpoints,
cacheLocation: 'localStorage'
},
$httpProvider
);
};
Then I ran the app, it sign me in just fine and I can also get the token, but that token is also unauthorized to request.
I decoded the token and saw the value of 'aud', it didn't return "https://outlook.office365.com/". In this url, the author said that "This should be "https://outlook.office365.com/" for the Mail, Calendar, or Contacts APIs"
So what did I miss ?
How you call the Office 365 API in AngularJS?
When signing the user in, you will only get the id_token to authenticate the user.
The aud of id_token is the tenant id (GUID).
To call the Office 365 API, you need to use AugularJS http request.
Here is a sample of sending email using Microsoft Graph API in AngularJS:
// Build the HTTP request to send an email.
var request = {
method: 'POST',
url: 'https://graph.microsoft.com/v1.0/me/microsoft.graph.sendmail',
data: email
};
// Execute the HTTP request.
$http(request)
.then(function (response) {
$log.debug('HTTP request to Microsoft Graph API returned successfully.', response);
response.status === 202 ? vm.requestSuccess = true : vm.requestSuccess = false;
vm.requestFinished = true;
}, function (error) {
$log.error('HTTP request to Microsoft Graph API failed.');
vm.requestSuccess= false;
vm.requestFinished = true;
});
Before calling the API, ADAL.js will acquire another token - access token which you can used to send the email.
UPDATE#1
I also downloaded the sample you mentioned. To run this sample, please ensure you have the Exchange Online > Read and writer user mail Permission assigned in your application.