Strapi / Nuxt - Can't find custom route - authentication

I've used this to setup auth in strapi and nuxt:
Auth with Strapi and Nuxt
I'm currently trying to retrieve the items specific to a authenticated user (already checked out this strapi - restrict user to fetch only data related to him). To do this I created a custom route in Strapi (/api/routine/config/routes.json):
{
"method": "GET",
"path": "/routines/me",
"handler": "Routine.me",
"config": {
"policies": []
}
}
and a custom controller (/api/controllers/Routine.js):
module.exports = {
me: async (ctx) => {
const user = ctx.state.user;
if (!user) {
return ctx.badRequest(null, [{ messages: [{ id: 'No authorization header was found' }] }]);
}
const data = await strapi.services.routine.find({user:user.id});
if(!data){
return ctx.notFound();
}
ctx.send(data);
},
};
I already gave permission through Strapi admin for authenticated users to access 'me'. When I hit the endpoint from Nuxt:
const routines = await axios.get(http://localhost:1337/routines/me)
I get this error:
GET http://localhost:1337/routines/me 404 (Not Found)
Why is the custom route not found? Am I using the wrong endpoint?

Maybe you have already solved it, but it seems like you forget to send the authentication header with the request.
const routines = await axios.get(
'http://localhost:1337/routines/me', {
headers: {
Authorization:
this.$auth.getToken('local'),
},
}

It was a fault in my Strapi routes config. Answer was provided through the amazingly helpful Strapi forums:
403 forbidden when calling custom controller from Nuxt
Here is the problem:
{
"method": "GET",
"path": "/routines/:id",
"handler": "routine.findOne",
"config": {
"policies": []
}
},
{
"method": "GET",
"path": "/routines/me",
"handler": "routine.me",
"config": {
"policies": []
}
So basically you are hitting the first route right now and it assumes that
me is actually an :id. Koa is making the verifications with regex so in this case it takes the first matched route. Move the route with /me above that one with /:id

Related

Shopify Storefront API error Delegate Access Token

I've made progress (I think) with getting delegate access scope working on my custom app for my store. However, I keep getting this error:
Error: GraphQL Error (Code: 422):
{"response":{"errors":{"delegate_access_scope":["The access scope
can't be empty."]},
To simply get this working I'm using the example from the docs:
const accessToken = gql`mutation {
delegateAccessTokenCreate(input: { delegateAccessScope: ["write_orders" ], expiresIn: 3600 }){
delegateAccessToken {
accessToken
}
shop {
id
}
userErrors {
field
message
}
}
}`
I'm kind of at my wits end here as I finally realized that the delegate.json actually needs the ADMIN key rather than the storefront even though I want to use this with the storefront API (which is weird). All I want to be able to do is create a new customer with a password via this API.
Thanks in advance.
Maybe you just need to change delegateAccessScope: to delegate_access_scope per doc, https://shopify.dev/apps/auth/oauth/delegate-access-tokens/create
{
"delegate_access_scope": [
"write_orders"
],
"expires_in": 3600
}
Ok, so I figured it out. I don't actually want a delegateAccessToken to create a user but to have a Storefront API Access Token. This may get a bit confusing but you use your Admin Access Token to request a storefront access token like so (I use graphql-request on npm):
const accessToken = gql`mutation storefrontAccessTokenCreate($input: StorefrontAccessTokenInput!) {
storefrontAccessTokenCreate(input: $input) {
shop {
id
}
storefrontAccessToken {
accessToken
}
userErrors {
field
message
}
}
}`
const accessTokenVars = {
"input": {
"title": "my-access-token"
}
}
const queryAccessTokenData = await adminGraphQLClient.request(accessToken, accessTokenVars);
From here you now have a Storefront Access Token and can make a call via Oauth to create a customer like so:
const shopifyUserQuery = gql`mutation customerCreate($input: CustomerCreateInput!) {
customerCreate(input: $input) {
customer {
id
firstName
lastName
acceptsMarketing
}
customerUserErrors {
field
message
code
}
}
}`
const shopifyUserVars =
{
"input": {
"firstName": values.firstName,
"lastName": values.lastName,
"email": values.email,
"password": values.password,
"acceptsMarketing": false,
}
}
// We need to switch the default storefront headers over to our private API key
sfGraphQLClient.headers = {
'X-Shopify-Storefront-Access-Token': queryAccessTokenData.storefrontAccessTokenCreate.storefrontAccessToken.accessToken,
'Content-Type': 'application/json'
}
const shopifyCreateCustData = await sfGraphQLClient.request(shopifyUserQuery, shopifyUserVars);
This will now create the user using the Storefront API.

CORS policy blocking access to Mailchimp API

I am developing a newsletter pop-up using nuxtJS and vuetify.
The process is simple: you enter you email adresse, mailchimp to the rest.
I am having an issue with Mailchimp API.
When I test the API using postman with the same setup, it works fine without any problems. (I can verify by checking the mailchimp account).
But when I try to subscribe through the pop-up, I recieve this error:
Error recieved
This my function code:
let data = {
"email_address": payload,
"status": "subscribed",
"merge_fields": {
"FIRSTNAME": "",
"LASTNAME": ""
}
}
const base64ApiKey = Buffer.from(`c18ab83bd3e9032e080d49f526285039-us6`).toString("base64");
// const base64ApiKey = "c18ab83bd3e9032e080d49f526285039-us6";
this.$axios.post("https://us6.api.mailchimp.com/3.0/lists/c3a3dea1fc/members/", data, {
method: 'POST',
mode: 'no-cors',
headers: {
"Access-Control-Allow-Headers": "Origin, Content-Type, X-Auth-Token, Authorization, Accept,charset,boundary,Content-Length",
"Content-Type": "application/json",
Authorization: `auth ${base64ApiKey}`,
"Access-Control-Allow-Origin": "*",
},
withCredentials: true,
credentials: 'include',
// proxyHeaders: false,
// credentials: false
}).then(res => {
console.log(res.data);
}).catch(err => {
console.log(err);
});
}
It's obviously a CORS problem, I tried on another machine and still have the same error.
A CORS issue is not to be setup on the front-end but rather on the backend/dashboard panel of the service.
So, there is probably a way to whitelist your localhost and production URL on the Mailchip dashboard.
Try to Google this out to find a guide.

How to get user email using Google Sign In expo Auth Session?

At moment im using this snippet of code to sign in to google, but i cant get user email… anyone know how to do this?
var LoginGoogle = () => {
const [request, response, promptAsync] = Google.useAuthRequest({
androidClientId: 'xxxxxxx.apps.googleusercontent.com',
expoClientId: 'xxxxxxx.apps.googleusercontent.com'
},{
scopes: ["email"]
},{});
React.useEffect(() => {
if (response?.type === 'success') {
const { authentication } = response;
console.log(response);
}
}, [response]);
return (
<GoogleSocialButton disabled={!request} onPress={() => {promptAsync()}} />
)
}
response returns object with links instead of email
I wish this is written in the expo docs. I would like to add a few points from the first answer:
First if you need code snippets on how to fetch user data after getting the access token, you can refer to this github issue: https://github.com/expo/expo/issues/8384
access token can be received by the following code after receiving the response object:
const { authentication: { accessToken } } = response;
then, you can create a function like this:
async function fetchUserInfo(token) {
const response = await fetch('https://www.googleapis.com/oauth2/v3/userinfo', {
method: 'GET',
headers: {
Accept: 'application/json',
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json'
},
});
return await response.json();
}
and get the user object (which contains the user email, profile, photo, etc) by something like this inside an async function:
const user = await fetchUserInfo(accessToken);
But NOTE for the user object, using https://www.googleapis.com/oauth2/v2/userinfo and https://www.googleapis.com/oauth2/v3/userinfo, will yield slightly different result/object ; in particular for v3, since Google implements the OpenID Connect API, there is no "id" attribute anymore, "id" will be called "sub".
sources:
How to identify a Google OAuth2 user?
https://developers.google.com/assistant/identity/google-sign-in-oauth
https://github.com/expo/expo/issues/8384
Example of a user object in v3:
Object {
"email": "xxxxx#gmail.com",
"email_verified": true,
"family_name": "John Deer",
"given_name": "John",
"hd": "gmail.com",
"locale": "en",
"name": "John Deer",
"picture": "https://lh3.googleusercontent.com/a/asdfjasdklfjaslkf",
"sub": "10998837733652322",
}
Hope this helps someone in the future...!
EDIT: if you need the id_token checkout this one:
expo-auth-session/providers/google Google.useAuthRequest
I am using AuthSession as well in my RN app and I stumbled with this problem. After going through Google API Docs, found out you can pass the access token from the useAuthRequest response to https://www.googleapis.com/oauth2/v3/userinfo?access_token= ACCESS_TOKEN.

react native login api jwt auth basic

I need help, I must login in React Native by calling an API
with this structure
URL: /api/a/login
Parameters: data
value: {
"user": "juan",
"userid": "123",
"passw": "000"
}
type: GET
with basic authentication using JWT
How can I call this api with those parameters from React Native
Thank you.
You can use axios to make HTTP calls. You can attach your auth JWT in the headers field to call the API.
Here's a minimal example using axios to make a GET request.
const axios = require("axios")
axios.get('/api/a/login', {
params: {
value: {
"user": "juan",
"userid": "123",
"passw": "000"
}
},
headers: {
jwt: your_jwt_here
}
})

405 error with JIRA REST API using node js

I am trying to create an automated JIRA ticket using the REST API but I keep getting a 405 error.
I am using the examples here: https://developer.atlassian.com/server/jira/platform/jira-rest-api-examples/
Also, when I visit the post URL directly I do not get any errors so I doubt it is a server issue. Any ideas?
var Client = require('node-rest-client').Client;
client = new Client();
// Provide user credentials, which will be used to log in to Jira.
var loginArgs = {
data: {
"username": "user",
"password": "pass"
},
headers: {
"Content-Type": "application/json"
}
};
client.post("https://jira.mydomain.com/rest/auth/1/session", loginArgs, function(data, response) {
if (response.statusCode == 200) {
//console.log('succesfully logged in, session:', data.session);
var session = data.session;
// Get the session information and store it in a cookie in the header
var args = {
headers: {
// Set the cookie from the session information
cookie: session.name + '=' + session.value,
"Content-Type": "application/json"
},
data: {
// I copied this from the tutorial
"fields": {
"project": {
"key": "REQ"
},
"summary": "REST ye merry gentlemen.",
"description": "Creating of an issue using project keys and issue type names using the REST API",
"issuetype": {
"name": "Request"
}
}
}
};
// Make the request return the search results, passing the header information including the cookie.
client.post("https://jira.mydomain.com/rest/api/2/issue/createmeta", args, function(searchResult, response) {
console.log('status code:', response.statusCode);
console.log('search result:', searchResult);
});
} else {
throw "Login failed :(";
}
});
I am expecting the Jira ticket of type REQ to be created with the details I added in the fields section.
I believe you are using the incorrect REST API; what you're currently doing is doing a POST to Get create issue meta which requires a GET method, hence, you're getting a 405. If you want to create an issue, kindly use Create issue (POST /rest/api/2/issue) instead.