Using Only Javascript To Shrink URLs Using The Bit.ly API - javascript

I'm playing a bit with Javascript these days... I was shrinking some URLs using bit.ly to tweet them, then I started to think on a automated process that could use their API to shrink the URLs I wanted, then I looked up on their documentation, and I saw that they only support PHP(with some Javascript), but there is anyway that I could make this using only Javascript?

Here is an example how to get a shortened URL with Bitly API and jQuery, no server side code required.
function get_short_url(long_url, login, api_key, func)
{
$.getJSON(
"http://api.bitly.com/v3/shorten?callback=?",
{
"format": "json",
"apiKey": api_key,
"login": login,
"longUrl": long_url
},
function(response)
{
func(response.data.url);
}
);
}
The following code could be used to get a short URL:
/*
Sign up for Bitly account at
https://bitly.com/a/sign_up
and upon completion visit
https://bitly.com/a/your_api_key/
to get "login" and "api_key" values
*/
var login = "LOGIN_HERE";
var api_key = "API_KEY_HERE";
var long_url = "http://www.kozlenko.info";
get_short_url(long_url, login, api_key, function(short_url) {
console.log(short_url);
});

Depending on where the JavaScript is executing, you could always use the bit.ly REST API:
http://code.google.com/p/bitly-api/wiki/ApiDocumentation
via XmlHttpRequest, for example:
http://api.bit.ly/v3/shorten?login=bitlyapidemo&apiKey=R_0da49e0a9118ff35f52f629d2d71bf07&longUrl=http%3A%2F%2Fbetaworks.com%2F&format=json

From the developer best practises page on bitly:
To ensure the security of your API key and/or OAuth access token, we strongly suggest that you make requests to the bitly API server-side whenever possible.
Any requests to the bitly API made via client-side Javascript present the risk of your OAuth token or API key being compromised, but there are steps you can take to partially mitigate this risk. Most importantly, never include your api_key or access_token inline in the page. Keep any references to your api_key or access_token in code that is contained in external javascript files which are included in the page. For additional security, don't have the key or token itself contained anywhere in your javascript code, but rather make an ajax call to load it, and keep it in a variable stored in a privately scoped method. For an example of this implementation, please see our sample html and included javascript files.

Related

Making POST request from ReactJS app built on WordPress

I'm building a ReactJS app on top of a WordPress backend. The React App is running on the same domain, embedded in the WordPress site. Most of the tutorials I've been following cover how to get data from WordPress to React. I've been successful at this, but need to figure out how to submit data from my React app to WordPress (preferably via the REST API).
This will be a custom admin page for logged in editors, either available in the admin panel or from the front-end.
As an example to create a post, I'm naively trying the following function:
saveGrid() {
const url = "/wp-json/wp/v2/posts";
const body = JSON.stringify({
"title":"internet",
"content":"teapot"
});
fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body:body
});
}
I get back a 401 unauthorized response. What is the easiest way to authorize myself for a POST submission (secure solution preferred)?
It looks like you're on the right track.
A quick read of this: https://apppresser.com/wp-api-post-submission/
shows me that all you're missing is a "nonce" in order for the WP API to recognise and validate your request successfully.
In the guide above, the dev created a JS written in JQuery that sends XHR/AJAX requests to the WP API and in their plugin.php they enqueue and localize the script with some variables from WP to help with the request inside the JS.
The takeaway here is that they used wp_create_nonce('wp_rest')and assigned this to a localized variable nonce so they could easily reference that later inside the JS and assign nonce to their X-WP-Nonce header inside the request!
If you look into this further you might find a suitable alternative for you that will work as I'm not entirely sure how you're loading your JSX files but this guide may come in handy for you to enqueue your JSX scripts/files: http://blog.milandinic.com/2015/12/01/using-react-jsx-in-wordpress/
More information
https://codex.wordpress.org/Function_Reference/wp_localize_script
https://developer.wordpress.org/reference/functions/wp_enqueue_script/
I was able to solve this problem by, instead of having a straight post request from React, using a Jquery AJAX submission outside of React that uses data from a form inside React. This caused the request to contain the necessary cookies (I don't understand exactly why this is the case)

How to Call a Firebase Authenticated Cloud Endpoint from Javascript?

I've written several Google Cloud Endpoints in Python and have followed the directions to require that calls to them come from users authenticated using Firebase. I need to call my Endpoints from a web app using JavaScript, but I can't seem to get the authentication working.
I'd like to use the Google APIs client (gapi) which comes with the added benefit of dynamically generating the client library from a provided discovery document. When I try using the gapi client, I can make the call to my API just fine, but I get an HTTP 401 as a response, along with the HTTP unauthorized message that my python source returns.
Google's documentation on the subject is rather sparse. I gather from one tutorial on the subject that a standard Ajax call can be used, but I don't see any documentation on how to call a Firebase authenticated endpoint from Gapi. My current concern is that the gapi client may not be set up (yet) to allow for the use of a discovery doc and also allow for the Authorization header to be set as Firebase Auth requires.
Is what I'm attempting even possible?
Any suggestions would be appreciated. Perhaps calling a Firebase Authenticated endpoint isn't possible using the gapi client.
Here's a rough outline of my gapi js code:
function(token) {
gapi.client.init({
apiKey: 'MY_API_KEY',
discoveryDocs: [MY_DISCOVERY_DOC_URL'],
clientId: 'MY_WEB_CLIENT_ID',
scope: 'profile'
}).then(function(){
return gapi.client.my.server.api.call();
}).then(function(response){
console.log(response.result.data)
}, function(reason){
console.log('Error: ' + reason.result.error.message)
});
}
I have been struggling with this for a while now and finally made it work. I found two options:
Option 1) If you want to use the gapi.client library:
There is a method called gapi.client.setToken(tokenObject) - documentation
However, it seems to be new (July '17) and little documentation or examples are available. I made it work doing the following (this is in angularJS with angular-fire but I hope you get what I am doing, basically ignore the "$scope")
// any time auth state changes, add the user data to scope
$scope.auth.$onAuthStateChanged(function (firebaseUser) {
$scope.firebaseUser = firebaseUser;
$scope.idToken = null;
// get the token from the firebase User Object
// Note that getToken() is deprecated and for me it did not work as desired
// use getIdToken() instead
firebaseUser.getIdToken().then(function (idToken) {
$scope.idToken = idToken;
});
});
// Now you can use setToken
// If from the docs you were thinking firebase's getIdToken() gives me TokenObject and gapi's setToken()
// expects a TokenObject so I'll just pass it - you'd be wrong! (at least for me - if it works for you please give me a heads up)
// You'll need to build your own token:
var homemadeToken = {
access_token: $scope.idToken.toString() // This feels so wrong
};
gapi.client.setToken(homemadeToken);
gapi.client.yourapi.getSomething().execute(function (resp) {
// Do stuff with the response
}
);
Option 2) Use jQuery's Ajax request - documentation
$.ajax(backendHostUrl + '/_ah/api/yourapi/v1/someendpoint', {
headers: {
'Authorization': 'Bearer ' + $scope.idToken // Here it worked without making a string first but I did not check why
},
method: 'GET',
success: function (resp) {
// Do stuff with the response
}
});
If after all of that your backend is still not accepting the tokens and you have migrated from endpoints v1 to v2, it might help migrating again as described here. Esp. make sure the lib folder is created again.
Even after SDK updates, I noticed that if and once you migrated from v1 to v2 the "lib" folder is never updated regardless of whether or not it hase been updated.
Still not working?
This github page fixes the issue on the BACKEND side for an earlier version - the backend did not accept firebase tokens and needed to be hacked. If you want to apply the changes as described there and you are using the latest "lib" folder's (writing in July '17) users_id_token.py as per migration guide, note that the file has changed and you need to go against the explicit commentary in that file's _verify_signed_jwt_with_certs method:
# Formerly we would parse the token body here.
# However, it's not safe to do that without first checking the signature.
and parse the token before checking the signature. From that file's comments it can be inferred however, that Google plans to put the entire logic elsewhere - hopefully firebase friendly and safely.

How to handle OAuth access tokens

I have been exploring a couple of OAuth API's lately and bumped into an API that requires my page's code to handle and access token. I used the following in the HTML for example:
<script>
var client = thisapi.createClient({
accessToken: '0b7f6x59a0'
})
</script>
I am able to make calls to the API and retrieve the kind of data I need as long as I can access this token on my page. But it is exposed to the public. So how can I hide this kind of information?

Google OAuth WildCard Domains

I am using the google auth but keep getting an origin mismatch. The project I am working has sub domains that are generated by the user. So for example there can be:
john.example.com
henry.example.com
larry.example.com
In my app settings I have one of my origins being http://*.example.com but I get an origin mismatch. Is there a way to solve this? Btw my code looks like this:
gapi.auth.authorize({
client_id : 'xxxxx.apps.googleusercontent.com',
scope : ['https://www.googleapis.com/auth/plus.me',
state: 'http://henry.example.com',
'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile'],
immediate : false
}, function(result) {
if (result != null) {
gapi.client.load('oath2', 'v2', function() {
console.log(gapi.client);
gapi.client.oauth2.userinfo.get().execute(function(resp) {
console.log(resp);
});
});
}
});
Hooray for useful yet unnecessary workarounds (thanks for complicating yourself into a corner Google)....
I was using Google Drive using the javascript api to open up the file picker, retrieve the file info/url and then download it using curl to my server. Once I finally realized that all my wildcard domains would have to be registered, I about had a stroke.
What I do now is the following (this is my use case, cater it to yours as you need to)
On the page that you are on, create an onclick event to open up a new window in a specific domain (https://googledrive.example.com/oauth/index.php?unique_token={some unique token}).
On the new popup I did all my google drive authentication, had a button to click which opened the file picker, then retrieved at least the metadata that I needed from the file. Then I stored the token (primary key), access_token, downloadurl and filename in my database (MySQL).
Back on step one's page, I created a setTimeout() loop that would run an ajax call every second with that same unique_token to check when it had been entered in the database. Once it finds it, I kill the loop and then retrieve the contents and do with them as I will (in this case I uploaded them through a separate upload script that uses curl to fetch the file).
This is obviously not the best method for handling this, but it's better than entering each and every subdomain into googles cloud console. I bet you can probably do this with googles server side oauth libraries they use, but my use case was a little complicated and I was cranky cause I was frustrated at the past 4 days I've spent on a silly little integration with google.
Wildcard origins are not supported, same for redirect URIs.
The fact that you can register a wildcard origin is a bug.
You can use the state parameter, but be very careful with that, make sure you don't create an open redirector (an endpoint that can redirect to any arbitrary URL).

How to get twitter oAuth token of a logged in user

I'm trying to set up a javascript function to post a status to a twitter account using POST statuses/update, details here: https://dev.twitter.com/docs/api/1/post/statuses/update. The goal is a Twitter post similar to the open graph actions on Facebook.
I'm using jQuery ajax to make the post request, here's what I have so far:
$.ajax
({
type: "POST",
url: "https://api.twitter.com/1/statuses/update.json",
headers: jsonData,
data: {},
dataType: "jsonp",
success: function( data )
{
}
});
I believe that I need to generate a header something like this for security:
Authorization: OAuth oauth_consumer_key=consumerKey, oauth_nonce=nonce,
oauth_signature=signature, oauth_signature_method="HMAC-SHA1",
oauth_timestamp=timestamp, oauth_token=userToken, oauth_version="1.0"
I have the consumer key for my app, I can generate a nonce, I'm generating the signature and timestamp using the methods from this question Twitter OAuth authentication in javascript. The only thing I have left is th oauth_token, which I believe is the token of the user whose feed I wish to post to. Please correct me if I'm wrong about that.
The problem is, I have absolutely no idea how to get this token from the user in order to post to their feed. I've spent the last 2 hours running around in circles through Twitter's oAuth documention without finding anything that looked useful; everything I've found was either flowcharts with no code examples or predicated on my code already having the user's oAuth token.
My question is this: how can I get the logged in user's oAuth token using javascript?
If that is not possible, I have another page where I am currently storing the user's twitter id in the database with their permission, getting their token and databasing it in PHP would also be satisfactory, assuming it doesn't change very frequently.
In order to obtain the oauth_token you need to follow the authentication process. Your application needs to be authorized to act on the behalf of the user.
I would recomend to take some time first and learn how OAuth exactly works (there is a lot of information available) and then implement it in your app. (http://hueniverse.com/oauth/)
You could also benefit from a library which will make your life easier. (in your case, look at: https://dev.twitter.com/docs/twitter-libraries#php).
Hope this has been useful.
Here is example for get twitter oauth token and post tweet in twitter .
Code sample is in php .
http://www.phpgang.com/how-to-post-tweet-on-twitter-with-php_414.html
1) to obtain the oauth token you need to follow the authentication process.
2) and your application needs to be authorized to act on the behalf of the user.
you can also see this twitter example for better understanding how it works
In this use can see the process of authorized user and post and get json result.
https://dev.twitter.com/rest/tools/console
I hope this will help you.
thanks

Categories

Resources