User Authentication -------------- auth module for user authentication -------------- auth module

A, auth module

from django.contrib import auth

1, authenticate (): validate user input user name and password are the same

Provides user authentication, which validates the username and password are correct , it normally takes two keyword arguments username password

If the authentication information is valid, it returns a User object. authenticate () will be provided on a User object attribute that identifies the user authentication backend authentication and the login information is later in the process is required. When we attempted to land a take out directly from the database without authenticate () User object will complain! !

user = authenticate(username='someone',password='somepassword')

 

2, login (HttpRequest, user): Log  

This function takes an HttpRequest object and a User object certified

This function uses the session django framework of an authenticated user to attach the session id and other information.

Copy the code
from django.contrib.auth import authenticate, login
   
def my_view(request):
  username = request.POST['username']
  password = request.POST['password']
  user = authenticate(username=username, password=password)
  if user:
    login(request, user)
    # Redirect to a success page.
    ...
  else:
    # Return an 'invalid login' error message.
    ...
Copy the code

3, logout (request) Logout 

This function takes a HttpRequest object, no return value. When the function is called, the current request will clear all session information. Even if the user is not logged in, use this function also does not complain.

from django.contrib.auth import logout
   
def logout_view(request):
  logout(request)
  # Redirect to a success page.

4, is_authenticated user object ()

Claim:

  1, users log in to access some of the pages

  2, if the user is not logged on to access the page, then jump directly login page

  3, after the user completes the login screen to log in to jump in, jump address automatic access to previously visited

method one:

def my_view(request):
  if not request.user.is_authenticated():
    return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))

Method Two: Django has been good for us to design a decorator for such situations: login_requierd ()

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

If the user is not logged, it will jump to the django default login URL '/ accounts / login /' (this value can be modified by LOGIN_URL in the settings file). And passing the current url to access the absolute path (after a successful landing, you will be redirected to the path).

Two, User Object

User object properties: username, password (required) password saved to the database using a hash algorithm

is_staff: whether the user has administrative permissions for the site.

is_active: whether to allow user login, set to `` False``, you can not delete users to disable user login

2.1 、is_authenticated()

If it is true the User object, the return value of the constant to True. For checking whether the user has passed the certification.
By certification does not mean that the user has no rights, not even check whether the user is in an active state, which only indicates the success of the certification by the user. This method is very important, () to determine whether the user has logged in with request.user.is_authenticated in the background, if true, you can display the front desk request.user.name

2.2, create a user: create_user 

from django.contrib.auth.models import User
user = User.objects.create_user(username='',password='',email=''

2.3, check_password (passwd): password checking

用户需要修改密码的时候 首先要让他输入原来的密码 ,如果给定的字符串通过了密码检查,返回 True

2.4, change passwords: set_password () 

user = User.objects.get(username='')
user.set_password(password='')
user.save 

Third, simple example

log in:

Copy the code
def log_in(request):
    print(request.POST)
    if request.method =="POST":
        username = request.POST.get("username")
        password = request.POST.get("password")
        print(username,password)
        user=auth.authenticate(username=username,password=password)#验证用户名和密码
        if user:
            #如果认证成功,就让登录,这个login里面包括了session操作和cookie
            auth.login(request,user)
            return redirect("/chakan/")
        else:
            s = "用户名和密码输入错误"
            return render(request,"login.html",{"s":s})
    return render(request,"login.html")
Copy the code

修改密码:

Copy the code
def set_pwd(request):
    if request.method=="POST":
        oldpassword = request.POST.get("oldpassword")
        newpassword = request.POST.get("newpassword")
        #得到当前登录的用户,判断旧密码是不是和当前的密码一样
        username = request.user  #打印的是当前登录的用户名
        user = User.objects.get(username=username)  #查看用户
        ret = user.check_password(oldpassword)  #检查密码是否正确
        if ret:
            user.set_password(newpassword) #如果正确就给设置一个新密码
            user.save()  #保存
            return redirect("/login/")
        else:
            info = "输入密码有误"
            return render(request,"set_pwd.html",{"info":info})
    return render(request,"set_pwd.html")
Copy the code

注册:

Copy the code
def reg(request):
    if request.method=="POST":
        username = request.POST.get("username")
        password = request.POST.get("password")
        #得到用户输入的用户名和密码创建一个新用户
        User.objects.create_user(username=username,password=password)  #User是以个对象
        s = "恭喜你注册成功,现在可以登录了"
        return redirect("/login/")
    return render(request,"reg.html")
Copy the code

注销:

def log_out(request):
    auth.logout(request)
    return redirect("/login/")

 

一、auth模块

from django.contrib import auth

1 、authenticate()   :验证用户输入的用户名和密码是否相同

提供了用户认证,即验证用户名以及密码是否正确,一般需要username  password两个关键字参数

如果认证信息有效,会返回一个  User  对象。authenticate()会在User 对象上设置一个属性标识那种认证后端认证了该用户,且该信息在后面的登录过程中是需要的。当我们试图登陆一个从数据库中直接取出来不经过authenticate()的User对象会报错的!!

user = authenticate(username='someone',password='somepassword')

 

2 、login(HttpRequest, user):登录  

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

此函数使用django的session框架给某个已认证的用户附加上session id等信息。

Copy the code
from django.contrib.auth import authenticate, login
   
def my_view(request):
  username = request.POST['username']
  password = request.POST['password']
  user = authenticate(username=username, password=password)
  if user:
    login(request, user)
    # Redirect to a success page.
    ...
  else:
    # Return an 'invalid login' error message.
    ...
Copy the code

3 、logout(request)  注销用户 

该函数接受一个HttpRequest对象,无返回值。当调用该函数时,当前请求的session信息会全部清除。该用户即使没有登录,使用该函数也不会报错。

from django.contrib.auth import logout
   
def logout_view(request):
  logout(request)
  # Redirect to a success page.

4 、user对象的 is_authenticated()

要求:

  1、用户登录后才能访问某些页面

  2、如果用户没有登录就访问该页面的话直接跳转登录页面

  3、用户在跳转的登录界面中完成登录后,自动访问跳转到之前访问的地址

方法一:

def my_view(request):
  if not request.user.is_authenticated():
    return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))

方法二:django已经为我们设计好了一个用于此种情况的装饰器:login_requierd()

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

若用户没有登录,则会跳转到django默认的 登录URL '/accounts/login/ ' (这个值可以在settings文件中通过LOGIN_URL进行修改)。并传递  当前访问url的绝对路径 (登陆成功后,会重定向到该路径)。

二、User对象

User 对象属性:username, password(必填项)password用哈希算法保存到数据库

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

is_active : 是否允许用户登录, 设置为``False``,可以不用删除用户来禁止 用户登录

2.1 、is_authenticated()

如果是真正的 User 对象,返回值恒为 True 。 用于检查用户是否已经通过了认证。
通过认证并不意味着用户拥有任何权限,甚至也不检查该用户是否处于激活状态,这只是表明用户成功的通过了认证。 这个方法很重要, 在后台用request.user.is_authenticated()判断用户是否已经登录,如果true则可以向前台展示request.user.name

2.2 、创建用户:create_user 

from django.contrib.auth.models import User
user = User.objects.create_user(username='',password='',email=''

2.3 、check_password(passwd):密码检查

用户需要修改密码的时候 首先要让他输入原来的密码 ,如果给定的字符串通过了密码检查,返回 True

2.4 、修改密码: set_password() 

user = User.objects.get(username='')
user.set_password(password='')
user.save 

三 、简单示例

登录:

Copy the code
def log_in(request):
    print(request.POST)
    if request.method =="POST":
        username = request.POST.get("username")
        password = request.POST.get("password")
        print(username,password)
        user=auth.authenticate(username=username,password=password)#验证用户名和密码
        if user:
            #如果认证成功,就让登录,这个login里面包括了session操作和cookie
            auth.login(request,user)
            return redirect("/chakan/")
        else:
            s = "用户名和密码输入错误"
            return render(request,"login.html",{"s":s})
    return render(request,"login.html")
Copy the code

修改密码:

Copy the code
def set_pwd(request):
    if request.method=="POST":
        oldpassword = request.POST.get("oldpassword")
        newpassword = request.POST.get("newpassword")
        #得到当前登录的用户,判断旧密码是不是和当前的密码一样
        username = request.user  #打印的是当前登录的用户名
        user = User.objects.get(username=username)  #查看用户
        ret = user.check_password(oldpassword)  #检查密码是否正确
        if ret:
            user.set_password(newpassword) #如果正确就给设置一个新密码
            user.save()  #保存
            return redirect("/login/")
        else:
            info = "输入密码有误"
            return render(request,"set_pwd.html",{"info":info})
    return render(request,"set_pwd.html")
Copy the code

注册:

Copy the code
def reg(request):
    if request.method=="POST":
        username = request.POST.get("username")
        password = request.POST.get("password")
        #得到用户输入的用户名和密码创建一个新用户
        User.objects.create_user(username=username,password=password)  #User是以个对象
        s = "恭喜你注册成功,现在可以登录了"
        return redirect("/login/")
    return render(request,"reg.html")
Copy the code

Logout:

def log_out(request):
    auth.logout(request)
    return redirect("/login/")

 

Guess you like

Origin www.cnblogs.com/maaosheng/p/11621513.html