The built-in permissions control in Django 3-login Logout

Source: Internet
Author: User
Tags anonymous auth
The built-in permissions control in Django 3-login Logout

The above two articles, on the core model object user API of the Django authentication system and related usage, continue in depth to discuss how to use the authentication system in the Web.

As I said before, the Django system has three cores, User,permission,group.

In Web applications, the first step in any privilege system is user identification, which is what we often call login. Only the correct login check, know who the user is, to be able to know what the user can do, that is, licensing (Permission) need to be responsible for the solution, and group is a batch set license when a convenient means. authentication for Web requests:

Django has a set of methods to add permission validation related methods to the request object that each view method can receive. To do this, you first need to: Install Sessionmiddleware and Authenticationmiddleware. The installation method adds the above two middleware classes to the middleware_classes variable in the settings file. Middleware's design is embodied in almost any web framework, except that the terms and means of implementation are not the same, such as the Interceptor Interceptor in Struts2, which is implemented by recursive stack of functions (not seen in other frameworks). The design idea is to enter the final processing method before the request through a pretreatment, in the processing method after processing after one after another, the order is exactly the opposite. A little bit topic, please see example:

1 middleware_classes = (
2     ' Django.contrib.sessions.middleware.SessionMiddleware ',
3     ' Django.middleware.locale.LocaleMiddleware ',
4     ' Django.middleware.common.CommonMiddleware ',
5     ' Django.middleware.csrf.CsrfViewMiddleware ',
6     ' Django.contrib.auth.middleware.AuthenticationMiddleware ',
7     ' Django.contrib.messages.middleware.MessageMiddleware ',
8     ' Django.middleware.transaction.TransactionMiddleware ',
9)

Once installed, in view, we can use Request.user to get the current login user object. If the current user does not log in, then Request.user will be the Anonymoususer object we mentioned before. We can distinguish between the two by using the is_authenticated () method of the user object:?

1 2 3 4 If request.user.is_authenticated (): # Do something for the authenticating user. else: # Do something for anonymous users who are not logged in.

   so how to log in to a user.

Requires two functions: Authenticate (Username,password) and login (Request,user), located in the Django.contrib.auth module;

These two methods need to be used in combination,

The 1.authenticate (Username,password) function requires two parameter Username,password and returns the user object if the checksum is passed, if the checksum does not return none through, for example:?

1 2 3 4 5 6 7 8 9 From Django.contrib.auth Import Authenticate user = Authenticate (username = ' john ', password = ' secret ') if user isn't      None:if User.is_active:print "You provided a correct username and password!" Else:print "Your account has been disabled!" Else:print "Your username and password were incorrect."

The

2.login accepts two parameters, the first is the request object, and the second is the user object. The login method uses Sessionmiddleware to deposit UserID into session. Note that when the user is not logged in, there is also a session of anonymous users, after their landing, the previous anonymous session in the information retained, will be retained. The two methods are used in combination and must be called first, because the method records the user's authenticate on a property that is used by the subsequent login process, for example:?

1 2 3 4 5 6 7 8 9 from Django.contrib.auth import Authenti Cate, login   def my_view (request):      username = Request. post[' username ']      password = Request. post[' password ']      user = Authenticate (username = username, password = password)   &nbs p;  if user is not None:          if user.is_active:    & nbsp;         Login (request, user)               jump to the success page.          Else:               # returns an invalid account error      else:          # Returns the login Failure page.

We can also use the authenticate () for a user-specific authentication, directly using several user-independent functions for password-related checksums, The following methods are available in Django1.4 as well as in the new version, located in Module Django.contrib.auth.hashers:check_password (password,encoded): The first parameter is a plaintext password. The second parameter is the encrypted password. Returns true with a checksum, not by returning false; Make_password (Password[,salt,hashers]): Returns an encrypted password based on the given plaintext password, salt, and the cryptographic algorithm that the Django supports. If the value provided by password is none, then the return value will never pass the Check_password () method. This return value is a specific contract value and is currently '! '; Is_password_usable (Encoded_password): Determines whether a given string is a hashed password and has the opportunity to pass the validation of the Check_password () function. Next, how to log out a user.

We use the Django.contrib.auth.logout function to log out the user logged in with the Django.contrib.auth.login function.

Logout (Requet)

The function has only one argument, which is the request. There is no return value, and no exception is thrown even if the current user does not log in.

Example:?

1 2 3 4 5 From Django.contrib.auth import logout def logout_view (Request): Logout (Request) # Redirect to successful Logout interface

This method clears all the data stored in the user's session so that no one can log in with the current user's browser and then view the current user's data, and recall that login retains the anonymous user's session data. If you need to add something to the user session after the logout, you need to do so after the logout method call. Next, we introduce the two signals of login and logout.

The Django signal system is a simple and practical framework for event definition, event generation, event monitoring, and event handling, which you can refer to Django's documentation on signal. At the two important points of landing and logging, two signal:django.contrib.auth.signals.user_logged_in were provided django.contrib.auth.signals.user_logged_ Out

There are three parameters that will be passed along with Singal: Sender:user class, if it is logout event the value may be none if the user simply does not validate the pass. Request:httprequest Object User:user Object, if it is logout event this value may be none if the user simply does not validate the pass.

A recurring simple requirement is to control some view (called the action method in struts) only for logged-in users, and if the Logged-on user requests the view, it jumps to the login interface for landing. To do this, we can do this:?

1 2 3 4 5 6 From django.http import Httpresponseredirect def my_view (request): If not request.user.is_authenticated (): Return Httpresponseredirect ('/login/?next=%s '% request.path) # ...

You can also do this and return a wrong page:?

1 2 3 4 def my_view (Request): If not request.user.is_authenticated (): Return Render_to_response (' Myapp/login_error. html ') # ...

The more elegant way is to use decorator:

Django.contrib.auth.decorators.login_required ([Redirect_field_name=redirect_field_name,login_url=none])
The login_required () adorner function does the following things:
If the current user does not log in, jump to settings. Login_url, and passes the current absolute path to the URL request parameter, for example:/accounts/login/?next=/polls/3/If the current user has logged in, execute the view method. The method in view can assume that the current user has logged in.

The Login_required method accepts two parameters: Redirect_field_name: The default value is next. Used to define the URL of the access interface before the login succeeds. Login_url: The default value is settings. Login_url. The URL used to specify the login interface. If you do not pass in the change parameter, you need to ensure the settings. The value of the Login_url is set correctly.

login_required Adorner usage without parameters:?

1 2 3 4 5 From django.contrib.auth.decorators import login_required @login_required def my_view (request): ...

How to pass parameters:?

1 2 3 4 5 From django.contrib.auth.decorators import login_required @login_required (redirect_field_name = ' My_redirect_field ') def my_view (Request): ...
?
1 2 3 4 5 From django.contrib.auth.decorators import login_required @login_required (login_url = '/accounts/login/') def my_view ( Request):.

These are some of the APIs that Django offers to complete login and logout related, and they can be very good for users to authenticate, that is, who the user is the system has been figured out, and then the more fine-grained judgments, to determine what the person can do, Which is the use of permission license. See the-authentication-built-in version of the permissions control in Django-4.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.