资讯专栏INFORMATION COLUMN

django rest framework 自定义用户以及自定义认证方式

flyer_dev / 3619人阅读

摘要:自定义一个用户很简单然后是最后是这样一个自定义的用户模型就弄好了,接下来是自定义登录字段

自定义一个用户很简单models.py

</>复制代码

  1. from django.db import models
  2. from django.contrib.auth.models import (
  3. BaseUserManager, AbstractBaseUser
  4. )
  5. class MyUserManager(BaseUserManager):
  6. def create_user(self, email, date_of_birth, password=None):
  7. """
  8. Creates and saves a User with the given email, date of
  9. birth and password.
  10. """
  11. if not email:
  12. raise ValueError("Users must have an email address")
  13. user = self.model(
  14. email=self.normalize_email(email),
  15. date_of_birth=date_of_birth,
  16. )
  17. user.set_password(password)
  18. user.save(using=self._db)
  19. return user
  20. def create_superuser(self, email, date_of_birth, password):
  21. """
  22. Creates and saves a superuser with the given email, date of
  23. birth and password.
  24. """
  25. user = self.create_user(
  26. email,
  27. password=password,
  28. date_of_birth=date_of_birth,
  29. )
  30. user.is_admin = True
  31. user.save(using=self._db)
  32. return user
  33. class MyUser(AbstractBaseUser):
  34. email = models.EmailField(
  35. verbose_name="email address",
  36. max_length=255,
  37. unique=True,
  38. )
  39. date_of_birth = models.DateField()
  40. is_active = models.BooleanField(default=True)
  41. is_admin = models.BooleanField(default=False)
  42. objects = MyUserManager()
  43. USERNAME_FIELD = "email"
  44. REQUIRED_FIELDS = ["date_of_birth"]
  45. def get_full_name(self):
  46. # The user is identified by their email address
  47. return self.email
  48. def get_short_name(self):
  49. # The user is identified by their email address
  50. return self.email
  51. def __str__(self): # __unicode__ on Python 2
  52. return self.email
  53. def has_perm(self, perm, obj=None):
  54. "Does the user have a specific permission?"
  55. # Simplest possible answer: Yes, always
  56. return True
  57. def has_module_perms(self, app_label):
  58. "Does the user have permissions to view the app `app_label`?"
  59. # Simplest possible answer: Yes, always
  60. return True
  61. @property
  62. def is_staff(self):
  63. "Is the user a member of staff?"
  64. # Simplest possible answer: All admins are staff
  65. return self.is_admin

然后是admin.py

</>复制代码

  1. class UserAdmin(BaseUserAdmin):
  2. # The forms to add and change user instances
  3. form = UserChangeForm
  4. add_form = UserCreationForm
  5. # The fields to be used in displaying the User model.
  6. # These override the definitions on the base UserAdmin
  7. # that reference specific fields on auth.User.
  8. list_display = ("email", "date_of_birth", "is_admin")
  9. list_filter = ("is_admin",)
  10. fieldsets = (
  11. (None, {"fields": ("email", "password")}),
  12. ("Personal info", {"fields": ("date_of_birth",)}),
  13. ("Permissions", {"fields": ("is_admin",)}),
  14. )
  15. # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
  16. # overrides get_fieldsets to use this attribute when creating a user.
  17. add_fieldsets = (
  18. (None, {
  19. "classes": ("wide",),
  20. "fields": ("email", "date_of_birth", "password1", "password2")}
  21. ),
  22. )
  23. search_fields = ("email",)
  24. ordering = ("email",)
  25. filter_horizontal = ()
  26. # Now register the new UserAdmin...
  27. admin.site.register(MyUser, UserAdmin)
  28. # ... and, since we"re not using Django"s built-in permissions,
  29. # unregister the Group model from admin.
  30. admin.site.unregister(Group)

最后是settings.py

</>复制代码

  1. AUTH_USER_MODEL = "customauth.MyUser"
  2. AUTHENTICATION_BACKENDS = (
  3. "accounts.backends.LoginBackend",
  4. )

这样一个自定义的用户模型就弄好了,接下来是自定义登录字段

</>复制代码

  1. class LoginBackend(object):
  2. def authenticate(self, username=None, password=None):
  3. if username:
  4. #email
  5. if re.match("^.+@([?)[a-zA-Z0-9-.]+.([a-zA-Z]{2,3}|[0-9]{1,3})(]?)$", username) != None:
  6. try:
  7. user = User.objects.get(email=username)
  8. if user.check_password(password):
  9. return user
  10. except User.DoesNotExist:
  11. return None
  12. #mobile
  13. elif len(username)==11 and re.match("^(1[3458]d{9})$", username) != None:
  14. try:
  15. user = User.objects.get(mobile=username)
  16. if user.check_password(password):
  17. return user
  18. except User.DoesNotExist:
  19. return None
  20. #nick
  21. else:
  22. try:
  23. user = User.objects.get(username=username)
  24. if user.check_password(password):
  25. return user
  26. except User.DoesNotExist:
  27. return None
  28. else:
  29. return None
  30. def get_user(self, user_id):
  31. try:
  32. return User.objects.get(pk=user_id)
  33. except User.DoesNotExist:
  34. return None

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/38077.html

相关文章

  • django rest framework 定义用户以及定义认证方式

    摘要:自定义一个用户很简单然后是最后是这样一个自定义的用户模型就弄好了,接下来是自定义登录字段 自定义一个用户很简单models.py from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) class MyUserManage...

    lauren_liuling 评论0 收藏0
  • django rest framework 定义用户以及定义认证方式

    摘要:自定义一个用户很简单然后是最后是这样一个自定义的用户模型就弄好了,接下来是自定义登录字段 自定义一个用户很简单models.py from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) class MyUserManage...

    wuyangchun 评论0 收藏0
  • django rest framework个人学习笔记(六)————Tutorial4.认证于授权

    摘要:另外一个字段用于储存突出显示的代码的表示形式。这将确保认证用户拥有读写权限,而未认证用户只有读的权限。唯一的限制是必须是。 官网地址目前,我们的API没有对如 edit 或者 delect做出任何限制。我们希望有一些更加高级的功能能够做到: Code snippets 应该永远和创建者相关 只有认证的用户才能够创建snippets 只有创建者才能更新或者删除他的snippet 没有认...

    eternalshallow 评论0 收藏0
  • django rest framework个人学习笔记(六)————Tutorial4.认证于授权

    摘要:另外一个字段用于储存突出显示的代码的表示形式。这将确保认证用户拥有读写权限,而未认证用户只有读的权限。唯一的限制是必须是。 官网地址目前,我们的API没有对如 edit 或者 delect做出任何限制。我们希望有一些更加高级的功能能够做到: Code snippets 应该永远和创建者相关 只有认证的用户才能够创建snippets 只有创建者才能更新或者删除他的snippet 没有认...

    MonoLog 评论0 收藏0
  • django rest framework个人学习笔记(六)————Tutorial4.认证于授权

    摘要:另外一个字段用于储存突出显示的代码的表示形式。这将确保认证用户拥有读写权限,而未认证用户只有读的权限。唯一的限制是必须是。 官网地址目前,我们的API没有对如 edit 或者 delect做出任何限制。我们希望有一些更加高级的功能能够做到: Code snippets 应该永远和创建者相关 只有认证的用户才能够创建snippets 只有创建者才能更新或者删除他的snippet 没有认...

    caozhijian 评论0 收藏0

发表评论

0条评论

flyer_dev

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<