Django-access control, unable to access django Internet

Source: Internet
Author: User

Django-access control, unable to access django Internet
The user authentication system provided by django provides the access control function.1. Only login users are allowed to log onDjango users can be divided into two types: one is authenticated users, that is, in django. contrib. auth. models. user. The other is anonymous django. contrib. auth. models. anonymousUser, each user who has not accessed the database is an instance of this class, But anonymous users cannot be authenticated. That is, the is_authenticated method always returns False, or is_anonymous returns True, in the Code logic, we can determine anonymous users, deny them access (403), or redirect them to the logon page.

from django.conf import settingsfrom django.shortcuts import redirectdef my_view(request):    if not request.user.is_authenticated:        return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))    # ...

 

The above is the method to redirect to the logon page in the code, and an error message can also be returned:
from django.shortcuts import renderdef my_view(request):    if not request.user.is_authenticated:        return render(request, 'myapp/login_error.html')    # ...

 

As this is a common requirement, django provides a decorator to implement this function.
from django.contrib.auth.decorators import login_required@login_requireddef my_view(request):    ...

 

This greatly simplifies the work. Login_required (redirect_field_name = 'Next', login_url = None) if the user does not log on, the user will not be able to access the decorated view, but will be redirected to the logon page, this logon page can be specified using the login_url parameter and can be named by url, for example, @ login_required (login_url = 'login'). Of course, the premise is that the corresponding named url is required. If this parameter is not specified, the value of settings. LOGIN_URL is used. LOGIN_URL
Default: '/accounts/login/' The URL where requests are redirected for login, especially when using the login_required () decorator. this setting also accepts named URL patterns which can be used to reduce configuration duplication since you don't have to define the URL in two places (settings and URLconf ). you can see that it has its default value. If you do not give the parameter and the logon address is not the default value, the 404 error will be triggered, that is, the page will be redirected to, but it cannot be found. If the value of force rewrite is None, TypeError is triggered. If DEBUG is set to False, the error is a series of server errors of 500. However, during redirection, the next query parameter is included, for example, http: // 127.0.0.1: 8000/account/login /? Next =/account/change_info so that you can get the page you want to visit before logging on (here is the/account/change_info page), and then redirect back after logging on, instead of blindly redirecting to the home page, the user experience will be better. The following is the cooperation in the logon View:
Next_to = request. GET. get ('Next', None) # obtain whether there is a next redirection. It is a relative path, excluding the scheme and domain name if next_to: return redirect (next_to)

 

Of course, you can also change the redirect_field_name to change the name of next. Of course, you also need to adjust it in the logon view, or set it to None to cancel the behavior of parameters attached. Note: login_required does not check whether the user is in the active status (is_active). The default background template used to process user logon does not reject non-active user logon before 1.10, whereas login_required does not check whether the user is in the active status (is_active. This means that if you are using a version earlier than 1.10, you must reject inactive user logon in the Code logic.
If user. is_active: # if the user is active, that is, the user is not frozen, and the user is frozen before 1.10, the user can log on by default, so you need to authenticate the login (request, user) # log on ...... # other processing else: return HttpResponse ('user frozen ')

 

  2. allowing only the staff user to access a view django also provides a convenient decorator to implement this function: staff_member_required (redirect_field_name = 'Next', login_url = 'admin: login ') it can be seen that it is almost the same as the above login_required parameter, but the default value is somewhat different, and the usage is the same, but there is no settings. LOGIN_URL. Note that, by default, the url is redirected to the admin logon page. Be careful when you want to hide the portal by using complicated URLs. This decorator is used on the admin views that require authorization. A view decorated with this function will having the following behavior: the decorator has been used by the admin view and its behavior is as follows:
  • If the user is logged in, is a staff member (User. is_staff = True), and is active (User. is_active = True), execute the view normally.
If the user has logged on and is an active member of the staff identity, the decorated view is executed normally.
  • Otherwise, the request will be redirected to the URL specified by the login_url parameter, with the originally requested path in a query string variable specified by redirect_field_name. For example:/admin/login /? Next =/admin/polls/question/3 /.
Otherwise, it will be redirected to login_url with query parameters. Example usage: Use Case:
from django.contrib.admin.views.decorators import staff_member_required@staff_member_requireddef my_view(request):    ...

 

The usage of login_required () is basically the same. 3. Simple function test and verification method  Django provides a decorator that allows us to customize a simple verification function. Only after passing this verification function can we access the specified view. User_passes_test (func [, login_url = None, redirect_field_name = REDIRECT_FIELD_NAME]) you can see that there is one more parameter than the two decorator above. This parameter is used to specify the verification function. For example, I want to verify whether a user's mailbox meets the format I want: original verification method:
from django.shortcuts import redirectdef my_view(request):    if not request.user.email.endswith('@example.com'):        return redirect('/login/?next=%s' % request.path)    # ...
Verify whether the view function ends with @ example.com. The following is the decorator verification method:
from django.contrib.auth.decorators import user_passes_testdef email_check(user):    return user.email.endswith('@example.com')@user_passes_test(email_check)def my_view(request):    ...

 

Note: The email_check function returns a Boolean value in essence. Therefore, when using a custom function, True is returned to indicate pass, and False is returned to indicate no pass. If it fails, the system redirects to the logon page. Other details are the same as those of the previous two decorator. Class-based view implementationClass-based views inherit the LoginRequiredMixin class when implementing login_required behavior, place it on the leftmost of the inheritance tree, and write the corresponding implementation in the class. For example:
from django.contrib.auth.mixins import LoginRequiredMixinclass MyView(LoginRequiredMixin, View):    login_url = '/login/'    redirect_field_name = 'redirect_to'

 

Note: View is a general View, and no code is imported here. For more information, see class-based View. More attributes are available. For details, refer to the AccessMixin class. The implementation of user_passes_test behavior is similar. First, inherit the UserPassesTestMixin class (on the far left), and then override the test_func method in the class. This method also returns a Boolean value. New in Django 1.9. 
from django.contrib.auth.mixins import UserPassesTestMixinclass MyView(UserPassesTestMixin, View):    def test_func(self):        return self.request.user.email.endswith('@example.com')

 

Note: The above two do not verify whether they are active users, so be careful when using them.

Related Article

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.