Google ReCaptcha API doesnt work properly on my frontend - vue.js

When I try to make the call from the browser it doesnt work properly
This is the response I get in browser
It is supposed to be like this:
{
"success": true|false,
"challenge_ts": timestamp, // timestamp of the challenge load (ISO format yyyy-MM-dd'T'HH:mm:ssZZ)
"hostname": string, // the hostname of the site where the reCAPTCHA was solved
"error-codes": [...] // optional
}
I'm using vue-recaptcha library on vue3.
<VueRecaptcha
ref="recaptcha"
sitekey="my_key"
#verify="onVerify"
/>
This is the fetch method I use to make the call to google recaptcha api
function onVerify(token) {
fetch(
`https://www.google.com/recaptcha/api/siteverify?secret=${secret_key}&response=${token}`,
{
method: 'POST',
}
)
.then((data) => {
console.log(data);
})
.catch((error) => {
console.error('There was an error!', error);
});
}
The thing is when i try the same call in postman it works as it should and responds with the following object:
{
"success": true,
"challenge_ts": "2023-02-07T13:20:44Z",
"hostname": "localhost"
}

Related

Setup Checkout Rest API for Shopify from react mobile app

I am new to shopify, can anyone help me how to setup the checkout API for shopify. I am creating a mobile app with react for a shopify website using API. I tried the one in the shopify docs but it return some error.
post: https://{apikey}:{password}#{hostname}/admin/api/2020-10/checkouts.json
body raw json
{
"checkout": {
"line_items": [
{
"product_id": 5584792125605,
"variant_id": 35877399986341,
"quantity": 1
}
]
}
}
header
X-Shopify-Access-Token : storefront access token
Response
{
"errors": "[API] Invalid API key or access token (unrecognized login or wrong password)"
}
But I've given API key and access token correctly. Is there anything else i should do( I tested this in postman)
Using react native, you have to give the apikey and the password in the Header like this.
getShopifyOrders = () => {
let authorization = base64.encode(
'${Constants.Shopify.key}:${Constants.Shopify.password}'
);
fetch(
'https://${Constants.Shopify.admin_url}/admin/api/2021-04/orders.json',
{
method: "get",
headers: new Headers({
Authorization: 'Basic ${authorization}',
}),
}
)
.then((response) => response.json())
.then((json) => {
console.log(json);
})
.catch((error) => {
console.error(error);
});
};
With Constants.Shopify.key = 'Your_api_key' and Constants.Shopify.password = 'Your_password'
Note : In this code, you have to replace the ' with backsticks ;)

How to handler server redirect from axios

I have a vue web app that uses axios to communicate with an API. The authentication is handled by the server, and not by my app. That is, the server ensures that the user cannot see the app before they have authenticated.
Of course, after some time the user's authentication token expires and my app only notices this when it fires off a get/post request to the API. When this happens the axios request returns a redirect to a login page that, when printed to the console, looks something like this:
config: Object { url: "https://...url for my request...",
method: "get", baseURL: "...base url for api", … }
data: "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/REC-html40/loose.dtd\">\n<HTML>\n<HEAD>\n<TITLE>Need Authentication</TITLE>\n<link rel=\"stylesheet\" href=\"/Steely.css\" type=\"text/css\">\n</HEAD>\n<BODY>....</BODY>\n</HTML>\n"
headers: Object {
connection: "Keep-Alive",
"content-encoding": "gzip", "content-length": "1686", …
}
request: XMLHttpRequest {
readyState: 4, timeout: 0, withCredentials: false, …
}
status: 200
statusText: "OK"
<prototype>: Object { … }
app~d0ae3f07.235327a9.js:1:97292
What is the best way to redirect the user to this login page and then resume my original request? At the moment I am not even succeeding in recognising this. My axios code tries, and fails, to recognise when this happens and then redirect to user a vue component that has a login page. The relevant part of code looks like this:
export default new class MyAPI {
constructor() {
this.axios = axios.create({
headers: {
'Accept': 'application/json',
'Cache-Control': 'no-cache',
'Content-Type': 'application/json',
},
baseURL: `https://.../api`,
});
}
// send a get request to the API
GET(command) {
return new Promise((resolve, reject) => {
this.axios.get(command)
.then((response) => {
if (response && response.status === 200) {
if ( response.data && typeof response.data == 'string' && response.data.includes('Require authentication') ) {
store.dispatch('authenticate', this.baseURL+'/'+command).then( (resp) => resolve(resp.data) )
} else {
resolve(response.data);
}
} else {
reject(response.data);
}
})
.catch((err) => { reject('Internal error'+err); });
});
}
}
This results in the dreaded
Internal errorTypeError: e(...) is undefined
error, although this error is almost certainly triggered further down the code since I not recognising the login authentication request.
Is anyone able to recommend how best to recognise and process the login request?

How to properly use passport-github for REST API authentication?

I am building a vue.js client which needs to be authenticated through github oauth using an express server. It's easy to do this using server side rendering but REST API has been troublesome for me.
I have set the homepage url as "http://localhost:3000" where the server runs and I want the authorization callback url to be "http://localhost:8080" (which hosts the client). I am redirecting to "http://localhost:3000/auth/github/redirect" instead, and in its callback redirecting to "http://localhost:8080". The problem I am facing is that I am unable to send user data to the vuejs client through res.redirect. I am not sure if I am doing it the right way.
router.get("/github", passport.authenticate("github"));
router.get(
"/github/redirect",
passport.authenticate("github", { failureRedirect: "/login" }),
(req, res) => {
// res.send(req.user);
res.redirect("http://localhost:8080/"); // req.user should be sent with this
}
);
I have implemented the following approach as a work around :-
A route that returns the user details in a get request :
router.get("/check", (req, res) => {
if (req.user === undefined) {
res.json({});
} else {
res.json({
user: req.user
});
}
});
The client app hits this api right after redirection along with some necessary headers :
checkIfLoggedIn() {
const url = `${API_ROOT}auth/check/`;
return axios(url, {
headers: { "Content-Type": "application/json" },
withCredentials: true
});
}
To enable credentials, we have to pass the following options while configuring cors :
var corsOption = {
origin: true,
credentials: true
};
app.use(cors(corsOption));

handle network request failed in react native

I'm facing an issue while using react native fetch api. many times request got failure . I have a high speed connection. but many times it got failed.
that issue is happening In android,ios both.
const shoppingApi = 'myserverlink';
async function Sendshoppinapi(data) {
try {
let response = await fetch(shoppingApi, {
method: 'POST',
headers: {
'Accept': 'application/json',
'content-type':'multipart/form-data'
},
body: data
});
let responseJson = await response.json();
return responseJson;
}
catch (error) {
Alert.alert(error.toString())
}
}
export {Sendshoppinapi};
data that I sending server as post request
add_to_wishlist = (item,index) => {
{
let data = new FormData();
data.append('methodName', 'add_to_wishlist');
data.append('user_id', global.userid)
data.append('item_id', this.props.navigation.state.params.itemid.toString())
Sendshoppinapi(data).then((responseJson)=>{
console.warn(responseJson);
if(responseJson.responseCode == '200'){
this.setState({fav:false})
Alert.alert('SHOPPING','Item added to wishlist successfully.',[{text: 'OK',},],{ cancelable: false })
}
else{
this.setState({fav:false})
Alert.alert('SHOPPING','Item already .',[{text: 'OK',},],{ cancelable: false })
}
})}
}
Error that when request got failed
I've quoted an answer I used for another post - however I have added await.
You can check the status of the call, to determine perhaps why the network call failed. Try using fetch's ok to check whether the response was valid, for example:
.then(function(response) {
if (!response.ok) {
//throw error
} else {
//valid response
}
})
Using await:
let response = await fetch(url)
if (response.ok) return await response.json()
You can also access the response's status like:
response.status;
or also, statusText such as:
response.statusText;
checkout the below:
https://developer.mozilla.org/en-US/docs/Web/API/Response/statusText
https://developer.mozilla.org/en-US/docs/Web/API/Response/status
https://www.tjvantoll.com/2015/09/13/fetch-and-errors/
Use then() function with promises. (Requested code snippet)
fetch(shoppingApi, {
method: 'POST',
headers: {
'Accept': 'application/json',
'content-type':'multipart/form-data'
},
body: data
})
.then((resp) => {
return resp.json()
})
.then((resp) => {
//resp contains your json data
});
You also can make your function returns a Promise, and use it with then():
function sendShoppingApi(data) {
return new Promise((resolve, reject) => {
fetch(shoppingApi, {
method: 'POST',
headers: {
'Accept': 'application/json',
'content-type':'multipart/form-data'
},
body: data
})
.then((resp) => {
return resp.json();
})
.then((resp) => {
resolve(resp);
/*
you should also check if data is valid, if something went wrong
you can reject the promise:
if(!dataOK)
reject("error message");
*/
});
});
}
So now you can do something like this:
sendShoppingApi(data)
.then((resp) => {
//do stuff with your data
})
.catch((err) => {
//handle error
});
UPDATE
could be a duplicate of this: React Native fetch() Network Request Failed
For the case when you are running the app on the android device, the API is on a computer and both of them are on the same network I have added some possible things to check. I haven't detailed specific solutions since there are many answers on each topic.
Do a quick check with ngrok https://ngrok.com/ on the free plan to see if that works. If yes:
Make sure the API is accessible by trying to access it on the device browser (most important is to check if you allow the port at inbound rules, firewall).
If you are using HTTPS, you might get an error if your react native env is not properly configured to accept not trusted certificates, assuming you are using a non trusted one. Do a check without HTTPS, only with HTTP, to see if it's the case. https://github.com/facebook/react-native/issues/20488

Google API client compatibility with Google Chrome extensions

I'm working inside of a Google Chrome extension and I would like to use Google's Client API, https://apis.google.com/js/client.js, to retrieve a user's Google+ ID.
I've supplied the following values in my manifest.json:
"oauth2": {
"client_id": "[CLIENT ID].apps.googleusercontent.com",
"scopes": [
"https://www.googleapis.com/auth/plus.login",
"https://www.googleapis.com/auth/plus.me"
]
}
Providing these values allows me to successfully call chrome.identity.getAuthToken: http://developer.chrome.com/apps/identity.html
getAuthToken: function () {
chrome.identity.getAuthToken({
interactive: false
}, function (authToken) {
if (chrome.runtime.lastError) {
// User isn't signed into Google Chrome.
console.error(chrome.runtime.lastError.message);
}
});
}
Once I have an auth token, I'm able to issue an AJAX request and successfully get my info:
$.ajax({
url: 'https://www.googleapis.com/plus/v1/people/me',
headers: {
'Authorization': 'Bearer ' + authToken
},
success: function (response) {
console.log("Received user info", response);
},
error: function (error) {
console.error(error);
}
});
None of this uses the aforementioned Google Client API, though. It would be nice to leverage that instead, but I'm wondering if it is not meant for Google Chrome extensions. I'm able to at least get things sort of working like so:
GoogleAPI.auth.authorize({
client_id: '[CLIENT ID].apps.googleusercontent.com',
scope: 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/plus.me',
// Set immediate to false if authResult returns null
immediate: true
}, function(){
GoogleAPI.client.load('plus', 'v1', function () {
var request = GoogleAPI.client.plus.people.get({
'userId': 'me'
});
request.execute(function (response) {
console.log("Response:", response);
});
});
But I've already specified these values in my manifest -- so it seems a bit odd to re-refrence them. I could load my manifest and parse it, but I've already got something successfully working above.
Additionally, you have to call GoogleAPI.client.setApiKey to use Google's stuff. This works on a development environment because I am able to whitelist my machine's IP, but this would not work in a production environment as there will be many clients connecting.
So, should Google's Client API not be used within Google Chrome extensions?