How to get twitter oAuth token of a logged in user - javascript

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

Related

Safe to call WooCommerce, WordPress and CoCart endpoints in frontend? I need your opinion

Question
I got a question about security. I am building a mobile webshop in Flutter. Is it bad to make those API calls in the frontend? Should I make a separate backend for it in Node for example?
I have also read that you can 'create' your own endpoints in WordPress with PHP. What about that? Does that make it any safer or not?
What endpoints do I use?
There is an existing WooCommerce API to retrieve products, get categories, and create orders on the WooCommerce API. On the CoCart API, you can retrieve the cart, add to the cart, delete the cart, etc...
For the Mollie payment APIs, I think it is better to make a backend.
My take on it
I think it is fine to call those endpoints in the front end. I have seen Flutter packages for WooCommerce to call those endpoints. Yes, I do send the basic auth in the headers... so I am not sure how 'dangerous' that is.
But on the other side. What can the 'hacker' do? They can see all the products, that is fine I guess. I am not sure if they can create orders... They cannot steal money at least :)
Reference code
For reference, here is a piece of code when calling an endpoint:
Future<Product> getProductById(int productId) async {
String basicAuth =
'Basic ' + base64Encode(utf8.encode('$username:$password'));
print(basicAuth);
var response = await http.get(
Uri.parse(
'https://websitename/wp-json/wc/v3/products/${productId}'),
headers: <String, String>{'Authorization': basicAuth});
if (response.statusCode == 200) {
return Product.fromJson(jsonDecode(response.body));
} else {
throw Exception('Failed');
}
}
Let me know your opinion!
When talking about security main question is what goes over the network request. If your username & password from code above is something to keep secret, that can't be on client side.
If you sent code to user, user got it and can check what's happening while tracing network requests.
You can always skip the UI, debug network request and take all the details that were sent over that request and send those requests with cURL or anything else. Yet client must authenticate somehow, and that's a wide topic from "unlisted" URLs where you just need to have exact "random id" to get to the resource (e.g. youtube's or many file sharing services use that as "unlisted" link, which means this won't be in search results but if you have exact link, you will get into the resource) to oAuth2, which you can learn more about here and
you could check this post too which covers several methods of token-based authentication.

Can't correctly obtain OAuth to append to google sheet via Javascript http request

I can't for the life of me append to my google sheet via http request. More specifically I can't seem to get the Oauth formatting right. I don't want/need a uri or prompt for permission as its just me managing my own spreadsheet. First, I was trying with just my api key, but then found out that if you're editing data you need to obtain an access token. That's when I started trying to obtain the token through oauth2 following the TERRIBLE google api documentation. That's where I hit a wall and have just about given up. It's such a simple concept, I just want to add data to my spreadsheet on drive from an online script (housed on scriptr.io), but Google yet again makes things so unneccessarily complicated and don't help matters with their convoluted, misleading, and scattered documentation. Can someone please help me in accomplishing this? Here's where I'm at or what progress I've made thus far.
I've figured out how to correctly format the call to add a row of data to the spreadsheet.
POST https://sheets.googleapis.com/v4/spreadsheets/-/values/Raw%20Data!A1:D1:append?valueInputOption=USER_ENTERED
//Header
Authorization: Bearer {oauth_token}
//Payload
{"range": "Raw Data!A1:D1","majorDimension": "ROWS","values": [["Test", "$15", "2", "3/15/2016"]]}
I know the above works because I've successfully added the data using the OAuth 2.0 Playground. However, when trying it outside of the playground (on a rest client) I keep getting errors trying to obtain the token.
POST https://www.googleapis.com/oauth2/v4/token
scope=https://www.googleapis.com/auth/spreadsheets
client_id=------&
client_secret=-----&
refresh_token=-----&
grant_type=refresh_token&
access_type=offline
I use the client id & client secret from my api console and I use the refresh token I got by authorizing the spreadsheet api in the oauth playground, but the above POST request leads to the following error
Error 400
{
"error": "unsupported_grant_type",
"error_description": "Invalid grant_type: "
}
Can someone please help me figure out how to correctly do this?

Twitter JS API, update status

I'm at a total loss here. I believe I'm right in thinking there is no longer any JS API for twitter which just sucks hugely.
However I realise looking at this I could just use ajax and react to the responses from this:
https://dev.twitter.com/rest/reference/post/statuses/update
OAuth Signature Generator
Example Request POST
https://api.twitter.com/1.1/statuses/update.json?status=Maybe%20he%27ll%20finally%20find%20his%20keys.%20%23peterfalk
However when I post to that url I get the following:
{"errors":[{"code":215,"message":"Bad Authentication data."}]}
Bad Authentication data -> this is very self explanatory: Your Authentication is Bad; in other word, you are not authorized to use that API method.
Since you use POST method, make sure you set your APP access level to Read & Write.
Sign in to apps.twitter.com, and in the Applications Management page for your app, click the Permissions tab. There you can change your access level.
For further reading, please see this answer.

Token google analytics and relationship webPropertyId / profilId

I am currently developing a dashboard with Google Analytics API, which will be accessible website back office. I realized this during this developing javaScript I block on 2 things:
The first is the authentication must be transparent to the user via the use of a token.
In my approach I utlise OAuth2 of the API by generating a token with the playground for this token to be valid
I join my code
gapi.analytics.ready(function() {
var CLIENT_ID = 'XXXX.apps.googleusercontent.com';
var CLIENT_SECRET ='XXX...';
var ACCESS_TOKEN = 'XXX...';
var REFRESH_TOKEN ='XXXX....';
var EXPIRE_IN ='3600';
var TOKEN_TYPE ='Bearer';
var ACCESS_TYPE ='offline';
var SCOPE = 'https://www.googleapis.com/auth/analytics.readonly'
gapi.analytics.auth.authorize({
clientid: CLIENT_ID,
client_secret:CLIENT_SECRET,
serverAuth: {
access_token: ACCESS_TOKEN,
refresh_token: REFRESH_TOKEN,
//token_type: TOKEN_TYPE,
//expires_in: EXPIRE_IN,
//access_type: ACCESS_TYPE,
}
});
After the validity of the data are more accessible with a 401 error (logical because the token is no longer valid)
or to my first question about how to obtain a valid token all the time?
My second question concerns the recovery of data I based on the recovery of the profile number (like many such works).
However SEVERAL of my sites using the tracking number (UA-XXXXXXXX-N).
Knowing that sites use this number is the posibility to find the profilId thanks to the tracking number and accountId that lion can deduct.
But I do not know how to arive.
Es that someone already out how to make this relationship ???
Pending your answers thank you in advance
(Sorry for the translation I utlise google translation)
Authenticating using the playground is a bad idea, and wont work for long. You are going to have to code your own authentication process here. It sounds like you want to do this with your own websites this your own data, I would normally recommend you use a service account. A service account can be set up to authenticate without requiring the user to do anything. While some people say that you can use a Service account with JavaScript, I don't feel that it is a secure solution, I also wonder if it is ok to do this under the current terms of service. So my first recommendation to you is to look into using as service account with a server sided scripting language. say PHP. If you don't a user will have to authenticate and then they will only be seeing the information on there own website not your website.
Second how to find the Profile id:
The first and probably easiest option would be to just go to the admin section of Google analytics and find your profile id there. If you are looking for a way of doing this programmatically you, I would use the account summaries report from the Management API this will give you a list of all of the accounts for the current authenticated user you can then scan that to find the profile ids you want.

sharePoint online count unread message from office365

As part of a project whose aim is to notably improve the visual side of a SharePoint Online site, I'm a bit stuck. On the home page in the left banner, users want to see the number of unread messages they have in Office365.
I created an area in the master page to put the result in. I thought the Rest API used to do this :
$.ajax ({
type: "GET",
url: " https://outlook.office365.com/ews/odata/Me/Folders/Inbox",
dataType : "json",
success : function (resp) {
// count unread messages
},
error : function (e) {
alert (' Error121212 :' + JSON.stringify (e));
}
})
Unfortunately I get an error like cross domain. I tried with JSONP but it does not work either (uncaught syntax error unexpected token).
Can you please tell me if this is a good practice? I feel that it anyways I must find a technic for authentication. (In the case of JSONP I have a popup that asks me authentication and then problem occurs on callback apparently)...
I want to avoid developing a type requiring a typical deployment Wsp...
Thank you in advance for your help.
Your URL for the ajax request seems incorrect. The URL for getting the inbox messages via the API is: https://outlook.office365.com/api/v1.0/me/folders/inbox/messages
Once you get the response, you can count the number of objects with the IsRead property set to false using a simple for loop and display that count.
The issue here is related to CORS and how browsers refuse to handle cross-domain requests. To get around this, typically you would either
Change the response header on the remote server - not an option here
Use some sort of proxy to handle the requests - here's where SharePoint apps come in.
I know you stipulated that you want to avoid using a WSP style deployment but there simply isn't a way around it, you have to use the SharePoint App Model
This article goes a long way to answer your question, but for completion the basic steps are as follows
Create a SharePoint hosted app in Visual Studio
In the App Manifest, you need to define the trust relationship with the remote host (in this case the host of outlook.office365.com) using the AppManifest section
Use SP.RequestExecutor.executor to make the request on your behalf

Categories

Resources