Username login

The core idea of login, authentication and status maintenance, through the user’s authentication, to determine that the login user is a registered user of Meiduo shopping mall. The unique identification information of the cached user is maintained by the state, which is used to determine whether to log in later.

1. Logical analysis of user name login

2. User name login interface design

1. Request mode

options plan
Request method POST
Request the address /login/

Request parameters: form

Parameter names type Whether will pass instructions
username string is The user name
password string is password
remembered string is Whether to remember the user

3. Response result: HTML

field instructions
Login failed Response to error message
Login successful Redirect to the home page

3. User name login interface definition

Class loginView (View): """ "def get(self, request): """ Login interface """ pass def post(self, request): """ "Login logic :param request: request object :return: Login result """

4. Login backend logic with user name

Class loginView (View): """ "def get(self, request): """ Return render(request, 'login.html') def post(self, request): """ UserName = request.post. get('username') password = request.post. get('password') remembered = Request.post. Get ('remembered') if not all([username, password]): Return HTTP. HttpResponseForbidden (' lack of will pass parameters') # to determine whether the user name. 5-20 characters if not re match (r '^ [a zA - Z0 - _ - 9] {5, 20} $', username) : Return HTTP. HttpResponseForbidden (" please enter a correct username or mobile phone number ') # judgment whether the password is 8 to 20 digital if not re. Match (r '^ [0-9 a Za - z] 8, 20} {$', password) : Return the HTTP. HttpResponseForbidden (' password at least eight, User = authenticate(username=username, password=password) if user is None: return render(request, 'login.html', {'account_errmsg': 'User/password error '}) login(request, user) if remembered! Request. Session. set_expiry(0) else: Request. Session. set_expiry(None) # Responds to the login result return redirect(reverse('contents:index'))

Multi-account login

Django’s built-in user authentication system only uses the user name to authenticate a user. Therefore, in order to achieve multi-account login, user name, mobile phone number or third-party login, we need to customize the authentication back end and use other unique information to authenticate a user

Customize the user authentication backend steps

  • Create a new utils.py file in the Users application
  • Create a new class that inherits from ModelBackend
  • Rewrite the authenticate() method
  • Use the user name and phone number to query the user respectively
  • Returns the user instance that was queried

1. Custom user authentication backend

users.utils.py

from django.contrib.auth.backends import ModelBackend import re from .models import User def Get_user_by_account (account): """ select user from account: param account: user name or phone number :return: user """ try: If re.match('^1[3-9]\d{9}$', account): # user = user.objects. get(mobile=account) else: User.objects.get(username=account) except user.doesNotExist: return None else: return user class UsernameMobileAuthBackend(ModelBackend): "" def authenticate(self, request, username=None, password=None, **kwargs): """ Rewrite the authentication method to achieve multi-account login :param request: request object :param username: username: param password: password: param kwargs: other parameters :return: Mysql > select username from user where username is passed. If user = get_user_by_account(username) # if user = get_user_by_account user.check_password(password): return user

2. Configure a custom user authentication backend

1.Django comes with its own certified back-end source code

2. Configure a custom user authentication backend

# to specify a custom user authentication backend AUTHENTICATION_BACKENDS = [' users. Utils. UsernameMobileAuthBackend]

3. Test the custom user authentication backend

Home page user name display

1. Home page user name display scheme

Plan a

  • The request variable in the template renders the user name directly
  • Disadvantages: not convenient to do static home page
{% if user.is_authenticated %} <div class="login_btn fl"> Welcome to: < em > {{user. The username}} < / em > < span > | < / span > < a href = "#" > out of < / a > < / div >} else {% % < div class = "login_btn fl" > < a Href = "login. HTML" > login < / a > < span > | < / span > < a href = "register. HTML" > register < / a > < / div > {% endif %}

Scheme 2

  • Send an Ajax request for user information
  • Disadvantages: Need to send a network request
<div class="login_btn fl"> {# ajax render #} </div>

Plan 3

  • Vue reads cookies to render user information
<div v-if="username" class="login_btn fl"> [[username]] < em > < / em > < span > | < / span > < a href = "#" > out of < / a > < / div > < div v - else class = "login_btn fl" > < a Href = "login. HTML" > login < / a > < span > | < / span > < a href = "register. HTML" > register < / a > < / div >

Conclusion:

  • By comparing the three schemes, we choose the third scheme in this project

Implementation steps:

  • After registration or login, the user name is written to the cookie
  • Vue renders the home page username

2. The user name is written to the cookie

Response = redirect(reverse('contents:index')) Response.set_cookie ('username', user. Username, Max_age =3600 * 24 * 15) return response # response = redirect(reverse(contents:index)) Response. Set_cookie ('username', user.username, max_age=3600 * 24 * 15) return response

3. Vue renders the home page user name

1.index.html

<div v-if="username" class="login_btn fl"> [[username]] < em > < / em > < span > | < / span > < a href = "#" > out of < / a > < / div > < div v - else class = "login_btn fl" > < a Href = "login. HTML" > login < / a > < span > | < / span > < a href = "register. HTML" > register < / a > < / div >

2.index.js

Mounted (){this.username = getCookie('username'); },

Log out

The core idea of logout is to clean up the cached state retention information when logging in. Because the username on the front page is read from the cookie. So when you log out, you need to clear the username from the cookie.

1. Introduction to logout() method

  1. Log out:

    • Recall login: Writes the unique identification information of the authenticated user to the current session
    • Log out: The exact opposite of logging in (clean up session information)
  2. Logout () method:

    • The Django user authentication system provides thislogout()methods
    • Encapsulates the action of cleaning up a session, which helps us quickly log out a user
  3. Logout () location:

    • django.contrib.auth.__init__.pyIn the file
logout(request)

2. Use the logout() method

Class logoutView (View): """ def get(self, request): # clean up session logout(request) # logout Response = redirect(reverse('contents:index')) return response

Determine whether the user is logged in

1. Show the user center interface

Class UserInfoView(View): """ "def get(self, request): Return render(request, 'user_center_info.html')

Requirements:

  • Only when the user is logged in can the user center be accessed.
  • If the user is not logged in, access to the user center is denied and the user is directed to the login screen.

Implementation scheme:

  • You need to determine if the user is logged in.
  • Depending on whether or not you log in, you decide whether or not the user has access to the user center.

2. is_authenticateDetermine whether the user is logged in

Introduction:

  • The Django user authentication system provides methodsrequest.user.is_authenticated()To determine whether the user is logged in.
  • Returns True if login authentication is passed. Otherwise, it returns False.
  • Cons: Login validation logic is required in many places, so this code needs to be recoded several times.
Class UserInfoView(View): """ UserCenter """ def get(self, request): """ "" if request.user.is_authenticated(): "" return render(request, 'user_center_info.html') else: return redirect(reverse('users:login'))

3. Login_required decoratorDetermine whether the user is logged in

  • The Django user authentication system provides decorators

    login_required

To determine whether the user is logged in.

  • Inside encapsulatedis_authenticate
  • Location:django.contrib.auth.decorators
  • If you pass login authentication, you go inside the view and execute the view logic.
  • It is redirected to if it fails login authentication

    LOGIN_URL

The address specified by the configuration item.

  • Refers to redirect the user to the login page when the user fails login authentication.

    LOGIN_URL = '/login/'

1. The decorationas_view()Method return value

Tip:

  • Login_required decoratorYou can decorate the function view directly, but this project uses the class view.
  • as_view()The return value of the method is the function view that the class view turns into.

Conclusion:

  • If you want to useLogin_required decoratorDecorate class views, which can be decorated indirectlyas_view()Method to achieve the desired effect.
url(r'^info/$', login_required(views.UserInfoView.as_view()), name='info'), class UserInfoView(View): "" def get(self, request): """ return render(request, 'user_center_info.html')

2. Define the encapsulation of View subclassesLogin_required decorator

  • Tip:LoginRequired(object)Depends on the view classView, the reusability is very poor.
url(r'^info/$', views.UserInfoView.as_view(), name='info'), class LoginRequired(View): "" @classmethod def as_view(CLS, **initkwargs): In the # custom as_view() method, Call the parent as_view() method view = super().as_view() return login_required(view) class UserInfoView(loginRequired): "" def get(self, request): """ return render(request, 'user_center_info.html')

3. Define OBEJCT subclass encapsulationLogin_required decorator

  • Tip:LoginRequired(object)Does not depend on any view class, more reusable.
url(r'^info/$', views.UserInfoView.as_view(), name='info'), class LoginRequired(object): "" @classmethod def as_view(CLS, **initkwargs): In the # custom as_view() method, Call the parent as_view() method view = super().as_view() return login_required(view) class UserInfoView(loginRequired, view) : "" def get(self, request): """ return render(request, 'user_center_info.html')

4. Define the extension class to verify whether the user is logged in

  • Tip: Define extension classes for easy import and use in projects (meiduo_mall.utils.views.py)
Class loginRequiredMixin (object): """ @classmethod def as_view(CLS, **initkwargs):" In the custom as_view() method, Call the parent as_view() method view = super().as_view() return login_required(view) class UserInfoView(loginRequiredMixin, view) : "" def get(self, request): """ return render(request, 'user_center_info.html')

4. Use of the next parameter during login

1. The effect of the next parameter

http://127.0.0.1:8000/login/?next=/info/

2. The next parameter

  • Provided by the Django user authentication systemLogin_required decoratorUse.
  • Recorded when the user did not log in to visit the address information, can help us to achieve the user login after the success of direct access to the address visited when the login.
Next = request.get. GET ('next') if next: response = redirect(next) else: response = redirect(reverse('contents:index'))