扩展用户对象后如何让 Django 登录 api 工作?

时间:2020-12-27 19:55:09

标签: django django-rest-framework django-authentication

我已经按照文档 here 扩展了我的用户类,但是现在我的登录测试失败了。我假设这是由于扩展类没有正确链接回处理身份验证的 django 视图。

r = self.client.post('/login/', {'username': 'test@test.com', 'password': 'test'})

返回

b'\n<!doctype html>\n<html lang="en">\n<head>\n  <title>Not Found</title>\n</head>\n<body>\n  <h1>Not Found</h1><p>The requested resource was not found on this server.</p>\n</body>\n</html>\n'

我已经在我的设置中设置了 AUTH_USER_MODEL

AUTH_USER_MODEL = 'api.ApiUser'

我可以在我的管理员中创建用户,然后正常登录。

models.py

class Company(models.Model):
    """
    Represents a company that has access to the same missions/mission plans/etc.
    """
    id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4)

    name = models.TextField()
    logo = models.ImageField(blank=True)

    def __str__(self):
        return self.name


class UserManager(BaseUserManager):
    def create_user(self, email, password=None):
        """
        Creates and saves a User with the given email, date of
        birth and password.
        """
        if not email:
            raise ValueError('Users must have an email address')

        user = self.model(
            email=self.normalize_email(email),
        )

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, password=None):
        """
        Creates and saves a superuser with the given email, date of
        birth and password.
        """
        user = self.create_user(
            email,
            password=password,
        )
        user.is_admin = True
        user.save(using=self._db)
        return user


class ApiUser(AbstractBaseUser):
    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique=True,
    )
    company = models.ForeignKey(Company, null=True, blank=True, on_delete=models.CASCADE)
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    def __str__(self):
        return self.email

    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True

    @property
    def is_staff(self):
        "Is the user a member of staff?"
        # Simplest possible answer: All admins are staff
        return self.is_admin

我还需要做什么才能让身份验证 API 再次运行?

我是否需要使用身份验证来实现我自己的视图?

1 个答案:

答案 0 :(得分:2)

你可以这样做

settings.py

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
    ]
}

INSTALLED_APPS = ['rest_framework.authtoken']

urls.py

from rest_framework.authtoken import views
urlpatterns += [
    path('api-token-auth/', views.obtain_auth_token)
]

curl -X POST -d "username=username&password=password123" http://localhost:8000/api-token-auth/