React Native App with WordPress REST API - not allowed to create posts as this user - wordpress

I'm working on an application in React Native with simple Wordpress backend using REST API and I didn't have any problems until I used GET method.
Now I need to create a blog post using the POST method and I'm still getting an error...
What I have:
Wordpress with activated Basic Authentication handler plugin -> https://github.com/WP-API/Basic-Auth
React Native project with WPAPI Client -> https://github.com/WP-API/node-wpapi
My React code:
const WPAPI = require( 'wpapi' );
let apiPromise = WPAPI.discover( 'https://myweb.com/wp-json' ).then(function( site ) {
return site.auth({
username: 'admin',
password: 'password'
});
});
apiPromise.then(function( site ) {
site.posts().create({
title: 'Your Post Title',
content: 'Your post content',
status: 'publish'
}).then(function( response ) {
console.log( response );
})
.catch(function(err){
console.log(err);
});
})
and always get this answer:
"code": "rest_cannot_create",
"status": 401,
"message": "Sorry, you are not allowed to create posts as this user."

Related

Next Auth email credential without default signIn page

Is there a solution to use credential email - password from backend
without the default authentication page provided from Next/auth?
I must use Modal instead of full-page authentication
I follow the doc:"https://next-auth.js.org/providers/credentials" but when I use the SignIn from nextAuth it generates a signIn Page
Add your own custom login page if any and/or a sign-in button that uses a function that is provided by NextAuth. See below how it is done.
Custom Login Page
In your api/auth/[...nextauth].js file add this option.
export default NextAuth({
...
pages: {
signIn: '/login',
},
});
NextAuth Sign In Function
signIn('credentials', {
redirect: false,
callbackUrl: '/',
username: ...,
password: ...,
})

React Native - How to persist a Firebase authenticated user session from react-native app to a (react-native-webview) webview component?

I have a react-native app which uses Firebase (with "#react-native-firebase/auth": "^6.0.1").
In the app there is one Webview (with "react-native-webview": "^7.5.2").
The user logs in, then I have access to its jwt by using:
auth().currentUser.getIdTokenResult()
.then(jwtToken => {
console.log('jwtToken: ', jwtToken.token);
})
Now I need the user to open the Webview and still being connected because the webview points to my firebase hosting page.
<WebView
source={{
uri: 'my-firebase-hosting-url',
headers: {
Authorization: jwtToken,
},
}}
renderLoading={this.renderLoadingView}
startInLoadingState={true}
sharedCookiesEnabled={true}
thirdPartyCookiesEnabled={true}
domStorageEnabled={true}
ref={ref => {
this.webview = ref;
}}
/>
On the server side, I have setup express and cookie-session.
The user doesn't seems to be logged in the webview: on the server side, when I console.log(req.session) it shows an empty object {}.
I've tried multiple options but nothing seems to work in iOS (not tried on Android yet)
What am I missing? Are there extra steps on the frontend/backend? (I am still new to programming)
Thank you for your help.
I finally solved it and hope it will help others:
Design your state
state = {
shouldRenderWebview: false,
authorization: ''
...
In your constructor, get a refreshed token from firebase
auth()
.currentUser.getIdTokenResult()
.then(result => {
this.setState({
authorization: result.token,
shouldRenderWebview: true,
});
})
Design your main component to either show a loading view (while it's getting the token) or render the webview
Your webview (and add 'Bearer' to the code)
const Authorization = 'Bearer ' + this.state.authorization;
<WebView
source={{
uri: this.state.urlToGo,
headers: {
Authorization,
},
}}
....
In your backend, check if the authentication code is valid
firebase.auth().verifyIdToken(req.headers.authorization.substr(7));
Then do your stuff depending on the result.

How do you add an item to an existing cart using BigCommerce's Storefront Cart API?

I'm having difficulty using the BigCommerce Storefront Cart API as described in their docs
When I manually send an http request through the fetch api using a console window open on the storefront website, it always comes back with 404 "Cart does not exist".
This is the fetch request I'm using:
fetch(
'/api/storefront/carts/e475da57-e9d1-4da0-b9bf-ac4c34b8d601/items',
{
credentials: 'same-origin',
method: 'POST',
body: JSON.stringify({ lineItems: [{ quantity: 1, productId: 2968 }]})
}
).then(res => res.json()).then(console.log)
I got the id by going to <store-url>/api/storefront/cart
When I simply do a GET on the same cart id, it sends back an object as expected.
I have no trouble when I make a new cart. It's only a problem if I want to add items to an existing cart.
I've tried adding a trailing forward slash, singular and plural forms of carts and items and lineItems

How to implement facebook-sdk to gatsby

I'm trying to pull photos from a facebook page and place them on a my gatsby website, but I'm having trouble integrating Facebook SDK so I can use Graph API to grab the data I need. I've tried just getting the url of the photos and used them in img tags, but the photos disappear as I refresh the page.
I used axios to get the data
getFacebookAPI = () => {
let imgArray = []
axios.get('https://graph.facebook.com/v2.7/me?fields=id,albums{photos{images}}&access_token=exampletoken')
.then(response => {
console.log(response)
console.log(response.data.albums.data[0].photos.data)
response.data.albums.data[0].photos.data.map(info =>
imgArray.push(info.images[0].source)
)
})
return imgArray.map(info => <img src={info} alt="facebook" />)
}

How to check if users shared info on wall?

What i need to do is when user login to game and share our adv picture i want check is share successful and add extra XP points. So i created link like this:
<a onClick="window.open('http://www.facebook.com/sharer.php?s=100&p[title]=Title of sharer;&p[summary]=Descriobe abiut game etc&p[url]=http://google.com&&p[images][0]=http://www.some.jpg','sharer','toolbar=0,status=0,width=548,height=455');" href="javascript: void;">
test </a>
So do i have no respond implementation. DO i need create some APP in fb and do by API with my APP ID or how to resolve this problem ?
You can use the Facebook JavaScript SDK to track if the user successfully shared something to their wall. This tutorial shows how to achieve this.
If you share something to the wall using the FB.ui dialog box, you can add a callback to the function to track success / failure, as follows:
FB.ui( {
method: 'feed',
name: "Facebook API: Tracking Shares using the JavaScript SDK",
link: "https://www.webniraj.com/2013/05/11/facebook-api-tracking-shares-using-the-javascript-sdk/",
picture: "https://stackexchange.com/users/flair/557969.png",
caption: "Tracking Facebook Shares on your website or application is a useful way of seeing how popular your articles are with your readers. In order to tracking Shares, you must used the Facebook JavaScript SDK."
}, function( response ) {
if ( response !== null && typeof response.post_id !== 'undefined' ) {
console.log( response );
// ajax call to save response
$.post( '{url_that_will_track_share}', { 'meta': response }, function( result ) {
console.log( result );
}, 'json' );
}
} );
In this example, the callback triggers an ajax call to another page with the response from the Feed dialog. If the user shared the post, the response will contain the post_id. You can use the ajax script to check if the post_id exists and is valid and then award XP points accordingly.

Resources