Get token from URL in Django. TDAmeritrade API Call - django

Ok,
I'm developing a website where I'm using Django. The website is for creating and keep track of stock portfolios. I have the database and the basics of the website set up but I would like to use the TDAmeritrade API in order to get the stock information. How it works is the user is redirected to TD where they enter there Login and Password they accept the terms and get transferred to a redirect page of the local host (until it goes live). Which looks a little like this
"https://127.0.0.1:8000/?code=" with a huge code after the equals sign.
Finally, how would one create the URL destination in Django url.py file and store the code for AUTH Token
I've tried something like this: path('?code=', test_view, name='test'),
but had no luck but that could be because of this error (You're accessing the development server over HTTPS, but it only supports HTTP.)
Thanks in advance!
Side note: I've tried looking up how Paypal does there send back confirmation but all I could find were packages Pre-build for Django

I figured out the solution with the help of Moha369 in the comments, So shout out to him/her!
def home_view(request):
context= {}
user = request.user
if user.is_authenticated:
token = request.GET.get('code')
print(token)
return render(request, "home.html", context)
Django Docs that helped

Related

Django - Prevent a User from Accessing a Page when He/She Typed the URL

I have a page in Django that I don't want to be accessed by anyone except when they clicked the specific link that I made for that page.
I'm aware about #login_required but the problem is I want the page to be restricted to EVERYONE.
I haven't tried any code yet since I absolutely have no idea how to do it. Even google did not give me answer. Please help
I have the same problem a few months back and way I solved it by making a POST request.
Whenever any user clicks on the link present on-page, I make a POST request at the Django application with some verification token sent in the POST request body.
You can generate any simple token mechanism and check for token validity in Django view and if success allows users to access that page.
The most common way to achieve this is to use randomized links.
In pseudo code
Page 1
<a href="/router/some-random-string">
# view serves '/secret-page'
class SecretView:
def _get(request):
# display real page here
def get(request):
return HttpNotFound()
# view serves '/router/<hash:str>'
class AccessorView(SecretView):
def get(request):
# get and validate hash
# if valid, display secret page
return super()._get(request)

Redirect From REST_API Response

I am using Angular and Django in my stack for a website, and after a user registers it emails them a link to activate their account. As of right now everything is working but the link takes the user to the Django rest framework page.
I've been returning responses in my app like this
data = {'success': True, 'message': 'An account has been activated.', 'response': {}}
return Response(data, status=status.HTTP_201_CREATED)
I am curious on how to redirect a user back to the login page which at the current moment would be a localhost page such as http://localhost:4200/#/authentication/login.
From research I have found methods like
return redirect('http://localhost:4200/#/authentication/login')
but I am wanting to keep my responses consistent. Is there a way to redirect a user while still using the rest api Response object?
After thinking about the comment posted by Muhammad Hassan, I realized I was thinking about this all wrong. Instead of sending a Django url I have change the email to send a URL to an Angular page I made and then I just sent an HTTP request from that page to the Django URL.

how to restrict a view function to be executed from website in django?

i have a website developed using django 1.6.0 with python 2.7.5 . In my view.py file i have a method defined which i want to be executed only when request for that view is redirected request from some where. I want to restrict user from executing that view by typing the url.
suppose view.py:
def online_test(request):
return buy_test_final(request)
urls.py:
url(r'^test$',online_test),
i need to restrict access of online_test method from url.
For making that view accessible for only redirected requests, you can check if request.META has HTTP_REFERER or not.
def online_test(request):
if 'HTTP_REFERER' not in request.META:
raise Http404
return buy_test_final(request)
Edit
As Andrew Gorcester has pointed out, in a comment below, that HTTP headers can be manipulated manually. Not only that, someone can simply add a link on any of your website's page by using Chrome's Developer Tools. Like this: Test. If he clicks this link, request.META will have HTTP_REFERER, thereby executing that view.
Use the above piece of code carefully, if you must.

Python Social auth authentication via access-token fails

I am currently developing a serverbackand with Django (1.7) that should handle authentication via social Networks by using python-social-auth.
I followed the Tutorial on this site, which describes the process for a simple Webapp.
This worked perfectly for Google and Twitter login.
Since the Server should be just a REST-FULL Backend I decided to get the Access-Token on the client side and send it to the server.
The server than will authenticate with it. This process should be no problem and is even given as an example in the docs of python-social-auth.
However if I do set everything up I will receive an error that says: "Backend not Found 404".
Here a minimal part of the project:
settings.py: (I also included API_KEY and SECRET)
AUTHENTICATION_BACKENDS = (
#'social.backends.facebook.FacebookOAuth2',
'social.backends.google.GoogleOAuth2',
'social.backends.twitter.TwitterOAuth',
'django.contrib.auth.backends.ModelBackend',
)
views.py (for the authentication view)
from django.contrib.auth import login
from social.apps.django_app.utils import psa
#psa('social:complete')
def register_by_access_token(request, backend):
token = request.GET.get('access_token')
user = request.backend.do_auth(request.GET.get('access_token'))
if user:
login(request, user)
return 'OK'
else:
return 'ERROR'
This i copied strait from the docs and only changed backend.do_auth to request.backend.do_auth. This seems to be an error in the docs.
urls.py:
...
url(r'^register-by-token/(?P<backend>[^/]+)/$', 'register_by_access_token')
...
Also as suggested in the docs.
I just tried to get this working just for google-oauth because there is a simple js-lib that gives you the access-token.
This also worked quite nice and I send a request to
GET http://localhost:8000/register-by-token/google-oauth2/<access-token>/
As described above the return was a 404 Backend not found.
I did a little bit of debugging and found out that the error is raised in the login function not the do_auth() function of the backend.
Therefor the actual authentication process works. I also tried using a random generated string as a token and got an according error, that the user cannot be authenticated.
The funny thing is that the user even has a property backend which holds 'social.backends.google.GoogleOAuth2' as it should.
Thank you if you stayed with me for the long post, and I hope someone has an idea what could be wrong :).
Looking forward to your answers.
In you register_by_access_token view, you are getting access_token in GET params
user = request.backend.do_auth(request.GET.get('access_token'))
and url you defiend is:
url(r'^register-by-token/(?P<backend>[^/]+)/$', 'register_by_access_token')
So you need to request something like:
GET http://localhost:8000/register-by-token/google-oauth2/?access_token=<access_token>
whereas, you are doing:
GET http://localhost:8000/register-by-token/google-oauth2/<access-token>/
You are passing access_token in url params, which is wrong.

How do I make cookie sessions?

I'm trying to make a cookie session and can't find anything thats resembles clear documentation. The django docs on this are very weak!
Alls I found was this guys video on cookies: http://www.youtube.com/watch?v=U_dDY7TvJ4E
Can someone show me how to make a cookie when a visitor goes to my site?
I want be able to save that cookie in my database, so that when they make another request I can associate changes with them server side.
Thanks!
Here is the link for where in the Django Docs on how to make cookies:
https://docs.djangoproject.com/en/dev/topics/http/sessions/
A short example of how to do so would be like so. You can use the built in Session table as a dictionary like so:
def myView(request):
request.session['foo'] = 'bar'
# other view code
render(request, 'mypage.html')
UPDATE:
This is how you would redirect a User based on if they have a Cookie or not
def myViewTwo(request):
id = request.session['UUID1']
# verify the UUID1 exists
if id == 'UUID1:
return render(request, 'cookie.html')
# if not, send them to a normal view
return render(request, 'no_cookie.html')