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

自定义一个用户很简单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 userdef 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.emaildef get_short_name(self):    # The user is identified by their email address    return self.emaildef __str__(self):              # __unicode__ on Python 2    return self.emaildef has_perm(self, perm, obj=None):    "Does the user have a specific permission?"    # Simplest possible answer: Yes, always    return Truedef has_module_perms(self, app_label):    "Does the user have permissions to view the app `app_label`?"    # Simplest possible answer: Yes, always    return True@propertydef 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 = UserChangeFormadd_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 Nonedef get_user(self, user_id):    try:        return User.objects.get(pk=user_id)    except User.DoesNotExist:        return None

关键字:Python, django

版权声明

本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处。如若内容有涉嫌抄袭侵权/违法违规/事实不符,请点击 举报 进行投诉反馈!

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部