Migrating from twitter anywhere api - django

I m using twitter anywhere api for allowing user to sign in with twitter and get their twitter data to store it my table.Since twitter anywhere api is going to expire soon how can i migrate this functionality to oauth.
my javascript:
<script src="https://platform.twitter.com/anywhere.js?id={{twitterappid}}&v=1"></script>
<script type="text/javascript">
var twt_connected = 0;
var Uuid = '2334443224';
$(function(){
if ($('#twtlogin').length) {
// do something
twttr.anywhere(function(twitter) {
if(twitter.isConnected()){
//alert('Welcome, you are connected');
currentUser = twitter.currentUser;
screenName = currentUser.data('screen_name');
jQuery.ajax({url:"/twitter/Uuid="+Uuid+"/" ,
type: "POST",
data: {user: JSON.stringify(currentUser) },
dataType: "json",
success: function(result) {
}});
document.getElementById("twtlogin").innerHTML = '<img src="/images/icon_tconnected.gif" width="153" height="37" alt="Connected" />';
}
});
}
});
$("#login").click(function(e){
e.preventDefault();
if (twt_connected == 0){
$.post("/twt-click-time/Uuid="+Uuid+"/","clicked",function(data){})
twttr.anywhere(function (T) {
T.bind("authComplete", function (e, user) {
document.getElementById("twtlogin").innerHTML = '<img src="/images/icon_tconnected.gif" width="153" height="37" alt="Connected" />';
twt_connected = 1;
currentUser = T.currentUser;
screenName = currentUser.data('screen_name');
jQuery.ajax({url:"/twitter/Uuid="+Uuid+"/" ,
type: "POST",
data: {user: JSON.stringify(currentUser) },
dataType: "json",
success: function(result) {
}});
});
T.signIn();
});
}
});
</script>
I m using django at my backend.

I'm doing this right now for flask. The easiest option is just to plug-in some server side oauth calls.
It's a reasonably large amount of code so I won't copy and paste the whole thing here, but the github page for simplegeo's oauth2 actually has a "logging into django with twitter" walkthrough that should help out.
After having gone through a few options, I think I like twython best. It's just this to do the first step of the oauth:
from twython import Twython
t = Twython(app_key='key',
app_secret='secret',
callback_url='http://google.com/')
auth_props = t.get_authentication_tokens()
print auth_props

Related

Get data from one site collection into another site collection in same web application sharepoint 2016

I am using SharePoint 2016 on premise. I am having one web application in which i am having 2 site collections.
site 1 and site 2.
I want to show data from site collection 1 list on site collection 2 Page, using rest or java script or J query. My environment is not configured with apps so i can't use apps and even server side code as well.
Please suggest any alternatives for doing this.
Thanks in advance.
Share the script here in case someone have similar requirement.
<script>
$(function () {
getDataFromSite1();
getDataFromSite2();
})
function getDataFromSite1() {
var url = "http://sp:12001/_api/web/lists/GetByTitle('MyList')/items";
$.ajax({
async: false,
url: url,
method: "GET",
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose"
},
success: function (data) {
console.log(data)
},
error: function (data) {
}
});
}
function getDataFromSite2() {
var url = "http://sp:12001/sites/team/_api/web/lists/GetByTitle('MyList')/items";
$.ajax({
async: false,
url: url,
method: "GET",
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose"
},
success: function (data) {
console.log(data)
},
error: function (data) {
}
});
}
</script>

401 error while uploading file to Sharepoint 2013 using REST API

I have a simple html form where i have request is built to upload a file to Sharepoint Server 2013 using REST ( taken reference of the Code from the net ) .
Following is the code snippet
<html>
<head>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js" type="text/javascript"></script>
<script>
function AddAttachments()
{
var digest = "";
$.ajax(
{
url: "http://vmjnjlabeling01:22216/as/Shared Documents/_api/contextinfo",
method: "POST",
headers: {
"ACCEPT": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"Authorization" : "Basic c3AyMDEzOlNoYXJlcG9pbnRAMjAxMw=="
},
success: function (data) {
digest = data.d.GetContextWebInformation.FormDigestValue;
},
error: function (data) {
}
}).done(function() {
var fileInput = $('#uploadFile');
var fileName = fileInput[0].files[0].name;
var reader = new FileReader();
reader.onload = function (e) {
var fileData = e.target.result;
var res11 = $.ajax(
{
//url: "http://vmjnjlabeling01:22216/as/_api/web/lists/getbytitle('DocTest')/items(1)/AttachmentFiles/ add(FileName='" + fileName + "')",
url:"http://vmjnjlabeling01:22216/as/_api/web/getfolderbyserverrelativeurl('/as/Shared Documents')/Files/add(overwrite=true, url='" + fileName + "')",
method: "POST",
binaryStringRequestBody: true,
data: fileData,
processData: false,
headers: {
"ACCEPT": "application/json;odata=verbose",
"X-RequestDigest": digest,
// "content-length": fileData.byteLength
},
success: function (data) {
},
error: function (data) {
alert("Error occured." + data.responseText);
}
});
};
reader.readAsArrayBuffer(fileInput[0].files[0]);
});
}
</script>
</head>
<body>
<div>
<input id="uploadFile" type="file">
</div>
<div>
<input type="submit" onclick="AddAttachments()" value="Add Attachments"> </input>
</div>
</body>
</html>
But when i upload the document i am getting the 401 Error everytime despite all permissions have been given .
Please find the screenshot :
Any help on this topic to resolve this issue is most appreciated.
Regards,
N
You need to enable Basic Authentication credentials are sent in clear text in Authentication Providers.
Goto
Central Admin>> Security>>Security Authentication providers>>
In Right side dropdown select the Application and click on default
Tick Basic Authentication in Claims Authentication Types
Because your page isn't inside SharePoint (you're not getting any "SharePoint" in it), you'll need to authorize differently than if it were a SharePoint page. The easiest answer is probably to look at how the Add-in model works. On the other hand, since there's nothing going on in the page other than your attempt to upload an attachment, could the page be a SharePoint page?

Got CSRF verification failure when while requesting POST through API

I'm writing a site using REST API. I use django with piston at backend (also using corsheaders.middleware.CorsMiddleware with CORS_ORIGIN_ALLOW_ALL = True). And I use backbone.js for frontend. I'm sending POST request from client-side and get error:
CSRF verification failed. Request aborted.
I've googled a lot and all solutions suggested something like "Use the render shortcut which adds RequestContext automatically". But I have no view, forms will be requested from frontend, that shouldn't know about how backend works. Here's code of my scipt
Question = Backbone.Model.extend({
urlRoot: 'http://example.com/api/questions',
defaults: {
id: null,
title: '',
text: ''
},
initialize: function() {
//alert(this.title);
}
});
var question2 = new Question;
var questionDetails = {title: 'test title', text: 'test text'};
question2.save(questionDetails, {
success: function(question) {
alert(question.toJSON());
}
});
The django docs have instructions on how to set up jquery to send the csrf token via ajax.
https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax
You should make sure that the template tag {% csrf_token %} renders something in your frontend. That way you know that the token is being created and passed to the frontend. If you follow the instructions from the docs above then your csrf token should always be sent with ajax requests. This is what the javascript looks like for one of my sites (assuming you are using jQuery).
// Set up Django CSRF Token Protection
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
crossDomain: false, // obviates need for sameOrigin test
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type)) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
Also, make sure that 'django.middleware.csrf.CsrfViewMiddleware' is in your MIDDLEWARE_CLASSES settings.
Sounds like you need to pass the CSRF token through with your save request.
One solution would be to pass the CSRF token back to the model requesting it, then override your model's save method ensuring the model passes the CSRF token back with it.
Question = Backbone.Model.extend({
urlRoot: 'http://example.com/api/questions',
defaults: {
csrf: null,
id: null,
title: '',
text: ''
},
initialize: function() {
//alert(this.title);
}
save: function( data, options ){
data = $.extend( true, {
csrf: this.get( 'csrf' )
}, data );
options = _.extend( options, {
error: onError,
success: onSuccess
} );
// Call super method.
Backbone.Model.prototype.save.apply( this, [ data, options ] );
}
});

Automated facebook post to wall with Javascript

I have a facebook application in which the user is authenticated with PHP and grants permissions to the app, including publish_stream.
During the application, the user is going through several screens.
On the last screen, the is user chooses if they want to share a post on their wall.
If they do, an automated and formatted post should be posted on their wall.
I've tried to do it with Javascript but it didn't work. Can you see what's wrong?
Thanks!
Here's my code:
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'MY APP ID',
status : true,
cookie : true,
xfbml : true
});
};
(function() {
var e = document.createElement('script');
e.src = 'http://connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
</script>
<script>
function postToFacebook() {
var body = '';
var params = {};
params['message'] = 'MESSAGE';
params['name'] = 'NAME';
params['description'] = '';
params['link'] = '';
params['picture'] = 'https://www.URL.com/pic.jpg';
params['caption'] = 'CAPTION';
FB.api('/me/feed', 'post', params, function(response) {
if (!response || response.error) {
// alert('Error occured');
} else {
// alert('Post ID: ' + response);
}
});
}
</script>
From reading your question and the various comments it seems to me that the users session information is not persisting into the JavaScript SDK - this assumes that there is a valid user session being maintained serverside.
First of all you should check that you are using the most up to date PHP SDK. To double check download and install the latest version from GitHub.
I think this should solve your problem as the cookies containing the authorised users session data should be passed between the PHP and JavaScript SDKs.
If that doesn't work I have a suspicion that the user is not being authenticated correctly serverside. In which case you could try the following.
Before you postToFacebook() you should check the users the users logged in status and log them in if necessary. For example:
FB.getLoginStatus(function(response) {
if (response.authResponse) {
// logged in and connected user, someone you know
postToFacebook();
} else {
// no user session available, someone you dont know
FB.login(function(response) {
if (response.authResponse) {
// logged in and connected user
postToFacebook();
} else {
// User cancelled login or did not fully authorize
}
}, {scope: 'YOUR,REQUIRED,PERMISSIONS'});
}
});
You are not calling the function postToFacebook()!
window.fbAsyncInit = function() {
FB.init({
appId : 'MY APP ID',
status : true,
cookie : true,
xfbml : true
});
postToFacebook();
};
When you attempt to do this:
FB.api('/me/feed', 'post', params, function(response) { .. });
You need to pass the access token along with the call. I assume you have it on the php/server side, so then:
FB.api('/me/feed/access_token='[INSERT_ACCESS_TOKEN], 'post', params, function(response) { .. });

"CSRF token missing or incorrect" while post parameter via AJAX in Django

I try to post parameter like
jQuery.ajax(
{
'type': 'POST',
'url': url,
'contentType': 'application/json',
'data': "{content:'xxx'}",
'dataType': 'json',
'success': rateReviewResult
}
);
However, Django return Forbidden 403. CSRF verification failed. Request aborted.
I am using 'django.middleware.csrf.CsrfViewMiddleware' and couldn't find how I can prevent this problem without compromising security.
You can make AJAX post request in two different ways:
To tell your view not to check the csrf token. This can be done by using decorator #csrf_exempt, like this:
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def your_view_name(request):
...
To embed a csrf token in each AJAX request, for jQuery it may be:
$(function () {
$.ajaxSetup({
headers: { "X-CSRFToken": getCookie("csrftoken") }
});
});
Where the getCookie function retrieves csrf token from cookies. I use the following implementation:
function getCookie(c_name)
{
if (document.cookie.length > 0)
{
c_start = document.cookie.indexOf(c_name + "=");
if (c_start != -1)
{
c_start = c_start + c_name.length + 1;
c_end = document.cookie.indexOf(";", c_start);
if (c_end == -1) c_end = document.cookie.length;
return unescape(document.cookie.substring(c_start,c_end));
}
}
return "";
}
Also, jQuery has a plugin for accessing cookies, something like that:
// set cookie
$.cookie('cookiename', 'cookievalue');
// read cookie
var myCookie = $.cookie('cookiename');
// delete cookie
$.cookie('cookiename', null);
The simplest way I have found is to include the {{csrf_token}} value in the data:
jQuery.ajax(
{
'type': 'POST',
'url': url,
'contentType': 'application/json',
'data': {
'content': 'xxx',
'csrfmiddlewaretoken': '{{ csrf_token }}',
},
'dataType': 'json',
'success': rateReviewResult
}
);
It took me a while to understand what to do with the code that Daniel posted. But actually all you have to do is paste it at the beginning of the javascript file.
For me, the best solution so far is:
Create a csrf.js file
Paste the code in the csrf.js file
Reference the code in the template you need it
<script type="text/javascript" src="{{ STATIC_PREFIX }}js/csrf.js"></script>
Notice that STATIC_PREFIX/js/csrf.js points to my file. I am actually loading the STATIC_PREFIX variable with {% get_static_prefix as STATIC_PREFIX %}.
Advanced tip: if you are using templates and have something like base.html where you extend from, then you can just reference the script from there and you don't have to worry anymore in there rest of your files. As far as I understand, this shouldn't represent any security issue either.
Simple and short
$.ajaxSetup({
headers: { "X-CSRFToken": '{{csrf_token}}' }
});
OR
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", '{{csrf_token}}');
}
}
});
docs
For lack of a straight forward answer, you just have to add the header X-CSRFToken to the ajax request which is in the cookie csrftoken. JQuery doesn't do cookies (for some reason) without a plugin so:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
and the minimal code change is:
$.ajax({
headers: { "X-CSRFToken": $.cookie("csrftoken") },
...
});
The fastest solution without any plugins if you are not embedding js into your template is:
Put <script type="text/javascript"> window.CSRF_TOKEN = "{{ csrf_token }}"; </script> before your reference to script.js file in your template, then add csrfmiddlewaretoken into your data dictionary:
$.ajax({
type: 'POST',
url: somepathname + "do_it/",
data: {csrfmiddlewaretoken: window.CSRF_TOKEN},
success: function() {
console.log("Success!");
}
})
If you do embed your js into the template, it's as simple as: data: {csrfmiddlewaretoken: '{{ csrf_token }}'}
I got the same issue yesterday and thought it would help people if there were a simple way to handle it, so I wrote a jQuery plugin for that: jquery.djangocsrf. Instead of adding the CSRF token in every request, it hooks itself on the AjaxSend jQuery event and adds the client cookie in a header.
Here’s how to use it:
1- include it:
<script src="path/to/jquery.js"></script>
<script src="path/to/jquery.cookie.js"></script>
<script src="path/to/jquery.djangocsrf.js"></script>
2- enable it in your code:
$.djangocsrf( "enable" );
Django always add the token in a cookie if your template uses {% csrf_token %}. To ensure it always adds it even if you don’t use the special tag in your template, use the #ensure_csrf_cookie decorator:
from django.views.decorators.csrf import ensure_csrf_cookie
#ensure_csrf_cookie
def my_view(request):
return render(request, 'mytemplate.html')
Note: I’m using Django 1.6.2.
Thank you everyone for all the answers. I am using Django 1.5.1. I'm a little late to the party, but here goes.
I found the link to the Django project to be very useful, but I didn't really want to have to include the extra JavaScript code every time I wanted to make an Ajax call.
I like jerrykan's response as it is very succinct and only adds one line to an otherwise normal Ajax call. In response to the comments below his comment regarding situations when Django template tags are unavailable, how about loading up the csrfmiddlewaretoken from the DOM?
var token = $('input[name="csrfmiddlewaretoken"]').prop('value');
jQuery.ajax({
type: 'POST',
url: url,
data: { 'csrfmiddlewaretoken': token },
dataType: 'json',
success: function(data) { console.log('Yippee! ' + data); }
});
EDIT March 2016
My approach to this issue over the past few years has changed. I add the code below (from the Django docs) to a main.js file and load it on every page. Once done, you shouldn't need to worry about the CSRF token with ajax again.
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
Include x-csrftoken header in request:
var token = $('input[name="csrfmiddlewaretoken"]').prop('value');
jQuery.ajax({
type: 'POST',
url: url,
beforeSend : function(jqXHR, settings) {
jqXHR.setRequestHeader("x-csrftoken", get_the_csrf_token_from_cookie());
},
data: data,
dataType: 'json',
});
If, after reading other answers, someone is still struggling please try this:
$.ajax({
type: "POST",
beforeSend: function (request)
{
request.setRequestHeader("X-CSRF-TOKEN", "${_csrf.token}");
},
url: servlet_path,
data : data,
success : function(result) {
console.log("Success!");
}
});
Please not that when doing it this way make sure you don't have the {% csrf_token %} inside the <form></form> tags. Then as explained here add the following code to your javascript
function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
const csrftoken = getCookie('csrftoken');
// using js fetch
// https://docs.djangoproject.com/en/3.1/ref/csrf/#setting-the-token-on-the-ajax-request
const request = new Request(
/* URL */,
{headers: {'X-CSRFToken': csrftoken}}
);
fetch(request, {
method: 'POST',
mode: 'same-origin' // Do not send CSRF token to another domain.
}).then(function(response) {
// ...
});
Just want to put it out here that if GET works in your use case, then it wouldn't need the CSRF token. For my use case, using GET was OK.
html
<form action="">
{% csrf_token %}
</form>
JS
<script>
const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;
const request = new Request(
'url_here',
{headers: {'X-CSRFToken': csrftoken}}
);
fetch(request, {
method: 'POST',
// mode: 'same-origin' optinal // Do not send CSRF token to another domain.
}).then(function(response) {
console.log(response);
});
</script>
reference link for more detail
As a summary for my mistakes:
Don't forget to set the request content type.
Get the csrf value, either from
The template {{ csrf_token }}
The cookie, use the snippet in django site
NB. The default cookie name is csrftoken, but can be overriden by CSRF_COOKIE_NAME setting.
The DOM, if you can't access the cookie (you set CSRF_USE_SESSIONS or CSRF_COOKIE_HTTPONLY to True)
document.querySelector('[name=csrfmiddlewaretoken]').value;
Set the request header, I'am using XMLHttpRequest
const Http = new XMLHttpRequest();
Http.setRequestHeader("X-CSRFToken", CSRF_VALUE);
Http.setRequestHeader("X_CSRFTOKEN", CSRF_VALUE);
The header name is managed by CSRF_HEADER_NAME setting, which its default is HTTP_X_CSRFTOKEN.
But: "The header name received from the server is normalized by converting all characters to uppercase, replacing any hyphens with underscores, and adding an 'HTTP_' prefix to the name" src.
So, If you set the HTTP_X_CSRFTOKEN header, Django will convert it to HTTP_HTTP_X_CSRFTOKEN which wis incorrect name and will raise CSRF missed error.
Http.setRequestHeader("X-CSRFToken", csrftoken); // This worked
Http.setRequestHeader("X-CSRFTOKEN", csrftoken); // Also this
Http.setRequestHeader("HTTP-X-CSRFToken", csrftoken); // Not working
Http.setRequestHeader("HTTP_X_CSRFTOKEN", csrftoken); // Not Working
Http.setRequestHeader("X_CSRFTOKEN", csrftoken); // Not working !!
Don't use url in ajax that is different than that of the browser 127.0.0.1 & localhost are not the same !!
No need to set data.append("csrfmiddlewaretoken", csrftoken); in the request body, As I know.