20 Auth authentication module

First, what is the Auth module

Django Auth module is built-in user authentication module: We are developing a site, the inevitable need to design websites to achieve the user's system. At this point we need to achieve, including user registration, user login, user authentication, log off, change passwords and other functions, we will use their own cookie and session to login authentication, it really is a troublesome thing yet.

Django as a framework for the ultimate perfectionist, of course, also think of these pain points users. It built a powerful user authentication system --auth, we do not know until we create the model table with django, perform database migration commands and commands to build the table, we find that it is not only our own table, there are some other tables, which are built in django table below

It is used by default auth_user table to store user data: first look at which fields this table have it

Two, auth module creates a superuser

Here we look at a map: the figure url you are not very familiar ah, we just create django project, in the routing layer, it will help us generate a default address for routing admin, I do not know you have I do not have access to this admin tried to address it?

Here you have not thought about this, this user and password to create me how to do, how can I log on to the real pages? Here I do as long as you follow along, you'll know how it happens?

1.首先,先去settings里到数据库配置那里,配一个数据库,最好是配一个新的数据库
2.配置完数据库以后千万别忘了去应用名或者是跟项目名同名的文件名下的__init__文件里配置如下两条代码,因为django默认是用sqlite3数据库,所以只要我们自己配置了数据库,就一定要配置这两句
    import pymysql
    pymysql.install_as_mysql()
3.打开菜单栏tools下的tool manage.py Task界面,输入下面的代码
    createsuperuser------创建超级用户
4.看下方图解

This time, our super users registered Okay, let's try the effect of the above admin address access, and can not be used on the user logs in we created: You will be surprised, landing up, but the contents inside some can not read

1572511940383

Here is thrown directly concept on the map is Django, just registered users devoted to the management model table, you can now manage all of django model table, but we have not created a model table only.

Then we look at the above-mentioned continue to see, django is the default user authentication information stored in auth_user table, take a look at this table what changes :( find out a multi-user data, it is above us registered superuser, it has all the rights of django)

Three, Auth custom login page Login superuser

According to the above examples superuser, we can use the auth module themselves to write a user's login page to see the super user cecilia we created earlier, whether the possibility of a normal login.

# 首先自定义一条url

# 利用auth模块登录超级用户
url(r'^login/$',views.login),
# views.py视图函数

# 我们既然要在视图函数中用auth模块,就要先导入这个模块
from django.contrib import auth
def login(request):
    if request.method == 'POST':
        # 获取登录页面的post请求的用户名和用户密码
        username = request.POST.get('username')
        password = request.POST.get('password')
        # 按道理来说,我们是不是应该通过表名去数据库表中查找有没有这个用户名和密码的数据
        # 但是现在这个auth_user表不是我们自己创建的模型表,所以我们没法用表名去表里查有没有这个用户数据
        # 这里就算是给了我们表名,我们就一定能够去这个表里查?
                # 不可以,
                # 应为auth模块在创建超级用户的时候,还记得存到表中的密码是密文的吧
                # 但是你通过表名,去查数据,查出来的是明文的,所以是不可以的
        
        # 所以我们要用auth模块去查询当前登录的用户,
        user_obj = auth.authenticate(username=username,password=password)
        # user_obj :当auth.authenicate帮我们校验数据的时候
        # 校验成功时,他是直接返回我们登录的用户名,但是是一个对象
        # 校验不成功,它就返回None
        print(user_obj)
        print(user_obj.username) # 可通过对象点的方法去值
        print(user_obj.password)
        if user_obj: # 判断是否有这个对象
            # 如果有值,则通过auth.login(request,name=user_obj),自动操作session
            auth.login(request,user_obj) # 这里是记录用户浏览器的状态
        else:
            return redirect('/login')   
            
    return render(request,'login.html')
// login.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="" method="post">
    {% csrf_token %} //这里当我们不注释中间件csrf的时候,post提交数据的时候,一定要加这句话
    <p>username:<input type="text" name="username"></p>
    <p>password:<input type="text" name="password"></p>
    <p><input type="submit"></p>
</form>
</body>
</html>

Now we come by to write their own login page, test module certified by the auth log in to do the check, how the situation:

  1. First, reboot your server, enter 127.0.0.1:8001/login in the browser, enter the login page, registration login command before our superuser

  1. We take a look at the return value to get through the print server auth module, to get what result
user_obj = auth.authenticate(username=username,password=password)
        # user_obj :当auth.authenicate帮我们校验数据的时候
        # 校验成功时,他是直接返回我们登录的用户名,但是是一个对象
        # 校验不成功,它就返回None
        print(user_obj)
        print(user_obj.username)  # 可通过对象点的方法去值
        print(user_obj.password)

  1. Continued access to the input 127.0.0.1:8001/login, enter the login page, f12 open developer tools to see auth module automatically help us to do session set default save the session goes on a server named django_session see table there is no saving value in the service end of the session
auth.login(request,user_obj)

Four, auth module common method

4.1 How to Create a Super User

Superuser is used to log in django admin background management

# 其实如何去创建超级用户,在上面已经有了
1. 打开tools manage.py Task终端窗口
    createsuperuser
2. 根据提示,去输入用户名,密码就好了(附图)    

4.2 How to use the normal login page verifies that the user exists or not

Auth module function is that we do not have to go through the session cookie and records the user's browser login status of

Now I will take the above example I created a good super user, to write a normal login page, I do a login check, see if you can log on successfully

# 首先默认我们已经写好了一个登录页面,现在去输入用户的用户名和密码:(默认是正确的)
# 然后利用auth模块帮我们校验这个超级用户存不存在

# 这就是在校验我输入的密码,和超级用户的密码是否匹配
user_obj = auth.authenticate(username=username,password=password)

NOTE: When the presence USER_OBJ returned to the object is a user name name can do the following; when verification fails, user_obj == None

user_obj.usernmae
user_obj.password
·····

4.3 auth save the user login status

Before we learn auth module, our own way through the session cookie and write their own to save the user logged on the server

Now auth module to help us do this thing, so with a word, use the auth module on the use of a full set, not part of his writing, some with auth

auth.login(request,user_obj)
# 在用户登录成功以后,执行这一句操作,我们会发现,在浏览器和服务端,都出现当前浏览器的session

The most important thing is: As long as we are after executing the above sentence, as long as the place to get a request, we are available through request.user get to the target user currently logged on

4.4 auth 的request.user

request.user
# 当用户登录的情况下,返回的结果是用户对象
# 当用户没有登录的情况下,返回的一个AnonymoUser---匿名用户

# 但是当我们如果需要对当前用户有没有登录,进行一些逻辑处理的时候,很明显,当用户没有登录的情况下,我们通过request.user不好进行判断呀

request.user.is_authenticated() 
# 如果用户登录:返回True
# 用户没有登录:返回False

4.5 Configuration local / global configuration decorator

What if I multiple views, I want every view function check what the user has not logged in, do not log on back to the login page if login, went back to visit our page of

So, now, is not it conceivable decorator ah, that here, decorators do not need to write our own, and follows with the auth step

from django.contrib.auth.decorators import login_required
# 局部配置,就是只对当前被装饰的有效
# 用我们以前用过的装饰器的方法,来装饰需要被装饰的视图函数
@login_requirde ## 仅仅这样是不行的,如过直接这样的话,我们用的就是auth默认的装饰器了


# 所以必须要这样写
@login_required(login_url = '/login') # 配置成我们自己的url路径
# 全局配置:在settings中配置,因为如果我们有一百个视图函数都需要用到装饰器的时候,          用局部配置的,也会出现代码的冗余现象,因为我们毕竟要写100行

# 在settings中配置如下代码
LOGIN_URL = '/login/'

# 然后我们的装饰器就可以这样写
@login_required

4.6 using the decorator implement user password changes

If I want to modify the current user's password, and change the password, I is not a normal situation, it should change the password to do in the case of user login,

We continue with the above registered user to test super good

# views.py


# 用户登录功能
def login(request):
    next_page = request.GET.get('next')
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        user_obj = auth.authenticate(username=username,password=password)
        if user_obj:
            auth.login(request, user_obj)
            if next_page:
                return redirect(next_page)
            else:
                return redirect('/login')
        return HttpResponse('用户名密码错误!')
    return render(request,'login.html')


# 修改密码
from django.contrib.auth.decorators import login_required
@login_required(login_url='/login/')
def set_pwd(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        old_pwd  =request.POST.get('old_pwd')
        new_pwd  =request.POST.get('new_pwd')
        
        # 拿到用户输入的旧密码后,通过auth模块,
        # check_password()方法,检验这个用户的密码和它输入的旧密码一致不一致
        is_right = request.user.check_password(old_pwd)
        if is_right:# 如果一致
            # 通过request.user拿到当前登录的用户对象
            # 通过set_password()方法将原密码改为用户设置的新密码
            request.user.set_password(new_pwd)

            # 写完上面的那一步还没有完,必须要写下面这句,保存到数据表中
            request.user.save()
            return redirect('/login')
    return render(request,'set_pwd.html')


# 首页
from django.contrib.auth.decorators import login_required
@login_required(login_url='/login/')
def home(request):
    return HttpResponse('我是首页')

4.7 auth how to register new users

from django.contrib.auth.models import User

User.objects.create_user(username=username,password=password)  # 创建普通用户
# 此处如果直接使用crete的话,会将密码存成明文的,下次就登录不上了
       User.objects.create_superuser(username=username,password=password,email='[email protected]') # 创建超级用户  邮箱字段必须填写

Fifth, the extension field auth_user table

Extended auth_user table fields in two ways:

The first (not recommended): use one table relationships to create, extend field

The second (by inheritance) : The original auth_user class through inheritance,

Here we mainly about the second method

思想:
 1. 首先我们在应用的模型层中导入
     from django.contrib.auth.models import AbstractUser
        
 2. 自己定义一个类继承(AbstractUser)
    注意:你继承了AbstractUser之后 你自定义的表中 字段不能跟原有的字段冲突
    
 3.一定要在settings配置文件中指定
    AUTH_USER_MODEL = 'app01.Userinfo'
    # 固定语法: AUTH_USER_MODEL = '应用名.表名'    

Note: When we need to expand the new field in auth_user table, they must be sure, the current application can not have any migration records, as long as there is migration record, it means you've auth_user Table migrated, this table model has been instantiated

Guess you like

Origin www.cnblogs.com/xichenHome/p/11774372.html