1
votes

I have implemented token authentication for my django project. when generating the token for the user after the POST request. I need to return other informations with the token like:

{

"Token": "token string",

"email": "[email protected]",

"phone": "12345", "photo": depending on the photo serailizer

}

Please how can i do it ? Here is my code:

Models.py

class User(AbstractUser):
    username = None
    email = models.EmailField(max_length=100, 
               verbose_name='email', unique=True)
    phone = models.CharField(max_length=100)

    
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []
    objects = UserManager()

Views.py

class AuthToken(auth_views.ObtainAuthToken):
    serializer_class = AuthTokenSerializer
    if coreapi is not None and coreschema is not 
                         None:
        schema = ManualSchema(
            fields=[
                coreapi.Field(
                    name="email",
                    required=True,
                    location='form',
                    schema=coreschema.String(
                        title="Email",
                        description="Valid email 
                           for authentication",
                    ),
                ),
                coreapi.Field(
                    name="password",
                    required=True,
                    location='form',
                    schema=coreschema.String(
                        title="Password",
                        description="Valid password for authentication",
                    ),
                ),
            ],
            encoding="application/json",
        )

Serializers.py

class AuthTokenSerializer(serializers.Serializer):

    email = serializers.EmailField(label=_("Email"))
    password = serializers.CharField(
        label=_("Password",),
        style={'input_type': 'password'},
        trim_whitespace=False
    )

    def validate(self, attrs):
        email = attrs.get('email')
        password = attrs.get('password')

        if email and password:
            user = 
 authenticate(request=self.context.get('request'),
                                email=email, password=password)

       if not user:
            msg = ('Unable to log in with 
                   provided credentials.')
            raise 
                serializers.ValidationError(msg, 
                  code='authorization')
        else:
            msg = ('Must include "username" and 
                  "password".')
            raise serializers.ValidationError(msg, 
              code='authorization')
        attrs['user'] = user
        return attrs

class UserSerializer(serializers.ModelSerializer):
    photo = PhotoSerializer()
    class Meta:
        model = User
        fields = ['id', 'email','phone', 'photo', ']

1

1 Answers

0
votes

just override post function of auth_views.ObtainAuthToken class and add your data to response:

class AuthToken(auth_views.ObtainAuthToken):
    serializer_class = AuthTokenSerializer
    if coreapi is not None and coreschema is not 
                         None:
        schema = ManualSchema(
            fields=[
                coreapi.Field(
                    name="email",
                    required=True,
                    location='form',
                    schema=coreschema.String(
                        title="Email",
                        description="Valid email 
                           for authentication",
                    ),
                ),
                coreapi.Field(
                    name="password",
                    required=True,
                    location='form',
                    schema=coreschema.String(
                        title="Password",
                        description="Valid password for authentication",
                    ),
                ),
            ],
            encoding="application/json",
        )

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data['user']
        token, created = Token.objects.get_or_create(user=user)
        return Response({
            'token': token.key,
            'email': user.email,
            # and your extra data required
        })