set up gdata in Django to retrieve google contact - python

I'm trying to use gdata in order to get the contact from my users on my site.
so far I have made a pip install gdata.
Then I added on top of my views.py
CLIENT_ID = 'mythingy' # Provided in the APIs console
CLIENT_SECRET = 'mythingy' # Provided in the APIs console
SCOPE = 'https://www.google.com/m8/feeds'
USER_AGENT = 'dummy-sample'
I have a button on my page that doesn nothing but I would like that if you click it it should ask you for persmission then open a pop up with the gmail contact of the user.
I would like to know how to implement htat.
in my views so far I have:
#login_required
def activate_user(request, activation_key):
user = User.objects.get(username=request.user)
profile = user.get_profile()
auth_token = gdata.gauth.OAuth2Token(client_id=CLIENT_ID,client_secret=CLIENT_SECRET,scope=SCOPE,user_agent=USER_AGENT)
APPLICATION_REDIRECT_URI = 'http://127.0.0.1:8000/oauth2callback'
authorize_url=auth_token.generate_authorize_url(redirect_uri=APPLICATION_REDIRECT_URI)
return render_to_response('registration/activation_complete.html',{'user': user,'profile':profile}, context_instance=RequestContext(request))
But this does nothing.
I haven't touch my urls.py or my settings.py
Thank you

I end up using the javascript API. If anyone needs the code let me know

Related

Redirection in django and passing arguments

I spent some time reading through the documentation and forums, but not sure I understand this. I have this bit of code in the views of my app:
def billboard_index(request):
if request.method == 'POST':
form = SpotiForm(request.POST)
if form.is_valid():
date = form.cleaned_data['spotiread_date']
try:
url = 'https://www.billboard.com/charts/hot-100/' + date
billboard = requests.get(url)
billboard.raise_for_status()
except:
print("No response")
else:
soup = BeautifulSoup(billboard.text, 'html.parser')
positions = [int(i.text) for i in soup.find_all(name='span', class_='chart-element__rank__number')]
songs = [i.text for i in soup.find_all(name='span', class_='chart-element__information__song')]
artists = [i.text for i in soup.find_all(name='span', class_='chart-element__information__artist')]
top100 = list(zip(positions, songs, artists))
if Top100model.objects.exists():
Top100model.objects.all().delete()
for position in top100:
top100data = Top100model(
idtop=str(position[0]), artist=str(position[2]), song=str(position[1])
)
top100data.save()
params = {
'client_id': SPOTIPY_CLIENT_ID,
'response_type': 'code',
'redirect_uri': request.build_absolute_uri(reverse('spotiauth')),
'scope': 'playlist-modify-private'
}
query_string = urlencode(params)
url = '{}?{}'.format('https://accounts.spotify.com/authorize', query_string)
return redirect(to=url)
# if a GET (or any other method) we'll create a blank form
else:
form = SpotiForm()
return render(request, 'billboardapp.html', {'form': form})
on billboard_index I have a form with one field in which user puts a date. This date is then used as an input for a webscraper. I save the scraped data in the database, this works (I know this code will break in couple instances, but I'll deal with this later). Next I want to follow the spotify authorization flow, so I redirect to a url at spotify/authorization, it works. This gives me the code back when I'm redirected to spotiauth.html. At the same time, I print there all the database entries that were added during scraping. This is the spotiauth view:
def spotiauth(request):
Positions100 = Top100model.objects.all()
print(request)
context = {
'positions': Positions100,
}
return render(request, 'spotiauth.html', context=context)
I have couple questions:
How do I pass additional arguments to the spotiauth view? I tried
return redirect(to=url, date=date)
But I can't access it in spotiauth view. So I don't really want to pass it in the url, I just want it as an argument to another function, is this doable?
Is this the actual way to go about it? Not sure this is the simplest thing to do.
Thank you for your help!
Authentication is something that should be handled in a generic way, and not individually and explicitly per request. This is because you don't want to duplicate the authentication code in every request that needs authentication.
Lucky you, you are using Django which already comes with an authentication and authorization layer, and a great community that creates great libraries such as django-allauth that integrate OAuth2 authentication into Django's authentication layer.
OAuth2 against Spotify is what you are trying to implement here. Just
include django-allauth via pip,
configure the Spotify provider in the settings following their documentation,
include their URLs for login and registration (see their docs)
... and you should be able to sign into your app using a Spotify account.
For your regular views then, the decorator login_required would then suffice.
Django-allauth will do the following:
for users who sign in via OAuth2 providers, regular Django accounts will be created automatically
you can see these users in the Django admin, in the same list as the regular Django users
you can manage the configuration of the OAuth2 provider configuration via the Django Admin - django-allauth brings a model with an admin for it
django-allauth brings additional functionality like email verification, multiple email address management etc.
If you want to style the login and registration pages, you can implement your own templates using django-allauth's templates as basis.

Page not found http://127.0.0.1:8000/manageAccount/a/delete

I don't know why I get this page because I think all works right. I couldn't identify why the browser gives this error but below url is not worked because user object not get because its redirect on login page but i am going on this url http://127.0.0.1:8000/user_homeview/a/delete its work successfully but user_homeview that template is after login show means homepage i dont know what can i do please tell me:
Page not found http://127.0.0.1:8000/manageAccount/a/delete
Here is my code:
template.html:
Delete Account<Br>
urls.py:
path('<str:username>/delete', delete_user, name='delete-user')
views.py:
def delete_user(request, username):
context = {}
u = User.objects.filter(username=username)
u.delete()
messages.success(request,'your account delete')
return render(request, 'home/login.html', context=context)
Check on your developer tools what is being rendered on your href attribute. I think the url is not being rendered correctly by your current template tag. It should be like this, according to Django's documentation:
Delete Account<Br>
Note that you don't have access to request by default in your templates. If you are deleting a user by its username, the previous code would be:
Delete Account<Br>
as user is accessible by default in your templates.
Be aware that this is not the secure way of deleting users, as anyone with other user's information can access this link to delete accounts. You should use POST requests and check if the user requesting the delete link is the owner of the account.

How do I check authentication across all views in Django using Pyrebase?

Okay so, ordinary Django allows you to simply:
if request.user.is_authenticated:
I want to be able to do the same in Pyrebase. Have the views sort of already know which user has logged in based on the current session without having to sign the user in in all views.
I have tried:
def sign_in(request):
user = firebase.auth().sign_in_with_email_and_password('email', 'password')
user_token = firebase.auth().refresh(user['refreshToken']
request.session['session_id'] = user_token
I noticed this creates a session ID for me. But I don't know how to associate it with the current user and I know it has something to do with the refresh token.
If I don't check authentication, anyone can visit any page of my site without signing in.

How to check user facebook likes/post in django

I need to check if my users liked or posted to pages. I've tried a few of the packages around (facebook_api, django-facebook) but cannot seem to login using my access_token, or get an fql request working.
This will be a cron job, not a page load. The user will not be logged in.
Does anyone have any ideas?
I'm the author of Django Facebook, this is how you could do it:
Implement a registration flow, have a look at the docs.
https://github.com/tschellenbach/Django-facebook
Now that your users can register the database will contain the access_token and facebook id for the users.
In your cronjob you can do things like:
from open_facebook.api import OpenFacebook
graph = OpenFacebook(access_token)
graph.get('%s/likes' % facebook_id)
graph.fql('SELECT ... FROM like WHERE post_id = A and user_id = B')
for a cronjob i would use
graph.batch_fql(dictionary_with_queries) for better performance

Django request.user is empty

Using django, I am authenticating the user through Google. I get the initial request tokens & redirect the user to google for auth. After which google redirects the user back to my website (using the redirect_url I provide).
At this point the request.user.id is None so is request.user.username why is this happening? I need the user ID to enter the access_tokens (that google sends me) into the DB.
Under what conditions can request.user object in Django be empty?
UPDATE1: When I get redirected back from Google with the url pattern as http://mywebsite.com/lserv?s=goog control comes back to my django views function, but django gives me the request.user object user as Anonymous user with no username or id. why?
UPDATE2:
all this is running on python manage.py runserver for now...
UPDATE3: Anybody faced anythn similar to this? basically, out of no reason the user in request clears out automatically & I get assigned as Anonymous user. All this happens between url requests from the user (from browser). Why?
Django's auth mechanism has nothing to do with Google's or any other auth service. If you want to integrate third party auth service with your Django site, you should do it youself.
If you're using oauth2 library, it's README has a section named "Logging into Django w/ Twitter" may help you.
If you are using oauth api from google. To get the user you have to do something like this
from google.appengine.api import oauth
# ...
try:
# Get the db.User that represents the user on whose behalf the
# consumer is making this request.
user = oauth.get_current_user()
except oauth.OAuthRequestError, e:
# The request was not a valid OAuth request.
# ...

Categories

Resources