These are chat archives for django/django

3rd
Jun 2017
:]
@elcolie
Jun 03 2017 05:16
@annshress Oh. Yes. Thank you
Kaushal Kumar
@kaushal087
Jun 03 2017 12:13
Hi guys, I have implemented 'Login with Facebook' in my project using python social auth. When I click the login link it takes some time. Before logging in and redirecting to the next page I want to show loading icon. I have tried this using jquery but Its not working maybe because python social auth is overriding dom events (I am not sure). Any idea how I can do this? Thanks!
azaleas
@azaleas
Jun 03 2017 12:34
@TheDeveloperTom, of course there are:D
Syed Zeeshan
@syedzeeshan1
Jun 03 2017 12:57
@kaushal087 Hey! PM me
selected-pixel-jameson
@selected-pixel-jameson
Jun 03 2017 15:38
Hey everyone. I’m looking for some help with a Django REST API project that my company (selectedpixel.com) is currently contracting. If you have any interest in working as a contractor with me please send me a PM so we can chat! Cheers.
Hubert
@hubert10
Jun 03 2017 15:38
Hello? I wouls like to join you guys as a young and new python developer
Costantin
@Cosbgn
Jun 03 2017 15:46
Hello everyone
is here someone who already worked with a divided frontend and django rest api on the backend?
I can make everything work apart of post requests
I would love to know how you solved the issue
:]
@elcolie
Jun 03 2017 15:48
@Cosbgn Yes
Costantin
@Cosbgn
Jun 03 2017 15:51
@elcolie Thanks for jumping in!
So I have my API setup as this:
class ContactFormPost(CreateAPIView):
    queryset = ContactForm.objects.all()
    serializer_class = ContactFormSerializer
from django admin I can make success full post requests
:]
@elcolie
Jun 03 2017 15:52
Sure
Costantin
@Cosbgn
Jun 03 2017 15:52
On my one page app I take the token like this:
<meta name="_token" content="{{ csrf_token }}">
:]
@elcolie
Jun 03 2017 15:53
No. You are confusing
Costantin
@Cosbgn
Jun 03 2017 15:53
what you mean?
:]
@elcolie
Jun 03 2017 15:53
csrf_token is being used when you use with ordinary django view
CreateAPIView is a part of Django REST framework
Costantin
@Cosbgn
Jun 03 2017 15:54
oh so to post data I need a different token?
:]
@elcolie
Jun 03 2017 15:55
From your given ContactFormPost. Your url endpoint does not need any token.
It is naked. No Auth nor permission at all
You can shoot by POST with postman app
or curl
Costantin
@Cosbgn
Jun 03 2017 15:55
I'm trying something like this:
wbeyda
@wbeyda
Jun 03 2017 15:56
or httpie for the sane.
Costantin
@Cosbgn
Jun 03 2017 15:56
sendMessage: function() {
  var vm = this
  axios.get('/api/v2/user/', {})
   .then(function(response) {
      var userInfo = response.data
      vm.property = userInfo[0].property_name
      vm.email = userInfo[0].google_email
  })
    .then(function() {
      var url = '/api/v1/message/'
      let token = document.head.querySelector("[name=_token]").content
      console.log(token) // Prints correct token
      axios.post(url,{
        headers: {"X-CSRFToken": token},
        data: {
          google_email:'vm.email',
          property_name:'vm.property',
          url: 'sss',
          message: vm.message,
          //xsrfHeaderName: token
        }
      })
    })
So I don't need the token at all in this request?
:]
@elcolie
Jun 03 2017 15:56
yes
Costantin
@Cosbgn
Jun 03 2017 15:56
I keep getting 403 but I am sending the token
Craig Derington
@craigderington
Jun 03 2017 15:56
Your front-end app should auth with the DRF.
:]
@elcolie
Jun 03 2017 15:57
@craigderington Aha. Yes I forgot it
wbeyda
@wbeyda
Jun 03 2017 15:57
token should be in the header
:]
@elcolie
Jun 03 2017 15:57
@craigderington You have default auth in the settings.py
Costantin
@Cosbgn
Jun 03 2017 15:58
so I commented out the token and still 403
:]
@elcolie
Jun 03 2017 15:59
@Cosbgn Please show me your settings.py and urls.py
One moment Craig and wbeyda point the correct solution
Please show me your base configuration
wbeyda
@wbeyda
Jun 03 2017 15:59
does it say anything about CORS? you might need to install django-cors I had to to get webpack to work with Vue
Craig Derington
@craigderington
Jun 03 2017 16:00
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
)
}
:]
@elcolie
Jun 03 2017 16:01
@Cosbgn Do you have REST_FRAMEWORK variable like @craigderington given example?
this is my settings.py
The urls looks like this
url(r'^api/v1/message/$', ContactFormPost.as_view(), name='message'),
and I'm importing that API view
which is the one I posted above
@wbeyda I'm also using vue, but I thought that CORS are needed if I use separate domains
wbeyda
@wbeyda
Jun 03 2017 16:04
403 is when you are authenticated but permission is denied
Craig Derington
@craigderington
Jun 03 2017 16:04
You're settings.py only specifies session auth. try adding basic auth. your front-end needs to authenticate with the DRF authetication framework. the response will contain a Token. Then your POST requests will pass the Token in the POST headers.
wbeyda
@wbeyda
Jun 03 2017 16:04
So its gonna be in your permissions class.
Costantin
@Cosbgn
Jun 03 2017 16:05
in my Rest permission classes?
wbeyda
@wbeyda
Jun 03 2017 16:05
yes
403's are weird in DRF
Costantin
@Cosbgn
Jun 03 2017 16:07
so adding something like this:
'rest_framework.authentication.BasicAuthentication',
:]
@elcolie
Jun 03 2017 16:07
Yes. Try this first
wbeyda
@wbeyda
Jun 03 2017 16:08
@Cosbgn here is my login but I'm using JSON web tokens. Might help you
<script>
import _ from 'lodash';
import axios from 'axios';
import Vue from 'vue';

export default {
  data: function () {
    return {
      email: '',
      password: '',
    };
  },
  methods: {
    loginUser: function () {
      axios.defaults.port = 8001;
      const app = this;
      const user = axios.create({
        baseURL: 'http://localhost:8001',
      });

      user.post('/api-token-auth/', { username: app.email, password: app.password })
      .then(function (response) {
        console.log('TOKEN:', response.data.token);
        axios({
          method: 'post',
          url: '/login/',
          baseURL: 'http://localhost:8001',
          headers: { Authorization: `JWT ${response.data.token}` },
          data: {
            email: 'admin@localhost.com',
            password: app.password,
          },
        })
        .then(function (response) {
          console.log('login then', response);

        })
        .catch(function (error) {
          console.log('login catch', error);
        });
      })
      .catch(function (error) {
        console.log('catch', error);
      });
    },
  },
};
</script>
Craig Derington
@craigderington
Jun 03 2017 16:08
Are you passing your permission_classes to CreateAPIView? Does not appear in the view code above.
Costantin
@Cosbgn
Jun 03 2017 16:08
changing the permission class I get this popup
image.png
and I don't have any password since I use only Google oAuth
Are you passing your permission_classes to CreateAPIView? Does not appear in the view code above.
No I'm not
I thought permissions are automatically setup globally in my settings.py
Craig Derington
@craigderington
Jun 03 2017 16:10
So, your app doesn't have a normal User model?
Costantin
@Cosbgn
Jun 03 2017 16:10
yes it does
actually no
Craig Derington
@craigderington
Jun 03 2017 16:11
That authorization pop-up is the django.contrib.auth.models User class login.
Costantin
@Cosbgn
Jun 03 2017 16:11
I have this:
class CredentialsModel(models.Model):
    credentials = CredentialsField()
    user = models.OneToOneField(User, primary_key=True, unique=True)
    google_email = models.EmailField(max_length=200)

    class Meta:
        db_table = 'credentials'

    def __str__(self):
        return 'creds'
which is like my user model
Craig Derington
@craigderington
Jun 03 2017 16:12
Hmm. How do you login to your app? Does your app have a admin login?
Costantin
@Cosbgn
Jun 03 2017 16:14
I have a view which generates a google link, the user gets redirected there, he accepted to share his data with me and get's redirected back to my app with a code in the url parameter
then I exchange that code for a token and same the user
next time he just clicks login and he get's automatically logged in (if he is signed in with Googel)
this 'rest_framework.authentication.SessionAuthentication' seemed to work fine
I could use my oAuth account to access the rest browsable api, make get requests with Axios, filter only user data etc
wbeyda
@wbeyda
Jun 03 2017 16:15
but your still using sessions and cookies right?
Costantin
@Cosbgn
Jun 03 2017 16:16
yes I think so
otherwise the rest API wouldn't recognize me on the browsable api but it does
wbeyda
@wbeyda
Jun 03 2017 16:17
You can log out and get denied permissions right?
Costantin
@Cosbgn
Jun 03 2017 16:18
image.png
Yes, this is how it looks when I'm logged out
image.png
And this is how it looks when I'm logged in
:]
@elcolie
Jun 03 2017 16:19
Get is not allowed because you uses CreateAPIView
Costantin
@Cosbgn
Jun 03 2017 16:20
yes, I don't need GET
:]
@elcolie
Jun 03 2017 16:20
Then your API is good to POST now
Costantin
@Cosbgn
Jun 03 2017 16:20
But I keep getting 403
when I try to post something with AXIOS
Craig Derington
@craigderington
Jun 03 2017 16:20
I always default to ModelViewSet for all of my API needs. It works flawlessly DRF with limited code.
Costantin
@Cosbgn
Jun 03 2017 16:20
and it's driving me crazy
:]
@elcolie
Jun 03 2017 16:21
Hold one
You are getting very close to finish it
Costantin
@Cosbgn
Jun 03 2017 16:21
:D
:]
@elcolie
Jun 03 2017 16:21
So you have put BasicAuthentication alreayd. Am I correct?
Costantin
@Cosbgn
Jun 03 2017 16:22
yes, but was always giving me the popup, so I removed it
wbeyda
@wbeyda
Jun 03 2017 16:22
the way I did it with JWT is a get a token from /auth-api-token with a post and in the then I make another post to /login and return user info from the login view and serializer. Tokens last for 5 minutes and then I'll make the user to get a new token after making contact with sensitive end points behind the scenes otherwise just let them expire.
Costantin
@Cosbgn
Jun 03 2017 16:23
I'm looking at JWT right now
wbeyda
@wbeyda
Jun 03 2017 16:23
I've been thinking about storing tokens in a cookie or I know vue has a store. thats an option. Still figuring it all out. Because making all this work on native mobile is the real goal.
:]
@elcolie
Jun 03 2017 16:24
@Cosbgn You made the right choice
:]
@elcolie
Jun 03 2017 16:24
Folow @wbeyda example
wbeyda
@wbeyda
Jun 03 2017 16:24
But I really don't want to use cookies or sessions at all because I know they are problematic in native mobile.
Costantin
@Cosbgn
Jun 03 2017 16:26
So I would substitute my <meta name="_token" content="{{ csrf_token }}"> with this JWT token
Ok, I'm following the tutorial, I'll let you know in ~ 20 minutes how it went. Thanks :D
wbeyda
@wbeyda
Jun 03 2017 16:28
I don't even use csrf with JWT
I'm still figuring out how to set the public and private keys for the server to encrypt and decrypt though.
Costantin
@Cosbgn
Jun 03 2017 16:31
mm the JWT token requires a username and a password.. I don't have any
my users or me don't have passwords
:]
@elcolie
Jun 03 2017 16:31
How do you login?
wbeyda
@wbeyda
Jun 03 2017 16:32
in a form
Costantin
@Cosbgn
Jun 03 2017 16:32
just login with google oAuth2.0
:]
@elcolie
Jun 03 2017 16:33
Maybe you need 3rd party now
Costantin
@Cosbgn
Jun 03 2017 16:34
yes, this seems to be my case
I'll try to set it up, I'll let you know soon
:]
@elcolie
Jun 03 2017 16:35
If I were you I would add bot user in the backend. And use that simple user credential POST to the backend
wbeyda
@wbeyda
Jun 03 2017 16:36
I think everything is moving towards JWT. It's just so much simpler to have tokens with a short lifespan and not worry about anything.
Costantin
@Cosbgn
Jun 03 2017 16:42
@elcolie you mean a normal non oAuth user which receives the data and post it using the API?
image.png
the oAuth toolkit doesn't work in my case becaue the user is not really authenticated as oAuth, but it's authenticated as basic django user using django sessions
Costantin
@Cosbgn
Jun 03 2017 16:47
I use oAuth to authenticate users but then I convert them in "normal" users, I do this so I can get data even when they are offline
:]
@elcolie
Jun 03 2017 17:11
Give me moment
Let me clarify your requirements
  1. frontend app get user detail from OAuth
  2. frontend would like to create "normal" user in the backend side. For your internal use in your program
    Am I correct?
Costantin
@Cosbgn
Jun 03 2017 17:14
No
Backend creates, logs in and does all the work
frontend just shows some data using the rest api
frontend doesn't even know who the user is or if he is authenticated or not, however the REST Api knows and so returns the correct information
could it be related to the WWW-Authenticate headers?
I'm reading on the rest tutorial that those can create a 403
The request was not successfully authenticated, and the highest priority authentication class does not use WWW-Authenticate headers. — An HTTP 403 Forbidden response will be returned.
:]
@elcolie
Jun 03 2017 17:17
I don't understand. What do you mean backend creates, logs and does all the REST API?
Sorry I am new to OAuth concept. As fas as I know it is authentication server
And when you use it you have to use OAuth library to authenticate Django REST and start using with headres
Costantin
@Cosbgn
Jun 03 2017 17:20
So, my django app uses oAuth2Client library to generate a link, the user is redirected to that link, it get's redirected back to my app with a code which I use to verify the user and login/signup him
this is all done by django views
and a session is created
the user has now access to the api, to particular django views which use the @login_required decorator etc
the frontend is not involved so far, this could all work within django
now I have a vue app, on a particular page, which fetches some user data using the rest api and presents it nicely formatted to the user
now I need to allow the user to send some data back to my db
and I get the 403
I've overwritten the permission for that particular API view and not I get 500 if it makes it any better
class ContactFormPost(CreateAPIView):
    queryset = ContactForm.objects.all()
    serializer_class = ContactFormSerializer

    authentication_classes = (BasicAuthentication)
    permission_classes = (AllowAny)
I think it's because of the BasicAuthentication
:]
@elcolie
Jun 03 2017 17:25
Can you POST to backend now?
Costantin
@Cosbgn
Jun 03 2017 17:26
image.png
No I get this error. I think now we are close..
:]
@elcolie
Jun 03 2017 17:26
That is not a Django REST error page
It is Django
Costantin
@Cosbgn
Jun 03 2017 17:27
image.png
But if I comment out those 2 lines everything goes back to normal..
:]
@elcolie
Jun 03 2017 17:30
Are you login to Django by Google OAuth?
Costantin
@Cosbgn
Jun 03 2017 17:30
yes
with oAuth2Client
:]
@elcolie
Jun 03 2017 17:31
By that you should have a user token. Am I right?
Costantin
@Cosbgn
Jun 03 2017 17:32
yes in theory
I think it's store in my credential model
:]
@elcolie
Jun 03 2017 17:33
I think so
http://django-oauth-toolkit.readthedocs.io/en/latest/rest-framework/getting_started.html
With given token. I think you put a wrong header. Then Django REST returns 403 to you
Costantin
@Cosbgn
Jun 03 2017 17:34
but my HTTP_COOKIE has only the session ID and csrftoken
I mean in theory I should be able to allow any user regardless if they are logged in/ authenticated or have any token to post some data no? I understand it's not the best for some cases but in my case it would solve everything
AJAX requests that are made on a different site from the API they are communicating with will typically need to use a non-session-based authentication scheme, such as TokenAuthentication.
But I'm on the same domain/site I shouldn't need any of this
Do you have User's access token?
Costantin
@Cosbgn
Jun 03 2017 17:48
No I don't think so
But I'm pretty sure it's not related to oAuth o
since django doesn't really knows if I'm using oAuth
In order to make AJAX requests, you need to include CSRF token in the HTTP header, as described in the Django documentation.
If so try this
Costantin
@Cosbgn
Jun 03 2017 17:50
By default, a ‘403 Forbidden’ response is sent to the user if an incoming request fails the checks performed by CsrfViewMiddleware. This should usually only be seen when there is a genuine Cross Site Request Forgery, or when, due to a programming error, the CSRF token has not been included with a POST form.
But the CORS are only for different domains no?
:]
@elcolie
Jun 03 2017 17:51
different domain only need CORS
Costantin
@Cosbgn
Jun 03 2017 17:51
yes, I'm on the same domain
:]
@elcolie
Jun 03 2017 17:52
I am wonder on your architecture
Costantin
@Cosbgn
Jun 03 2017 17:52
anyways I really don't want to take too much of your time!
:D
:]
@elcolie
Jun 03 2017 17:52
Since you Django authenticate user by Google OAuth only. That is mean you have no real user in your database right?
Costantin
@Cosbgn
Jun 03 2017 17:52
I'll eventually figure it out
No I have, that's why I'm saying that for django it's like normal authentication
oauth is divided in 2
session oauth (no real user)
and "normal" oauth, which uses google just to generate/ authenticate the user
:]
@elcolie
Jun 03 2017 17:54
Oh
I am afraid that session oauth will not work. Because it is not a token
The 2nd one with token should be fine
Costantin
@Cosbgn
Jun 03 2017 17:57
Which 2nd token?
oh yes, I'm using the second method
so I have the users in my DB etc
:]
@elcolie
Jun 03 2017 18:03
Sorry I have go now it is 1:02 (night time) Thailand time.
Tmr If I can finish my project and appointment I will try OAuth. I heard it is good
Costantin
@Cosbgn
Jun 03 2017 18:04
Sure, Thank You soo much!
:D
oAuth is great, just annoying to setup, but from the user side is fantastic
:]
@elcolie
Jun 03 2017 18:05
I could be more help than that. Yes it is :D
It is fantastic
Costantin
@Cosbgn
Jun 03 2017 18:08
see you
Costantin
@Cosbgn
Jun 03 2017 18:14
BTW I just fixed it :D
if anyone was following this adventure here is the solution:
:]
@elcolie
Jun 03 2017 18:15
:tada:
Costantin
@Cosbgn
Jun 03 2017 18:15

In your js file:

import axios from 'axios';
axios.defaults.xsrfHeaderName = "X-CSRFTOKEN";
axios.defaults.xsrfCookieName = "XCSRF-TOKEN";

And in the settings.py file:

CSRF_COOKIE_NAME = "XCSRF-TOKEN"
this makes axios work well with django, and I think it's a fairly secure method, but I really have no idea :D
Thanks again @elcolie and also @wbeyda & @craigderington
Kaushal Kumar
@kaushal087
Jun 03 2017 20:39
Hi guys, I have implemented 'Login with Facebook' in my project using python social auth. When I click the login link it takes some time. Before logging in and redirecting to the next page I want to show loading icon. I have tried this using jquery but Its not working maybe because python social auth is overriding dom events (I am not sure). Any idea how I can do this? Thanks!
John
@flyboy1565
Jun 03 2017 22:01
@Cosbgn , are you doing Django rest with a vue.js frontend??
@kaushal087 are you doing a SAP page?
Sorry Single Page Application... Lol too abbreviations...
wbeyda
@wbeyda
Jun 03 2017 22:04
@kaushal087 on your submit button I would prevent the default action and write my own function to show the swirly thing and rotate it. Then pass in the Facebook funtion in . Just start setting breakpoints and find out where this Facebook JS is getting run from.