Nicholas James Hall
Nicholas James Hall

Reputation: 69

request.user.is_authenticated() consistently returns false (Django)

The problem I'm having

The part that seems to work

@csrf_exempt
def userlogin(request):

  body_unicode = request.body.decode('utf-8')
  body = json.loads(body_unicode)
  input_u = body['uname']
  input_p = body['pword']

  worked = False

  user = authenticate(username=input_u, password=input_p)

  if user is not None:
      login(request, user)
      context = { "login_data" : { "logged_in" : True, "user_id" : user.id } }
  else:
      context = { "login_data" : { "logged_in" : False, "user_id" : 0 } }

  return HttpResponse(json.dumps(context), content_type="application/json")

The part I'm struggling with

@ensure_csrf_cookie
def user(request):
  is_auth = False

  if request.user.is_authenticated():
    is_auth = True

  context = { "is_auth" : is_auth }

  return HttpResponse(json.dumps(context), content_type="application/json") 

Note: I'm using is_authenticated() (function) and not is_authenticated (property) as I'm on Django v1.9 and not v.1.10 (source). I was previously making the mistake of checking for the property and it always returned true, but when I'd try to return the ID of the user from the request object it would always be null.

I keep getting false here. This is the first time I've tried auth with Django, so I just wanted to ask some questions here:

I also have 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware' in my middleware.

Thanks, guys! Nick

Upvotes: 1

Views: 2478

Answers (2)

Nicholas James Hall
Nicholas James Hall

Reputation: 69

Found the solution to my own problem from another problem I was having.

The issue is that Angular wasn't sending cookies to the Django server. As Angular is using CORS by default, I had to add { withCredentials : true } to my RequestOptions object.

Example: editUser(userdata) {

    console.log("UserService: createUser function called");
    console.log(JSON.stringify(userdata));

    if(this.validateData(userdata)) {

        let headers = new Headers({
            'Content-Type': 'application/json',
            'X-CSRFToken': this.getCookie('csrftoken')
        });

        let options = new RequestOptions({ headers: headers, withCredentials: true });

        return this._http
            .post(
                this._editUserUri,
                JSON.stringify(userdata),
                options)
            .map(res => {
                console.log(res.json());
                return res.json();
            })
    }

}

Explained thoroughly here: Angular2 and Django: CSRF Token Headache

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599450

You don't have the contrib.auth app in INSTALLED_APPS.

Upvotes: -1

Related Questions