Reputation: 69
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:
Am I doing something terribly wrong? I think I have all of the stuff I need in my settings:
INSTALLED_APPS = [
'search.apps.SearchConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'corsheaders'
]
I also have 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware' in my middleware.
How exactly does Django know that the user is authenticated? I assume that since I have sessions activated, it checks for the session cookie. However, I suspect this could be the issue. On inspection, I had a cookie placed this afternoon for localhost. However, since then I've signed in and not been able to update it. I even tried Django's in-built test cookie function (source) but it wouldn't work when I tested it. My settings should be okay, I have the following:
INSTALLED_APPS = ['django.contrib.sessions']
SESSION_ENGINE = "django.contrib.sessions.backends.signed_cookies"
MIDDLEWARE_CLASSES = [
...
'django.contrib.sessions.middleware.SessionMiddleware',
...
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
...]
I suspect I'm missing something obvious but I've been reading other threads for a while now with no luck.
Thanks, guys! Nick
Upvotes: 1
Views: 2478
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