当前位置: 移动技术网 > IT编程>脚本编程>Python > Django自定义用户认证示例详解

Django自定义用户认证示例详解

2019年06月18日  | 移动技术网IT编程  | 我要评论

怕寂寞的猫,眉山家园网,坐公交投2700元

前言

django附带的认证对于大多数常见情况来说已经足够了,但是如何在 django 中使用自定义的数据表进行用户认证,有一种较为笨蛋的办法就是自定义好数据表后,使用onetoone来跟 django 的表进行关联,类似于这样:

from django.contrib.auth.models import user
class userprofile(models.model):
 """
 用户账号表
 """
 user = models.onetoonefield(user)
 name = models.charfield(max_length=32)
 def __str__(self):
  return self.name
 class meta:
  verbose_name_plural = verbose_name = "用户账号"
  ordering = ['id']

这样做虽然可以简单、快速的实现,但是有一个问题就是我们在自己的表中创建一个用户就必须再跟 admin 中的一个用户进行关联,这简直是不可以忍受的。

admin代替默认user model

写我们自定义的 models 类来创建用户数据表来代替默认的user model,而不与django admin的进行关联,相关的官方文档在这里


from django.db import models
from django.contrib.auth.models import user
from django.contrib.auth.models import (
 baseusermanager, abstractbaseuser
)
class userprofilemanager(baseusermanager):
 def create_user(self, email, name, password=none):
  """
  用户创建,需要提供 email、name、password
  """
  if not email:
   raise valueerror('users must have an email address')
  user = self.model(
   email=self.normalize_email(email),
   name=name,
  )
  user.set_password(password)
  user.save(using=self._db)
  return user
 def create_superuser(self, email, name, password):
  """
  超级用户创建,需要提供 email、name、password
  """
  user = self.create_user(
   email,
   password=password,
   name=name,
  )
  user.is_admin = true
  user.is_active = true
  user.save(using=self._db)
  return user
class userprofile(abstractbaseuser):
 # 在此处可以配置更多的自定义字段
 email = models.emailfield(
  verbose_name='email address',
  max_length=255,
  unique=true,
 )
 name = models.charfield(max_length=32, verbose_name="用户名称")
 phone = models.integerfield("电话")
 is_active = models.booleanfield(default=true)
 is_admin = models.booleanfield(default=false)
 objects = userprofilemanager()
 username_field = 'email' # 将email 作为登入用户名
 required_fields = ['name', 'phone']
 def __str__(self):
  return self.email
 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 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 配置

class usercreationform(forms.modelform):
 """a form for creating new users. includes all the required
 fields, plus a repeated password."""
 password1 = forms.charfield(label='password', widget=forms.passwordinput)
 password2 = forms.charfield(label='password confirmation', widget=forms.passwordinput)

 class meta:
  model = models.userprofile
  fields = ('email', 'name')

 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(usercreationform, self).save(commit=false)
  user.set_password(self.cleaned_data["password1"])
  if commit:
   user.save()
  return user


class userchangeform(forms.modelform):
 """a form for updating users. includes all the fields on
 the user, but replaces the password field with admin's
 password hash display field.
 """
 password = readonlypasswordhashfield()
 class meta:
  model = models.userprofile
  fields = ('email', 'password', 'name', 'is_active', 'is_admin')
 def clean_password(self):
  return self.initial["password"]
class userprofileadmin(baseuseradmin):
 form = userchangeform
 add_form = usercreationform
 list_display = ('email', 'name', 'is_admin', 'is_staff')
 list_filter = ('is_admin',)
 fieldsets = (
  (none, {'fields': ('email', 'password')}),
  ('personal info', {'fields': ('name',)}),
  ('permissions', {'fields': ('is_admin', 'is_active', 'roles', 'user_permissions', 'groups')}),
 )
 add_fieldsets = (
  (none, {
   'classes': ('wide',),
   'fields': ('email', 'name', 'password1', 'password2')}
   ),
 )
 search_fields = ('email',)
 ordering = ('email',)
 filter_horizontal = ('groups', 'user_permissions','roles')

2.django允许您通过auth_user_model配置来引用自定义的model设置来覆盖默认user模型,这个配置的配置方法为在 settings 中加入:auth_user_model = "app.model_class" ,例如本例中我们需要在 setting 中加入以下配置:

auth_user_model = "app1.userprofile"

3.部署

python manage.py makemigrations
python manage.py migrate

创建一个新用户,此时我们就可以用这个用户来登录 admin 后台了

python manage.py createsuperuser

效果如下:

 

自定义认证

那如果我们需要使用我们自己的认证系统呢,假如我们有一个 login 页面和一个 home 页面:

from django.shortcuts import render, httpresponse, redirect
from django.contrib.auth import authenticate,login,logout
from app1 import models
from django.contrib.auth.decorators import login_required

def auth_required(auth_type):
 # 认证装饰器
 def wapper(func):
  def inner(request, *args, **kwargs):
   if auth_type == 'admin':
    ck = request.cookies.get("login") # 获取当前登录的用户
    if request.user.is_authenticated() and ck:
     return func(request, *args, **kwargs)
    else:
     return redirect("/app1/login/")
  return inner
 return wapper

def login_auth(request):
 # 认证
 if request.method == "get":
  return render(request, 'login.html')

 elif request.method == "post":
  username = request.post.get('username', none)
  password = request.post.get('password', none)
  user = authenticate(username=username, password=password)
  if user is not none:
   if user.is_active:
    login(request, user)
    _next = request.get.get("next",'/crm')
    return redirect('_next')
   else:
    return redirect('/app1/login/')
  else:
   return redirect('/app1/login/')
 else:
  pass
def my_logout(request):
 # 注销
 if request.method == 'get':
  logout(request)
  return redirect('/app1/login/')

@login_required
def home(request):
 # home page
 path1, path2 = "home", '主页'
 if request.method == "get":
  return render(request, 'home.html', locals())
 elif request.method == "post":
  pass

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对移动技术网的支持。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网