我在这里面临两个问题。
1)如果用户没有旧令牌,则应生成并登录新令牌,但不会发生这种情况。
2)登录时新创建的用户获得“您配置了多个身份验证后端”,因此必须提供backend
参数或在用户上设置backend
属性。&#39 ;
3)旧用户在尝试登录时收到错误的get()返回多个AccessToken - 它返回8!
专家可以从我的代码中了解
class UserLoginAPI(APIView):
permission_classes = [AllowAny]
serializer_class = UserLoginSerializer
def post(self, request, *args, **kwargs):
access_token = request.GET.get('access_token')
data = request.data
print('data',data)
serializer = UserLoginSerializer(data=data)
if serializer.is_valid(raise_exception=True):
new_data = serializer.data
if new_data:
app = Application.objects.get(name="Foodie")
try:
user = User.objects.get(username=data['username'])
print ('user',user)
except ObjectDoesNotExist:
return HttpResponse("Can't find this user")
else:
try:
access_token = AccessToken.objects.get(user=user)
except ObjectDoesNotExist:
return HttpResponse('Have not set any token')
else:
access_token.delete()
new_token = generate_token()
print('new_token',new_token)
AccessToken.objects.create(user=user, application=app, expires=datetime.now() + timedelta(days=365),token=new_token)
print('aceess',AccessToken)
login(request, user)
return Response(new_data, status=status.HTTP_200_OK)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
serializers.py
class UserLoginSerializer(ModelSerializer):
username = CharField()
class Meta:
model = User
fields = ['username', 'password']
class UserCreateSerializer(ModelSerializer):
class Meta:
model = User
extra_kwargs = {"password": {"write_only": True}}
def create(self, validated_data):
user_obj = User(
username = username,
first_name = first_name,
last_name = last_name,
email = email
)
user_obj.set_password(password)
user_obj.save()
if user_obj:
expire_seconds = oauth2_settings.user_settings['ACCESS_TOKEN_EXPIRE_SECONDS']
scopes = oauth2_settings.user_settings['SCOPES']
application = Application.objects.get(name="Foodie")
expires = datetime.now() + timedelta(seconds=expire_seconds)
access_token = AccessToken.objects.create(user=user_obj,
application=application,
token = generate_token(),
expires=expires,
scope=scopes)
return validated_data