好吧,我發現得到使用電子郵件或用戶名的身份驗證令牌的方式......這是串行:
class AuthCustomTokenSerializer(serializers.Serializer):
email_or_username = serializers.CharField()
password = serializers.CharField()
def validate(self, attrs):
email_or_username = attrs.get('email_or_username')
password = attrs.get('password')
if email_or_username and password:
# Check if user sent email
if validateEmail(email_or_username):
user_request = get_object_or_404(
User,
email=email_or_username,
)
email_or_username = user_request.username
user = authenticate(username=email_or_username, password=password)
if user:
if not user.is_active:
msg = _('User account is disabled.')
raise exceptions.ValidationError(msg)
else:
msg = _('Unable to log in with provided credentials.')
raise exceptions.ValidationError(msg)
else:
msg = _('Must include "email or username" and "password"')
raise exceptions.ValidationError(msg)
attrs['user'] = user
return attrs
在EMAIL_OR_USERNAME領域,用戶可以發送電子郵件或用戶名,使用功能validateEmail(),我們可以檢查用戶是否嘗試使用電子郵件或用戶名登錄。然後,我們可以查詢獲取用戶實例是否有效,並對其進行身份驗證。
這是視圖。
class ObtainAuthToken(APIView):
throttle_classes =()
permission_classes =()
parser_classes = (
parsers.FormParser,
parsers.MultiPartParser,
parsers.JSONParser,
)
renderer_classes = (renderers.JSONRenderer,)
def post(self, request):
serializer = AuthCustomTokenSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.validated_data['user']
token, created = Token.objects.get_or_create(user=user)
content = {
'token': unicode(token.key),
}
return Response(content)
然後:
curl --data "email_or_username=emailorusername&password=password" http://127.0.0.1:8000/api/my-api-token-auth/.
這是準備好了。
喲喲你的應用程序已經有使用電子郵件和密碼登錄的方法嗎?或者這是您爲應用程序實施的第一種身份驗證方法? – 2015-01-21 02:02:57
嗨...是第一種身份驗證方法,我以前沒有實現過其他...現在我使用默認的獲取令牌方法,使用用戶名和密碼......但是,在移動設備中,我需要獲取令牌使用電子郵件和密碼驗證。 – 2015-01-21 02:07:03