资讯专栏INFORMATION COLUMN

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

flyer_dev / 3547人阅读

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

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

from django.db import models
from django.contrib.auth.models import (
    BaseUserManager, AbstractBaseUser
)

class MyUserManager(BaseUserManager):
    def create_user(self, email, date_of_birth, 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),
            date_of_birth=date_of_birth,
        )

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

    def create_superuser(self, email, date_of_birth, password):
        """
        Creates and saves a superuser with the given email, date of
        birth and password.
        """
        user = self.create_user(
            email,
            password=password,
            date_of_birth=date_of_birth,
        )
        user.is_admin = True
        user.save(using=self._db)
        return user
               
class MyUser(AbstractBaseUser):
    email = models.EmailField(
        verbose_name="email address",
        max_length=255,
        unique=True,
    )
    date_of_birth = models.DateField()
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)

    objects = MyUserManager()

    USERNAME_FIELD = "email"
    REQUIRED_FIELDS = ["date_of_birth"]

    def get_full_name(self):
        # The user is identified by their email address
        return self.email

    def get_short_name(self):
        # The user is identified by their email address
        return self.email

    def __str__(self):              # __unicode__ on Python 2
        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

然后是admin.py

class UserAdmin(BaseUserAdmin):
    # The forms to add and change user instances
    form = UserChangeForm
    add_form = UserCreationForm

    # The fields to be used in displaying the User model.
    # These override the definitions on the base UserAdmin
    # that reference specific fields on auth.User.
    list_display = ("email", "date_of_birth", "is_admin")
    list_filter = ("is_admin",)
    fieldsets = (
        (None, {"fields": ("email", "password")}),
        ("Personal info", {"fields": ("date_of_birth",)}),
        ("Permissions", {"fields": ("is_admin",)}),
    )
    # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
    # overrides get_fieldsets to use this attribute when creating a user.
    add_fieldsets = (
        (None, {
            "classes": ("wide",),
            "fields": ("email", "date_of_birth", "password1", "password2")}
        ),
    )
    search_fields = ("email",)
    ordering = ("email",)
    filter_horizontal = ()

# Now register the new UserAdmin...
admin.site.register(MyUser, UserAdmin)
# ... and, since we"re not using Django"s built-in permissions,
# unregister the Group model from admin.
admin.site.unregister(Group)

最后是settings.py

AUTH_USER_MODEL = "customauth.MyUser"
AUTHENTICATION_BACKENDS = (
    "accounts.backends.LoginBackend",
)

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

class LoginBackend(object):
    def authenticate(self, username=None, password=None):
        if username:
            #email
            if re.match("^.+@([?)[a-zA-Z0-9-.]+.([a-zA-Z]{2,3}|[0-9]{1,3})(]?)$", username) != None:
                try:
                    user = User.objects.get(email=username)
                    if user.check_password(password):
                        return user
                except User.DoesNotExist:
                    return None
            #mobile
            elif len(username)==11 and re.match("^(1[3458]d{9})$", username) != None:
                try:
                    user = User.objects.get(mobile=username)
                    if user.check_password(password):
                        return user
                except User.DoesNotExist:
                    return None  
            #nick
            else:
                try:
                    user = User.objects.get(username=username)
                    if user.check_password(password):
                        return user
                except User.DoesNotExist:
                    return None                
        else:
            return None

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            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元查看
<