Skip to content
This repository was archived by the owner on May 26, 2020. It is now read-only.

Support Custom User models. #18

Merged
merged 1 commit into from Jun 6, 2014
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 14 additions & 7 deletions rest_framework_jwt/serializers.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from django.contrib.auth import authenticate
from django.contrib.auth import authenticate, get_user_model
from rest_framework import serializers

from rest_framework_jwt.settings import api_settings
Expand All @@ -12,17 +12,24 @@ class JSONWebTokenSerializer(serializers.Serializer):
"""
Serializer class used to validate a username and password.

'username' is identified by the custom UserModel.USERNAME_FIELD.

Returns a JSON Web Token that can be used to authenticate later calls.
"""
username = serializers.CharField()

username_field = get_user_model().USERNAME_FIELD
password = serializers.CharField(write_only=True)

def validate(self, attrs):
username = attrs.get('username')
password = attrs.get('password')
def __init__(self, *args, **kwargs):
"""Dynamically add the USERNAME_FIELD to self.fields."""
super(JSONWebTokenSerializer, self).__init__(*args, **kwargs)
self.fields[self.username_field] = serializers.CharField()

if username and password:
user = authenticate(username=username, password=password)
def validate(self, attrs):
credentials = {self.username_field: attrs.get(self.username_field),
'password': attrs.get('password')}
if all(credentials.values()):
user = authenticate(**credentials)

if user:
if not user.is_active:
Expand Down