menu

Junjielee Blog

在平凡中坚持前行,总会遇见不凡的自己

Django自定义登录

最近使用django开发一个账号系统相关的服务,然后django本身就自带了账号模块,但是有时候我们需要对这个django自带的账号进行扩展

目录

自定义登录验证流程

django提供一个 authentication backends的东西给我们自定义登录登录验证,我们可以跳过django自身的登录验证,重写验证的方法;也可以在django自身的验证不通过后,调用我们写的自定义的验证方法。

怎么使用?

首先我们在对应的app目录下创建一个文件,例如有一个app叫accounts, 创建一个backends.py文件,创建一个类,继承object就可以,然后类里面编写authenticate方法和get_user方法,例如:

from django.contrib.auth.models import User


class MyBackend(object):

    def authenticate(self, username=None, password=None):
        # 如果验证不通过,返回None就行了
        print "username: {username} \n password: {password}".format(username=username,
                                                                    password=password)
        if username is not None and password is not None:
            try:
                user = User.objects.get(username=username)
                valid_user = user.check_password(password)
                if valid_user is None:
                    return None
            except User.DoesNotExist:
                user = User(username=username, password=password)
                user.is_staff = True
                user.save()
            return user

        return None

    def get_user(self, user_id):
         The get_user method takes a user_id  which could be a username, database ID or whatever, but has to be the primary key of your User object  and returns a User object.
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None

get_useruser_id 参数需要是表的primary key, 官方文档也相应的例子

The get_user method takes a user_id – which could be a username, database ID or whatever, but has to be the primary key of your User object – and returns a User object.

也可以使用添加权限的判断def has_perm(self, user_obj, perm, obj=None)方法,

然后在settings.py文件添加变量AUTHENTICATION_BACKENDS

AUTHENTICATION_BACKENDS = [
    'django.contrib.auth.backends.ModelBackend', # 这个是自带的验证,如果不是用自带的验证,就去掉
    'ff.accounts.backends.MyBackend', # 这个是自己创建的backends
]

自定义权限

在对应的model里面添加Meta的权限内容,例如:

class Article(models.Model):
    class Meta:
        permissions = (
            ('can_change_article', 'Can change articles'),
            ('can_view_article', 'Can view articles'),
        )

扩展UserModel

扩展UserModel,可以对现有的User添加字段等,有两种方式,一种使用OneToOneFieldproxy

这里我是使用了OneToOneField的方式

# models.py
from django.db import models
from django.contrib.auth.models import User

class GameInfo(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    money = models.IntegerField(default=0)
# admin.py
from django.contrib import admin
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin

from ff.accounts.models import GameInfo


class GameInfoInline(admin.StackedInline):
    model = GameInfo
    can_delete = False
    verbose_name_plural = 'gameinfo'


class UserAdmin(BaseUserAdmin):
    inlines = (MyUserInline, )

admin.site.unregister(User)
admin.site.register(User, UserAdmin)

这样在admin后台就能看到对应的字段,如果想在代码中访问,还是需要访问GameInfo表,例如

u = User.objects.get(username='test')
# 获取用户test的money
game_user_money = u.gameinfo.money

自定义一个Model作为UserModel

  1. 定义用户Model,继承AbstractBaseUser
  2. 定义UserManager,继承BaseUserManager
  3. 定义相关的Form,例如CreateForm, ChangeForm
  4. 定义admin
  5. 修改settings.py,添加变量AUTH_USER_MODEL

直接上例子,官方文档也有例子

# models.py
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager


class GameUserManager(BaseUserManager):
    def create_user(self, gameusername, password=None):
        if not gameusername:
            raise ValueError('Users must have an gameusername')
        user = self.model(
            gameusername=gameusername
        )
        user.set_password(password)
        user.save(using=self._db)

        return user

    def create_superuser(self, gameusername, password):
        user = self.create_user(gameusername=gameusername,
                                password=password)
        user.is_superuser = True
        user.save(using=self._db)

        return user


class GameUser(AbstractBaseUser):
    gameusername = models.CharField(max_length=40, unique=True)
    name = models.CharField(max_length=100)
    level = models.IntegerField(default=0)
    money = models.IntegerField(default=0)
    food = models.IntegerField(default=0)

    is_active = models.BooleanField(default=True)
    is_superuser = models.BooleanField(default=False)

    objects = GameUserManager()

    USERNAME_FIELD = 'gameusername'

    def get_full_name(self):
        return self.name

    def get_short_name(self):
        return self.name
# forms.py
from django import forms
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from custom_auth.accounts.models import GameUser


class GameUserCreationForm(forms.ModelForm):
    password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
    password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)

    class Meta:
        model = GameUser
        fields = ('gameusername', 'level', )

    def clean_password2(self):
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("Passwords don't match")
        return password2

    def save(self, commit=True):
        user = super(GameUserCreationForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user


class GameUserChangeForm(forms.ModelForm):
    password = ReadOnlyPasswordHashField()

    class Meta:
        model = GameUser
        fields = ('gameusername', 'password', 'level', )

    def clean_password(self):
        return self.initial['password']
# admin.py
from django.contrib import admin
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin

from custom_auth.accounts.forms import (
    GameUserCreationForm,
    GameUserChangeForm,
)
from custom_auth.accounts.models import GameUser


class GameUserAdmin(UserAdmin):
    form = GameUserChangeForm
    add_form = GameUserCreationForm

    list_display = ('gameusername', 'level', 'money', )
    list_filter = ('is_superuser',)
    fieldsets = (
        (None, {'fields': ('gameusername', 'password')}),
        ('Personal info', {'fields': ('level',)}),
        ('Permissions', {'fields': ('is_superuser',)}),
    )
    # 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': ('gameusername', 'level', 'password1', 'password2')}
        ),
    )
    search_fields = ('gameusername',)
    ordering = ('gameusername',)
    filter_horizontal = ()


admin.site.register(GameUser, GameUserAdmin)
admin.site.unregister(Group)
# settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'custom_auth.accounts', # 自己的app
]

AUTH_USER_MODEL = 'accounts.GameUser'

注意,变量AUTH_USER_MODEL这个填写的只是 app_name.UserModelName 这个形式,不然会报错: ValueError: too many values to unpack

参考官方文档