Django--csrf跨站请求伪造、Auth认证模块

form表单中使用跨站请求伪造html

  { % csrf_token % }
  会动态生成一个input框,内部的value是随机刷新的数据库

 

 

若是不想校验csrfdjango

  from django.views.decorators.csrf import csrf_exempt, csrf_protect后端

  而后在不想装饰的函数的上面加上@csrf_exemptsession

  

若是只想校验单独一个的话就在那个函数的上面加上@csrf_protectapp

 

 

 

在CBV中添加csrf就是经过导入第三方模块函数

  from django.utils.decorators import method_decorator工具

  而后在方法上面利用method_decorator进行装饰,第一个参数传的是csrf_protect,第二个参数name要制定方法网站

 

csrf_protect在装饰的时候跟正常的CBV的装饰器同样,也是三种方式均可以的ui

csrf_exempt只能有下面两种方式

@method_decorator(csrf_exempt, name='dispatch')
class Index(View):
    @method_decorator(csrf_exempt)
    def dispatch(self, request, *args, **kwargs):
        super().dispatch(request, *args, **kwargs)

 

 

Auth模块: 

  命令行建立超级用户

    createsuperuser

  Auth模块是Django自带的用户认证模块

    咱们在开发一个网站的时候,无可避免的须要设计实现网站的用户系统。此时咱们须要实现包括用户注册、用户登陆、用户认证、注销、修改密码等功能

    Django内置了强大的用户认证系统--auth, 它默认使用auth_user表来存储用户数据

 

  auth模块经常使用的方法:

    authenticate()

      提供了用户认证功能,即验证用户名以及密码是否正确,通常须要username、password两个关键字参数 

      若是认证成功,便会返回一个User对象

      authenticate()会在该User对象上设置一个属性来标识后端已经认证了该用户,而且该信息在后续的登录过程当中是须要的

  

    login(HttpRequest,user)

      该函数接受一个HttpRequest对象,以及一个认证过的User对象

      该函数实现一个用户登陆的功能,它本质上会在后端为该用户生成相关的session数据

 

    logout(request)

      该函数没有返回值

      当调用该函数时,当前请求session会被所有清除。该用户即便没有登陆,使用该函数也不会报错

 

    is_authenticated()

      用来判断当前请求是否经过了认证

  

    login_required()  

      auth给咱们提供的一个装饰器工具,用来快捷给某个视图函数添加登陆校验

from django.contrib.auth.decorators import login_required
      
@login_required
def my_view(request):
  ...

 

      若用户没有登陆,就会跳转到Django默认的登陆URL '/accounts/login/ ' 并传递当前访问url的绝对路径(若登录成功后,会重定向到该路径)。

      若是须要自定义登陆到URL,则须要在settings.py文件中经过LOGIN_URL进行修改

LOGIN_URL = '/login/'  # 这里配置成你项目登陆页面的路由

    create_user()

      auth提供的一个建立新用户的方法,须要提供必要的参数(username, password)等

from django.contrib.auth.models import User
user = User.objects.create_user(username='用户名',password='密码',email='邮箱',...)

    

    create_superuser()

      auth提供的一个建立新用户的方法,须要提供必要的参数(username, password)等

from django.contrib.auth.models import User
user = User.objects.create_superuser(username='用户名',password='密码',email='邮箱',...)

 

      

    check_password(password)

      auth提供的一个检查密码是否正确的方法,须要提供当前请求用户的密码,密码正确就返回True,不然就返回False

ok = user.check_password('密码')

 

  

    set_password(password)

      auth提供的一个修改密码的方法,接受要设置的新密码 做为参数

      注意:设置完必定要调用用户对象的save方法       

user.set_password(password='')
user.save()

 

  

@login_required
def set_password(request):
    user = request.user
    err_msg = ''
    if request.method == 'POST':
        old_password = request.POST.get('old_password', '')
        new_password = request.POST.get('new_password', '')
        repeat_password = request.POST.get('repeat_password', '')
        # 检查旧密码是否正确
        if user.check_password(old_password):
            if not new_password:
                err_msg = '新密码不能为空'
            elif new_password != repeat_password:
                err_msg = '两次密码不一致'
            else:
                user.set_password(new_password)
                user.save()
                return redirect("/login/")
        else:
            err_msg = '原密码输入错误'
    content = {
        'err_msg': err_msg,
    }
    return render(request, 'set_password.html', content)

 

 

 

    User对象的属性

      username、password

      is_staff:用户是否拥有网站的管理权限

      is_active:是否容许用户登陆,设置为False,能够在不删除用户的前提下禁止用户登陆

 

  扩展默认的auth_user表

    auth_user表的字段就那么几个,我在项目中没办法直接拿来使用,好比我想要存储一个用户的手机号的字段,首先想到的确定是一对一进行表与表之间的关联

    咱们能够经过继承内置的AbstractUser类,来自定义一个Model类,这样既能够根据项目需求灵活的设计用户表,又能使用Django强大的认证系统了

from django.contrib.auth.models import AbstractUser
class UserInfo(AbstractUser):
    """
    用户信息表
    """
    nid = models.AutoField(primary_key=True)
    phone = models.CharField(max_length=11, null=True, unique=True)
    
    def __str__(self):
        return self.username

    按上面的方式扩展了内置的auth_user表以后,必定要在settings.py中告诉Django,我如今使用我新定义的UserInfo表来作用户的认证,

# 引用Django自带的User表,继承使用时须要设置
AUTH_USER_MODEL = "app名.UserInfo"

    一旦咱们指定了新的认证系统所使用的的表,咱们就须要从新在数据库中建立该表,而不能继续使用原来默认的auth_user表了

相关文章
相关标签/搜索