How to open POST url in device browser from React native application - javascript

I have a shopping website where user can add items to the user's cart. But in the checkout process, I want the user to navigate in my website with the user's cart token. I want to open URL in Device browser from the react-native application with post data.

There's a library called Linking you could use.
You can open the url like so:
Linking.openURL('<insert-url-here');
This will open the URL in the default browser.

According to Linking documentation, you can't pass any POST data with the url. You can only send POST data with fetch. You will have to find another way for this to work.
You could definitely just send your token with GET data:
Linking.openURL('https://yoururl.com/?cart_token=[token]');

If you want to check if any installed app can handle a given URL
beforehand you can call:
Linking.canOpenURL(url)
.then((supported) => {
if (!supported) {
console.log("Can't handle url: " + url);
} else {
return Linking.openURL(url);
}
})
.catch((err) => console.error('An error occurred', err));
https://facebook.github.io/react-native/docs/linking#opening-external-links

Related

Sending data from frontend to backend in shopify

I'm developing an app with node and react. In this app, I have created a scriptTag using the fetch function to get customer id and product id whenever a specific button is pressed. Now when I have fetched that data, I want to store it in my firebase database, which I cannot import in my script tag file because it's on the front end. Therefore, I need to send the data from my frontend to the backend of the app but I'm confused that if I use the fetch function to make POST and GET requests, what URL should I use? Moreover, can the fetch function even post the variable values or not?
Scripttag.js
const header = $('header.site-header').parent();
header.prepend('<div>Hello this is coming from the public folder </div>').css({'background-color':'orange', 'text-align': 'center'})
function addWishList(customer, productid){
/*
fetch(`url`, {
method: 'POST',
headers: {
'Content-Type': ,
"X-Shopify-Access-Token": ,
},
body:
}})
})
*/
console.log('adding item to the wishlist!!')
}
function removeWishList(){
console.log('removing item from the wishlist!!')
}
var wishbtn = document.querySelector('.wishlist-btn')
wishbtn.addEventListener('click', function(){
if(this.classList.contains('active')){ //condition to check if the button is already pressed
removeWishList();
this.classList.remove('active');
this.innerHTML = 'Add to wishlist'
}
else{
var customer = wishbtn.dataset.customer;
if(customer == null || customer == ''){
console.log('Please log in to add this item to your wishlist')
}
else{
var productid = wishbtn.dataset.product;
this.classList.add('active'); //when the user presses add to wishlist button, it add active to the button's class
this.innerHTML = 'Remove from wishlist'
addWishList(customer, productid);
}
}
})
The best way to send data from the frontend to the backend is to use the Proxy option that is provided in the Shopify Partner Dashboard.
This way you can stay in the Shopify environment since it will pass specific arguments to the request that you can check if the request is truly coming from Shopify and you will have one less worry about securing it from outside requests.
So for example you will make a fetch request to /apps/YOUR_CUSTOM_PATH and this will proxy to your URL https://example.com/custom_path where you will handle the request.
You can see more info here: https://shopify.dev/tutorials/display-data-on-an-online-store-with-an-application-proxy-app-extension
You can create a public route for your app as well that can be requested from everywhere and allow for CORS but it's usually more work to do so... so pick your poison.
Have in mind that when creating a proxy page you need to reinstall the app on the store to take effect.
PS: Don't ever use the Access Token in the frontend, that should be never present in the frontend. The AccessToken is only back-end way of communicating with the API!

get all items from podio api

I want to fetch items of app from podio in node js
here is the code that am using to get items,
podio.authenticateWithCredentials(username, password, function () {
podio.request('GET', '/item/app/{app_id}/filters').then(function (responseData) {
console.log(responseData);
res.send(responseData);
}).catch(function (e) {
console.log('0-0-0-0', e);
res.send(e);
});
});
an i always get this error
"No matching operation could be found. The path '/item/app/{app_id}/filters' was not found.."
is there any solutions ?
only replace {app_id} with the app id To get the app id and token:
Go to your app on Podio
Click the little wrench in the sidebar
Select the "Developer" option near the bottom
On the following page you can get the app id and token
You need to replace app_id in this url '/item/app/{app_id}/filters' with actual url you must have got from podio api.
You should use POST instead of GET method

Azure using wrong callback url during implicit flow login

I'm currently struggling with a weird problem in azure active directory implicit flow oauth authentication. I've implemented a spa webapp using msal.js to login users to their microsoft accont.
The userAgentApplication is executed as shown below:
userAgentApplication = new
Msal.UserAgentApplication(client_id,null,function(errorDes,token,error,tokenType)
{
if(error) {
console.log(JSON.stringify(error));
return;
}
},{ redirectUri: 'https://example.com/app/msalCallback.html' });
When they click login executing the is piece of code:
logInPopup = function() {
var uaa = userAgentApplication;
return new Promise(function(resolve,reject) {
uaa.loginPopup([
'https://graph.microsoft.com/user.read'
]).then(function(token) {
//signin success
console.log(token);
var user = uaa.getUser();
console.log(JSON.stringify(user));
resolve(user);
}, function(error) {
console.log(JSON.stringify(error));
reject(error);
});
})
}
The popup comes up and the user tries to login but the following error comes up:
Microsoft account is experiencing technical problems. Please try again later.
In the url the error parameters string is:
error_description=The provided value for the input parameter
'redirect_uri' is not valid The expected value is
'https://login.live.com/oauth20_desktop.srf' or a URL which matches
the redirect URI registered for this client application.
Upon further research I found that though I configured the redirect uri to be
https://example.com/app/msalCallback.html
(Which I confirmed on the application registration page to be true)
The redirect_uri of the /oauth2/v2.0/authorise url in the login popup page is:
redirect_uri=https://example.com/app/
Which is weird but the above uri is not random one. It is in fact the callback uri for a previous previously registered but now deleted app with the same name.
Further investigation showed that when I config Msal to use the old the redirect_uri login passes.
I'm fresh out of ideas. It looks like a bug in the azure network but wanted to know if anyone else has had this problem or at least point me in the right direction towards getting in contact with azure to find a fix.
Thanks in advance
I've found the cause of the problem after carefully reviewing the msal.js documentation i found that i was setting the redirectUri incorrectly. The correct way is as follows:
var userAgentApplication = new
Msal.UserAgentApplication(client_id,null,function(errorDes,token,error,tokenType)
{
if(error) {
console.log(JSON.stringify(error));
return;
}
});
userAgentApplication.redirectUri = 'https://example.com/app/msalCallback.html'
Hope that helps.
regards

Authentication logic for sessions that last while tab is open

Assume you are working on a front end application that performs authentication through 3rd party api. Successful authentication returns a json web token.
What would be best practices to store such token and create some sort of session for user while he is active on the website i.e. didn't close a tab or browser, however refreshing / reloading a page should not destroy such session.
Also, how can this session be used to protect routes? I am working with a stack consisting of react / redux / node / express and quiet a few other libraries. I believe I can perform certain checks within my react-router, however wouldn't it be better to do these on the express side?
You can store the token in localStorage or sessionStorage, and include it in every API request.
Local storage outlives the tab, it's stored there until you explicitly delete from it, so refreshing a page won't be a problem. Even closing a tab and then coming back won't be.
Session storage allows you to store data. Page refreshes are fine, but tab closing isn't, which is closer to the behavior you want.
As for protecting routes, the server should obviously check the token on requests to all protected API routes.
On the browser side, you will probably want to show a login form if a user tries to visit a protected route but the token isn't there (or is invalid).
With react-router, you could do it like the official repo shows in the example, via onEnter hooks: https://github.com/reactjs/react-router/blob/master/examples/auth-flow/app.js
An alternative would be to create two top-level components, one for protected routes, one for public routes (like a landing page or the sign in/sign up forms). The protected handler will then in componentWillMount check if there's a token:
- PublicHandler
+ SignIn
+ SignUp
+ Index
- ProtectedHandler
+ Dashboard
+ MoneyWithdrawal
it may looks like that , with sessionStorage (JWT token is accesseble, untill browser or tab closed)
///action creator redux
export const signupUser = creds => dispatch =>{
dispatch(requestSignup());
return API.auth.signup(creds)
.then(res => {
sessionStorage.setItem('token', res.token);// <------------------
dispatch(receiveSignup(res));
return res;
})
.catch(err => {
dispatch(SignupError(err));
);
});
};
On client : handling auth through HOC redux-auth-wrapper
On server on server you can use passport-jwt strategy
passport.use('jwt',new JwtStrategy(opts, function(jwt_payload, done) {
User.findOne({where:{ id: jwt_payload.user.id }}).then(user=>{
if (user) {
done(null, jwt_payload.user);
} else {
done(null, false);
// or you could create a new account
}
},err=>{
console.log('Error ',err);
return done(err,false);
});
}));
then just add route handler
var checkJWT = passport.authenticate('jwt')
router.get('/protected',checkJWT, (req, res) =>{
res.json(req.user);
});
You don't need sessions on server for that

What oauthRedirectURL in openFB should look like, using a cordova app?

I came across this openFB plugin to make facebook requests without the sdk, that can be used in cordova,
I got it to log in the user in facebook, the thing is as oauthRedirectURL I end up in a white page, that says Success and I'm not sure how to get the user back to the app,
if (runningInCordova) {
oauthRedirectURL = "https://www.facebook.com/connect/login_success.html";
}
Question is,
What url can i use to point my app ?
User ends up in this screen after the login
-edit-
I found solutions like http://localhost.com/oauthcallback.html but I don't have a apache2 in the cordova environament..
-2nd edit-
This is my current code,
openFB.init({appId: 'xxxxxxxxyyyyyyyy'});
openFB.login( function(response) {
if(response.status === 'connected') {
alert('Facebook login succeeded, got access token: ' + response.authResponse.token);
} else {
alert('Facebook login failed: ' + response.error);
}
}, {scope: 'email'});
This the line of the lib that fills this value
if (runningInCordova) {
oauthRedirectURL = "https://www.facebook.com/connect/login_success.html";
}
I haven't used openFB before but I'm pretty sure it's based on the following docs:
https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow/v2.3
If you go to the section "logging people in" you'll see the following message:
redirect_uri. The URL that you want to redirect the person logging in
back to. This URL will capture the response from the Login Dialog. If
you are using this in a webview within a desktop app, this must be set
to https://www.facebook.com/connect/login_success.html.
When a FB user grants permissions to your App, it will be redirected to the url https://www.facebook.com/connect/login_success.html?access_token=new_token&...
What you have to do now is monitor this url and get the access token provided, which you should store with the fb user id in order to perform any API call.
Googling how to do this with openFB I found a thread at the openFB github repo that should help: https://github.com/ccoenraets/OpenFB/issues/20#issuecomment-49249483 (is not totally related but it provides some code you can use)
This should be the code that will allow you to monitor the URL (extracted from the code provided on the thread):
if (runningInCordova) {
loginWindow.addEventListener('loadstart', function (event) {
var url = event.url;
if (url.indexOf("access_token=") > 0) {
// Get the token
}
});
}
Once you have obtained the access token and stored in your database, you should redirect to any other place of your App.
I hope it helps.
Javier.

Categories

Resources