Hiding contentful Space id and access token, client side javascript file - javascript

I am new in contentful and I am trying to display content from contentful to a web page. I am displaying the content using contentful.js, I wanted to know How can i hide these information(space id and access token values) from public users when i am using it in a js file to display contents in a web page. Below is the Javascript code which i am using in main Js file to display the content in html file.
var client = contentful.createClient({
accessToken: 'b4c0n73n7fu1',
space: 'cfexampleapi'
});
client.entries()
.then(function (entries) {
// log the file url of any linked assets on image field name
entries.forEach(function (entry) {
if(entry.fields.SampleContent) {
document.getElementById('sample_content_block').innerHTML = entry.fields.SampleContent;
}
})
})
Thanks in advance!

There a few different ways that you could do this. The easiest way would be to move your space ID and accessToken into an environment variable. Take a look at this medium post on how to do that with Javascript: https://medium.com/ibm-watson-data-lab/environment-variables-or-keeping-your-secrets-secret-in-a-node-js-app-99019dfff716.
Then on your hosting provider, you'd be able to set the environment variable as those variables and your code would be able to utilize them.
Something interesting to note is that all the content that you put onto Contentful is assumed to be read-only. Exposing your Content Delivery API key (the access key in your example) and your space ID isn't the end of the world in a way that sharing an API Key for an alternative service can be. Using that CDA Key you posted wouldn't enable someone to edit any of the data you have stored on Contentful, just to read it.
However, you want to make sure you don't expose your CMA Key (Content Management API Key) as that would allow people to edit and change your content in Contentful.

You could use your own server to proxy requests, or something like Aerobatic's express request proxy feature: https://www.aerobatic.com/docs/http-proxy

Related

Shopify wishlist app - displaying item information from products.json?

I'm trying to finish the front-end of my shopify wishlist app.
-My app uses a database with each record contains a product ID that the client has wishlisted.
The logic:
-I have a front-end shopify page with a div tag containing the client's ID. (if signed in)
-I use javascript to grab the client's ID and then grab all the product IDs from my app's database.
[Up to this point it works fine, I have the product IDs]
-Now I'm calling axios.post(appDomain + '/api/showWishlist', {shop_id: Shopify.shop,customer_id: customer})
-Inside my api.php file I have: Route::post('showWishlist', 'App\Http\Controllers\WishlistController#show');
-Which then my show function in my wishlistController file has php code that needs to return the product info (name, price, image, etc.) from the store's products.json.
This is where my problem lies. I can't seem to be able to grab the product info based on the ID. My original idea was to use graphQL in my controller function, but I believe that it only works for the website's owner as Auth::user() is required to run the graphQL?
How can I get the shopify product details (name,price,etc.) by using the product's ID from my wishlistController.php file?
Since you are already running an App, your best bet is re-factor it to be embedded (or just installed) in the shop itself, with permission to read products. In the front end, you use the App Proxy to call your App with product ID and customer IDs. You can then call Shopify, get the correct product information based on the IDs, and provide a nice JSON payload back to the front-end, all securely. This is the preferred pattern and without it, you're in for a tough slog. You could try tap-dancing with StorefrontAPI permissions, but still. You also expose your own App to abuse since you make no mention of you are securing your data. With the Shopify embedded App approach, you are protected.

Firebase storage access token gets removed when passed as a parameter to firebase dynamic link

I've stored an audio file in firebase storage and I want to pass its url with access token as a parameter to the firebase dynamic link.
I wan to make my file.component,ts available for public share on whatsapp, FB etc and below is the code where I am getting the file parameters
this.activatedRoute.queryParams.subscribe(params => {
this.userName = params["user"];
this.audioPath = params["audio"]; //firebase storage audio with access token
this.docId = params["docId"];
this.docTitle = params["title"];
this.userId = params["userId"];
)
Now I want to pass all the above parameters as a link to the firebase dynamic link http.post call to get a short link.
The audio parameter consists of url to firebase storage access url along with the access token e.g
https://firebasestorage.googleapis.com/v0/b/<site>/o/audio%2Fsong1-min.mp3?alt=media&token=xxxx-xxxxx-xxxx-xxxxx
The moment I pass this audio variable to the dynamic link, it removes the token and reduces the path to
https://firebasestorage.googleapis.com/v0/b/<site>/o/audio%2Fsong1-min.mp3
Hence when I receive the short link it displays all other fields on UI along with the audio tag but the src has the token removed hence external user cannot play the audio if shared on whats app, FB etc.
Is there anyway I can send this firebase storage access url as it is inside the dynamic link so that the audio could play.
I don't believe this is possible in the way you are designing it, Firebase Dynamic Links will take out the token to shorten the link and there is no way to force it not to do it. What you could do is either:
1 - Make the File publicly readable;
2 - Have the file be fetched and processed separetly in your app without using Firebase Dynamic Links;
The problem may be linked to the method that you use to generate the Dynamic Links. The longDynamicLink method of the firebase REST API seems to exclude tokens, but the dynamicLinkInfo seems to keep them, so try that latter instead.
The following error message pops up when using the longDynamicLink approach with a token:
{
warningCode: 'UNRECOGNIZED_PARAM',
warningMessage: "Unrecognized param 'token'. [https://firebase.google.com/docs/dynamic-links/create-manually#ddl_parameters]"
}

Best way to store wordings in my web application?

Hi i want to store wordings used in my application where i could easily get them and use/reuse them.
Some example of wordings like loading messages or validation messages, or any information messages.
I have tried using .resx files to store some of these but one thing i hate about is i need to get that wording on the server which i get lazy after doing it so many times.
I also tried storing them in a javascript array but i realized that any user might be able to see all those wordings since it is stored on the client side. But i dont have anything to hide there. It is just i feel that it is not the right thing to do maybe?
Anybody has any good suggestions?
If you want to store just some messages javascript is absolutely fine.
I may suggest you the following approach:
Create a js file as follows and name it messages.js
var messages = {
"loading" : "Still loading",
"validation1" : "Please fill the required field",
"success" : "thats a success",
"failure" : "some error",
"custom1" : "custommsg1",
"custom2" : "custommsg2"
}
Include it in your web page and use whichever custom message you want to use
like for example
when you want to use success use message.success and similarily message.loading and so on for other messages.
Make sure that the left hand side values are unique since these are key value pairs.
There is nothing wrong that the user can see your wordings, and there is no way to hide data from user in web app. If you need to store secure data, keep them on the server, otherwise user can get from researching your app.
Create a JSON file called messages.json
and create a service to read from that by doing a HTTP request
$http.get("messages.json").then(function(response) {
$scope.messages = response.data;
});
Now scope has a property which is globally accessible

protect http request URL

i am getting remote JSON value into to my client app as below.
var $Xhr = Ti.Network.createHTTPClient({
onerror : function($e) {
Ti.API.info($e);
},
timeout : 5000,
});
$Xhr.open("GET", "http://***********.json");
$Xhr.send();
$Xhr.onload = function() {
if ($Xhr.status == 200) {
try {
Ti.API.info(this.responseText);
} catch($e) {
Ti.API.info($e);
} finally {
$Xhr = null;
}
}
};
My json URL is static. i would like to protect this URL from stranger eyes after creating APK file or publishing for iOS.
Also my server side support PHP. I have thouhgt MD5, SHA etc. but i didn't develop any project about this algortim.
Do you have any suggestion or approach?
Thank you in advance.
I would just say that it is not possible for you to "hide" the end point. Your url will always to visible to the user because otherwise user's browser wouldn't know how to actually post it to your server.
If you meant to only hide the json object, even that is not totally possible. If your javascript knows what the values are then any of your client smart enough to understand javascript will be able to decode your encoded json object. Remember, your javascript has decoded object and a user would have full access to it. There is no protection against that. At best, you can hide it from everyday user by encoding to with md5 or sha as you put it.
I you wish to restrict access to app user only, you will need to authenticate your users first.
Once they are authenticated, you should generate a hash by concatenating userid (or any user identifying data) and a key that you know (a string will do it), and hashing it using any hashing method, md5 would be enough for that kind of usage I guess, SHA is good anyway.
The next step would be to send this hash with every AJAX request to your server. consider it as an additional data.
Finally, server-side, before treating the request and fetching the data to be sent, just generate a hash the same way you did in your app, using the userid of the requesting user and the same "secret" key you chose. You can now compare both hashes and see if they're identical. If not, then it's probably that someone tried to forge a request from outside your app.
Note that it could be possible for someone authenticated to get his hash (which depends on his ID) and then use it in one of his applications, so it may be a good idea to track the requests server-side in order to check if there's any suspicious usage of your API. You could aswell change your "secret key" regularily (forcing an update of your app though) or define an array with a different key for each day of the year in both your app and server code, so that each individual hashkey will change everyday, recurring each year.

Adding couchdb persistence to a socketio json feed in node

I'm currently researching how to add persistence to a realtime twitter json feed in node.
I've got my stream setup, it's broadcasting to the client, but how do i go about storing this data in a json database such as couchdb, so i can access the stores json when the client first visits the page?
I can't seem to get my head around couchdb.
var array = {
"tweet_id": tweet.id,
"screen_name": tweet.user.screen_name,
"text" : tweet.text,
"profile_image_url" : tweet.user.profile_image_url
};
db.saveDoc('tweet', strencode(array), function(er, ok) {
if (er) throw new Error(JSON.stringify(er));
util.puts('Saved my first doc to the couch!');
});
db.allDocs(function(er, doc) {
if (er) throw new Error(JSON.stringify(er));
//client.send(JSON.stringify(doc));
console.log(JSON.stringify(doc));
util.puts('Fetched my new doc from couch:');
});
These are the two snippets i'm using to try and save / retrieve tweet data. The array is one individual tweet, and needs to be saved to couch each time a new tweet is received.
I don't understand the id part of saveDoc - when i make it unique, db.allDocs only lists ID's and not the content of each doc in the database - and when it's not unique, it fails after the first db entry.
Can someone kindly explain the correct way to save and retrieve this type of json data to couchdb?
I basically want to to load the entire database when the client first views the page. (The database will have less than 100 entries)
Cheers.
You need to insert the documents in the database. You can do this by inserting the JSON that comes from the twitter API or you can insert one status at a time (for loop)
You should create a view that exposes that information. If you saved the JSON directly from Twitter you are going to need to emit several times in your map function
There operations (ingestion and querying) are not the same thing, so you should really do them at the different times in your program.
You should consider running a bg process (maybe in something as simple as a setInterval) that updates your database. Or you can use something like clarinet (http://github.com/dscape/clarinet) to parse the Twitter streaming API directly.
I'm the author of nano, and here is one of the tests that does most of what you need:
https://github.com/dscape/nano/blob/master/tests/view/query.js
For the actual query semantics and for you learn a bit more of how CouchDB works I would suggest you read:
http://guide.couchdb.org/editions/1/en/index.html
I you find it useful I would suggest you buy the book :)
If you want to use a module to interact with CouchDB I would suggest cradle or nano.
You can also use the default http module you find in Node.js to make requests to CouchDB. The down-side is that the default http module tends to be a little verbose. There are alternatives that give you an better API to deal with http requests. The request is really popular.
To get data you need to make a GET request to a view you can find more information here. If you want to create a document you have to use PUT request to your database.

Categories