Chickenfresh
Chickenfresh

Reputation: 365

django get token and userid after successful registration

I'm building a server with custom registration pages using rest and django (latest versions).

I have 3 fields required (username unique, phone_number unique, password) and 1 optional. Schema is: User sends phone-number to server, we check if user exists and if don't - ask for registration. In both cases I want to send token and user_id as answer if credentials are correct.

The topics from 2016's are not working in my case, i think because of latest framework and python updates.

That's what i have now in view.py:

class RegisterView(APIView):
  renderer_classes = [renderers.JSONRenderer]

  def post(self, request):
    phone = request.POST.get('phone')
    username = request.POST.get('username')
    password = request.POST.get('password')
    name = request.POST.get('name', '')
    try:
        ChatUser.objects.create_user(username, phone, password, name)
        return Response({'success': True, 'token': """THERE SHOULD BE TOKEN"""})
    except Exception:
        return Response({'success': False})

class CheckPhone(APIView): # works fine 
    renderer_classes = [renderers.JSONRenderer]

    def post(self, request):
        phone_number = request.POST.get('phone_number')
        try:
            User.objects.get(phone=phone_number)
            return Response("""asks for login""")
        except User.DoesNotExist:
            return Response("""asks for registration""")

models.py:

class ChatUserManager(BaseUserManager):
    """Define a model manager for User model with no username field."""

    use_in_migrations = True

    def _create_user(self, username, phone, password, name, **extra_fields):
        """Create and save a User with the given phone and password."""
        if not phone:
            raise ValueError('The given phone must be set')
        if not username:
            raise ValueError('The given username must be set')
        username = self.model.normalize_username(username)
        user = self.model(phone=phone, username=username, name=name, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return username

    def create_user(self, username, phone, password, name, **extra_fields):
        """Create and save a regular User with the given phone and password."""
        extra_fields.setdefault('is_staff', False)
        extra_fields.setdefault('is_superuser', False)
        return self._create_user(username, phone, password, name, **extra_fields)

class ChatUser(AbstractUser):
    REQUIRED_FIELDS = ['phone', 'name']

    groups = models.ManyToManyField(
        Group,
        verbose_name=_('groups'),
        blank=True,
        help_text=_(
            'The groups this user belongs to. A user will get all permissions '
            'granted to each of their groups.'
        ),
        related_name="chatuser_set",
        related_query_name="user",
    )
    user_permissions = models.ManyToManyField(
        Permission,
        verbose_name=_('user permissions'),
        blank=True,
        help_text=_('Specific permissions for this user.'),
        related_name="chatuser_set",
        related_query_name="user",
    )
    username = models.CharField(_('username'), max_length=25, unique=True)
    phone_regex = RegexValidator(regex=r'^\+?7?\d{9,15}$', message="Phone number must be entered in the format: '+71234567890'. Up to 15 digits allowed.")
    phone = models.CharField(_('phone_number'), validators=[phone_regex], max_length=17, unique=True) # validators should be a list
    name = models.CharField(_('name'), max_length=30, blank=True)
    USERNAME_FIELD = 'username'
    objects = ChatUserManager()

So, how can I get token and user_id in these cases and, also, did I miss anything while creating custom models?

Upvotes: 0

Views: 2968

Answers (1)

Youssef BH
Youssef BH

Reputation: 582

You can create the token using from rest_framework.authtoken.models import Token

from rest_framework.authtoken.models import Token

class RegisterView(APIView):
  renderer_classes = [renderers.JSONRenderer]

  def post(self, request):
    phone = request.POST.get('phone')
    username = request.POST.get('username')
    password = request.POST.get('password')
    name = request.POST.get('name', '')
    try:
        chat_user = ChatUser.objects.create_user(username, phone, password, name)
        token = Token.objects.create(user=chat_user)
        return Response({'success': True, 'token': token.key})
    except Exception:
        return Response({'success': False})

Edit:

def _create_user(self, username, phone, password, name, **extra_fields):
        """Create and save a User with the given phone and password."""
        if not phone:
            raise ValueError('The given phone must be set')
        if not username:
            raise ValueError('The given username must be set')
        username = self.model.normalize_username(username)
        user = self.model(phone=phone, username=username, name=name, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

You should return user not username

I hope this will help.

Upvotes: 1

Related Questions