我在Django中为我的用户创建了一个自定义用户模型,并使用Django rest框架和JWT以及angular作为前端。
当我使用超级用户登录时,它运行良好,但是现在,我已经创建了新用户,仅使用超级用户无法登录。我注意到的主要问题是未对密码进行哈希处理,所以问题是,当我创建一个从Angular发布用户的用户时,如何对密码进行哈希处理?我的做法正确吗?因为我看到很多不同的方法来做到这一点,老实说,我有点迷失了。
models.py
class User(AbstractUser):
email = models.EmailField(unique=True)
username = models.CharField(blank=True,null=True,max_length=30)
is_candidate = models.BooleanField(default=False)
is_employer = models.BooleanField(default=False)
skype_id = models.CharField(max_length=50, blank=True)
last_modified = models.DateTimeField(auto_now_add=False, auto_now=True, null=True)
created = models.DateTimeField(auto_now_add=True, auto_now=False, null=True)
email_confirmed = models.BooleanField(default=False)
user_cpf = models.CharField(max_length=14, blank=True,verbose_name='cpf')
company_name = models.CharField(max_length=50, blank=True)
user_data_waiver = models.BooleanField(default=True)
user_receive_emails = models.BooleanField(default=True)
USERNAME_FIELD = 'email'
EMAIL_FIELD = 'email'
REQUIRED_FIELDS = ['username']
def __str__(self):
return self.email
serializers.py
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = '__all__'
views.py
class UserViewSet(viewsets.ModelViewSet):
serializer_class = UserSerializer
queryset = User.objects.all()
core / urls.py
router.register('user', UserViewSet, base_name='user')
qualify / urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('select2/', include('django_select2.urls')),
path('api-auth/', include('rest_framework.urls')),
path('login/', obtain_jwt_token),
path('refresh-token/', refresh_jwt_token),
path('', include('core.urls')),
]
settings.py
INSTALLED_APPS = [
'django_select2',
#'jquery',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'social_django',
'core.apps.CoreConfig',
'rest_framework',
'corsheaders',
]
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
),
'NON_FIELD_ERRORS_KEY': 'global',
}
JWT_AUTH = {
'JWT_ALLOW_REFRESH': True,
'JWT_EXPIRATION_DELTA': timedelta(days=2),
}
AUTH_USER_MODEL = 'core.User'