Problem with Twitter app using python and django - django

I was creating a twitter application with Django. I used the twitter lib from http://github.com/henriklied/django-twitter-oauth for OAuth , as specified in the twitter example pages .
But I am not too sure how to redirect user to my application home page once the authentication with twitter is over .
The code for
oauth_request = oauth.OAuthRequest.from_consumer_and_token(
consumer, http_url=REQUEST_TOKEN_URL
)
oauth_request.sign_request(signature_method, consumer, None)
resp = fetch_response(oauth_request, connection)
token = oauth.OAuthToken.from_string(resp)
oauth_request = oauth.OAuthRequest.from_consumer_and_token(
consumer, token=token, http_url=AUTHORIZATION_URL
)
print(oauth_request.to_url());
oauth_request.sign_request(signature_method, consumer, token)
return oauth_request.to_url()
response = HttpResponseRedirect(auth_url)
request.session['unauthed_token'] = token.to_string()
I even tried passing a "oauth_callback" parameter along with "auth_url" .
But after the authentication , it's not redirecting back to my application which is at
"http://localhost:8000/myApp/twitter/"
Any clues ? Any pointers ?
Thanks
Jijoy

The callback needs to be something like http://local.dev:8080. Twitter doesn't recognize localhost. One thing you probably need to do is go to your etc/hosts file and make sure you add the line 127.0.0.l local.dev

Check if you have enter the callback url in the details of your Twitter App in http://dev.twitter.com/apps.

Related

How to use google contacts api to allow my users to invite their gmail contacts to my django website

I have a website built in django 1.7, python 3.4. I want to enable my users to invite their gmail contacts to my website (like linkedin & many other websites do). I am using Oauth2.0 and am able to get permission to access their contacts. But i am not getting an idea how to proceed and what steps to take.
Can somebody help me to get an overview of all the steps that i need to take and a little explanation as to how to do that.
Even a link to suitable post would be helpful.
See, When you need to implement these features in your website, you will have to understand the APIs etc to utilize it to the fullest.
Go through this https://developers.google.com/google-apps/contacts/v3/?csw=1#audience
Let's talk only about google only. The rest providers can also be managed with similar steps. Here you are using django-allauth for this task.
The basic steps involved are:
Get your app created and configured with the provider. for that you will need a developer profile in google(or facebook etc.). You will have to create an app in google developer console and you will find a plenty of tutorial for this on internet. That has been done by you as you have signup with google activated on your site. That is server side of Oauth2.0
Now you need to define the scope of authorization you need. You might only need the access to view the public profile thing. that may include first name, last name, email, id, gender, etc. For your app, you need contacts of users and for that you will have to include it in the scope too.
That is done in settings.py only.
'google': {'SCOPE': ['profile', 'email', 'https://www.googleapis.com/auth/contacts'],
'AUTH_PARAMS': {'access_type': 'online'}}
}
Now here, you have got the access to the contacts. Now, you only need to extract the contacts with the consent of data owner(user).
For this purpose,you may follow the first link in the answer. What you have to do is you have to send a get request to some url('https://www.google.com/m8/feeds/contacts/default/full' + '?access_token=' + access_token). The request goes to provider only(google) with the authorization token it has provided you for that particular user. That you will find in the db table socialtoken. Once you send proper request, the response you will get is the contacts of the user in xml format.
Once you get it, you can easily parse it to extract the required information.
Things are simple if you understand the flow. django-allauth only helpy you upto signup & signin where you can get different permissions through defining the scope.
For extracting the contacts, you can write your own code.
A simple example is:
def get_email_google(request):
# social = request.user.social_auth.get(provider='google-oauth2')
user =request.user
# Code dependent upon django-allauth. Will change if we shift to another module
# if request.user.userprofile.get_provider() != "google":
a = SocialAccount.objects.get(user=user)
b = SocialToken.objects.get(account=a)
# access = b.token
access_token = b.token
url = 'https://www.google.com/m8/feeds/contacts/default/full' + '?access_token=' + access_token + '&max-results=100'
req = urllib2.Request(url, headers={'User-Agent' : "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/534.30 (KHTML, like Gecko) Ubuntu/11.04 Chromium/12.0.742.112 Chrome/12.0.742.112 Safari/534.30"})
contacts = urllib2.urlopen(req).read()
contacts_xml = etree.fromstring(contacts)
# print
# return render(request, 'search/random_text_print.html', locals())
result = []
for entry in contacts_xml.findall('{http://www.w3.org/2005/Atom}entry'):
for address in entry.findall('{http://schemas.google.com/g/2005}email'):
email = address.attrib.get('address')
result.append(email)
return render(request, 'search/random_text_print.html', locals())
user =request.user
a = SocialAccount.objects.get(user=user)
b = SocialToken.objects.get(account=a)
# access = b.token
access_token = b.token
SCOPES = ['SCOPE_URL']
creds = client.AccessTokenCredentials(access_token, 'USER_AGENT')
service = build('calendar', 'v3', credentials=creds)

How to avoid user having to re-authorize Evernote every time?

I'm building a Python web app with the Evernote API. When users log in they're redirected to a page on the Evernote site to authorize the application. When they come back everything works fine (can see and edit notes etc.)
The challenge now is to avoid having to redirect the user to the Evernote site every time they log on.
I read on the Evernote forums that I need to save the access token and the notestore url to achieve this. I now save these to the users accounts after the first successful authorization.
But how do I use the access token and notestore url to authorize?
I found this sample code on the Evernote website that's supposed to achieve this, but it's in Java and I can't seem to make it work in Python.
// Retrieved during authentication:
String authToken = ...
String noteStoreUrl = ...
String userAgent = myCompanyName + " " + myAppName + "/" + myAppVersion;
THttpClient noteStoreTrans = new THttpClient(noteStoreUrl);
userStoreTrans.setCustomHeader("User-Agent", userAgent);
TBinaryProtocol noteStoreProt = new TBinaryProtocol(noteStoreTrans);
NoteStore.Client noteStore = new NoteStore.Client(noteStoreProt, noteStoreProt);
Basically, if you got the notestore url and access token from a previous authorization, how do you use them to re-authorize?
If you have the access token, you will use that as a constructor argument for the EvernoteClient class.
For example:
client = EvernoteClient(token=your_access_token)
note_store = client.get_note_store()
notebooks = note_store.listNotebooks();
for n in notebooks:
print n.name
For more examples, check out the Python Quick-start Guide.

How to set and get sessionid from Django without web browser

I'm using Django 1.6.
I want to set session id.
When I use web browser, I can watch "sessionid" logs.
But, when I used other application like Unity3d,
I can't watch "sessionid" logs.
Could you tell me how to get a session id?
I've create the view
But, I'm accessing application like unity
it returns.
def get_token(request):
# request_cookies = OrderedDict(request.COOKIES)
context = {}
context.update(csrf(request))
context['csrf_token'] = force_text(context['csrf_token'])
session_key = request.session.session_key
context['sessionid'] = session_key
return HttpResponse(json.dumps(context), content_type="application/json")
But, session id is null. however web broweser is okey.
jsonText: {"csrf_token": "xma9Dtmv46va5uomZiZ9dcjjfCB9E2Gw", "sessionid": null}
Sessions are set using cookies. Cookies are implemented by the vast majority of browser but not by other http clients.
Since you mention Unity, I guess what you are building with Django is an api. I suggest you take a look at http://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication as an alternative to relying on cookies.

Sending email not working on heroku

I have this function in forms.py. There is currently no email specifications in my settings.py.
def send_email(FROM_NAME,FROM,TO,SUB,MSG,EXISTING_EMAIL,EXISTING_PASSWORD):
FROMADDR = "%s <%s>" % (FROM_NAME, FROM)
LOGIN = EXISTING_EMAIL
PASSWORD = EXISTING_PASSWORD
TOADDRS = [TO]
SUBJECT = SUB
msg = ("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n" % (FROMADDR, ", ".join(TOADDRS), SUBJECT) )
msg += MSG+"\r\n"
server = smtplib.SMTP('smtp.gmail.com', 587)
server.set_debuglevel(1)
server.ehlo()
server.starttls()
server.login(LOGIN, PASSWORD)
server.sendmail(FROMADDR, TOADDRS, msg)
server.quit()
I call it my views.py like so
send_email('my_name','from_me#gmail.com','to_som1#gmail.com','my subject','mymessage','my_existing_email#gmail.com','password_to_existing_email')
This works locally. I have tested it with yahoomail and gmail. But when I upload to heroku it gives the error "(535, '5.7.1 Please log in with your web browser and then try again. Learn more at\n5.7.1 support.google.com/mail/bin/answer.py?answer=78754 et6sm2577249qab.8')"
Can anyone help?
You want to use this:
FROMADDR = "%s <%s>" % (your_name, your_email)
You shouldn't be building emails with string interpolation, that's a good way to get your site used to send spam via header injections. See my answer here for details on how to construct emails securely.
Generally speaking, when formatting from addresses, you should use the format Display Name <email#example.com>. See RFC 5322 for details.
Have you read the page linked to in the error message?
If you're repeatedly prompted for your username and password, or if
you're getting an 'invalid credentials' or 'web login required' error,
make sure your password is correct. Keep in mind that password are
case-sensitive.
If you’re sure your password is correct, sign in to your account from
the web version of Gmail instead at http://mail.google.com
In most cases signing in from the web should resolve the issue
Here is what worked for me. After getting the error Please log in with your web browser and then try again. Learn more etc. when trying to send email from my web application, I logged in to the email via browser from my local computer.
After I logged in, there was a yellow notification bar on top which asking me if I want to allow external application access my mail. I confirmed this and Google asked me to log in to the account from the application within the next 10 mins. This will white-list the application.

django socialauth twitter , google oauth , facebook does not work

This is my first post, and I have a problem I could not make it work django OMAB socialauth of three things I just need to google, facebook, and twitter, google works well with open id, but not much twitter and I put in my
settings. py:
TWITTER_CONSUMER_KEY = '00' this is no real
TWITTER_CONSUMER_SECRET = '00' this is no real
FACEBOOK_APP_ID = '' ihave no key
FACEBOOK_API_SECRET = ''
LINKEDIN_CONSUMER_KEY = ''
LINKEDIN_CONSUMER_SECRET = ''
ORKUT_CONSUMER_KEY = ''
ORKUT_CONSUMER_SECRET = ''ihave no key
GOOGLE_OAUTH2_CLIENT_ID = ''
GOOGLE_OAUTH2_CLIENT_SECRET = ''
SOCIAL_AUTH_CREATE_USERS = True
SOCIAL_AUTH_FORCE_RANDOM_USERNAME = False
SOCIAL_AUTH_DEFAULT_USERNAME = 'socialauth_user'
SOCIAL_AUTH_COMPLETE_URL_NAME = 'socialauth_complete'
LOGIN_ERROR_URL = '/login/error/'
#SOCIAL_AUTH_USER_MODEL = 'app.CustomUser'
SOCIAL_AUTH_ERROR_KEY = 'socialauth_error'
GITHUB_APP_ID = ''
GITHUB_API_SECRET = ''
FOURSQUARE_CONSUMER_KEY = ''
FOURSQUARE_CONSUMER_SECRET = ''
LOGIN_URL = '/login-form/'
LOGIN_REDIRECT_URL = '/'
LOGIN_ERROR_URL = '/login-error/'
I am using the example that comes in the zip of OMAB socialauth django , but not working.
When I created my twitter app, I wrote my domain www.sisvei.com , I am testing locally socialauth django ie 127.0.0.1:8000, then sign in with twitter sends me to this url:
http://127.0.0.1:8000/login/error/ and a message saying is the Incorrect authentication service
this happens with facebook and google oauth and oauth2
I'm new to django and I this much work comprising this part of django socialath hopefully help me, thank you very much.
You need to be more specific on "why it doesn't work". Where are you getting the errors?
When debugging a third-party oauth/openid app in Django, generally it boils down to:
configuration & keys - did you make sure to obtain all of the necessary API keys for the services you will be using, and to add them to your configuration?
urls - did you remember to add the necessary urlpatterns to your base urls.py file?
authentication setup on the server - often, you'll need to have a file available or respond with a specific header when the authentication service hits your server. Have you checked to make sure that is set up?
databases - have you run syncdb after installing the app? Are all the tables set up?
templates - if the third party app requires you to set up templates, do you have them set up?
custom views - are you using custom views? If so, try using the built-in views that came with the third party app first, to see if they work
After those are confirmed, you're going to want to be able to see what requests are taking place. Use the debugger included in Chrome/Safari, or get the web developer add-on for Firefox, and look at the network requests as they happen. Do you see HTTP responses other than 200 (say, 404, 500, 403, etc?) those mean that the services aren't responding correctly.
From your error, it looks like you have not correctly set up your callback URL on Twitter. It should be sending you to www.sisvei.com, not 127.0.0.1. Alternatively, check the URL when you get to the Twitter login page -- is the callback URL in the URL, and is it pointing to 127.0.0.1? Then Django is sending it the wrong callback URL.
Finally this:
I wrote my domain www.sisvei.com python does not support this
Is unclear. As far as I know, Python doesn't care what the domain is.
WAIT A MINUTE ...
Are you using runserver? Are you getting the following error?
Error: "www.sisvei.com" is not a valid port number or address:port pair.
If so, there is an easy fix! Just run it like so:
python manage.py runserver www.sisvei.com:80
That should resolve your error if that's what's happening. You're probably running it as
python manage.py runserver 127.0.0.1
127.0.0.1 is a reserved IP address that points back to localhost, your own computer. As a result, it is not possible to use it for authentication or any other purpose outside of programs running on your own machine. See this article for more info.
I'm not sure, but I might be having similar problems, oscar. For me, SocialAuth was generating an AuthenticationURL for facebook, foursquare and hotmail, but not for google, twitter or any of the other address it supports. I think it may be something wrong with the API, so I posted an issue on the social-auth google group...you may want to check there to see if anyone updates!!
https://code.google.com/p/socialauth/issues/detail?id=282&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary%20Modified