Django User Authentication System (3) groups and permissions, django Authentication

Source: Internet
Author: User

Django User Authentication System (3) groups and permissions, django Authentication

Django's permission system is simple. It can grant users or users in groups permissions.

This permission system is used in the Django admin background, but it can also be used in your own code.

The User object has two ManyToManyField fields: groups and user_permissions.

    groups = models.ManyToManyField(Group, verbose_name=_('groups'),        blank=True, help_text=_('The groups this user belongs to. A user will '                                'get all permissions granted to each of '                                'their groups.'),        related_name="user_set", related_query_name="user")    user_permissions = models.ManyToManyField(Permission,        verbose_name=_('user permissions'), blank=True,        help_text=_('Specific permissions for this user.'),        related_name="user_set", related_query_name="user")

You can access them like other django models:

myuser.groups = [group_list]myuser.groups.add(group, group, ...)myuser.groups.remove(group, group, ...)myuser.groups.clear()myuser.user_permissions = [permission_list]myuser.user_permissions.add(permission, permission, ...)myuser.user_permissions.remove(permission, permission, ...)myuser.user_permissions.clear()
Permission Permissions

Permissions exist as a Model. Creating a Permission is to create a Permission Model instance.

@python_2_unicode_compatibleclass Permission(models.Model):    """    The permissions system provides a way to assign permissions to specific    users and groups of users.    The permission system is used by the Django admin site, but may also be    useful in your own code. The Django admin site uses permissions as follows:        - The "add" permission limits the user's ability to view the "add" form          and add an object.        - The "change" permission limits a user's ability to view the change          list, view the "change" form and change an object.        - The "delete" permission limits the ability to delete an object.    Permissions are set globally per type of object, not per specific object    instance. It is possible to say "Mary may change news stories," but it's    not currently possible to say "Mary may change news stories, but only the    ones she created herself" or "Mary may only change news stories that have a    certain status or publication date."    Three basic permissions -- add, change and delete -- are automatically    created for each Django model.    """    name = models.CharField(_('name'), max_length=255)    content_type = models.ForeignKey(ContentType)    codename = models.CharField(_('codename'), max_length=100)    objects = PermissionManager()    class Meta:        verbose_name = _('permission')        verbose_name_plural = _('permissions')        unique_together = (('content_type', 'codename'),)        ordering = ('content_type__app_label', 'content_type__model',                    'codename')    def __str__(self):        return "%s | %s | %s" % (            six.text_type(self.content_type.app_label),            six.text_type(self.content_type),            six.text_type(self.name))    def natural_key(self):        return (self.codename,) + self.content_type.natural_key()    natural_key.dependencies = ['contenttypes.contenttype']

Field fields

Name: required. 50 characters or less, for example, 'can vote'

Content_type: required. A reference to the table in the django_content_type database. The table contains the Model record of each application.

Codename: required, 100 characters or less, for example, 'can _ vote '.

If you want to create permissions for a Model:

from django.db import modelsclass Vote(models.Model):   ...    class Meta:        permissions = (("can_vote", "Can Vote"),)

If the Model is in the application foo, the permission is expressed as 'foo. can_vote ', and check whether a user has the permission myuser. has_perm ('foo. can_vote ')

Default permissions

If django. contrib. auth has been configured in INSTALLED_APPS, it ensures that three default permissions are created for each Django Model in installed applications: add, change, and delete.

These permissions will be created when you first run manage. py migrate (syncdb before 1.7. At that time, all models will create permissions. The new models created after this will create these default permissions when you run manage. py migrate again. These permissions correspond to the creation, deletion, and modification actions on the admin management interface.

Suppose you have an app foo with a model Bar, and you can test the basic permissions using the following methods:

Add: user. has_perm ('foo. add_bar ')
Change: user. has_perm ('foo. change_bar ')
Delete: user. has_perm ('foo. delete_bar ')
Permission model is generally not directly used.

Group Groups

A group also exists as a Model:

@python_2_unicode_compatibleclass Group(models.Model):    """    Groups are a generic way of categorizing users to apply permissions, or    some other label, to those users. A user can belong to any number of    groups.    A user in a group automatically has all the permissions granted to that    group. For example, if the group Site editors has the permission    can_edit_home_page, any user in that group will have that permission.    Beyond permissions, groups are a convenient way to categorize users to    apply some label, or extended functionality, to them. For example, you    could create a group 'Special users', and you could write code that would    do special things to those users -- such as giving them access to a    members-only portion of your site, or sending them members-only email    messages.    """    name = models.CharField(_('name'), max_length=80, unique=True)    permissions = models.ManyToManyField(Permission,        verbose_name=_('permissions'), blank=True)    objects = GroupManager()    class Meta:        verbose_name = _('group')        verbose_name_plural = _('groups')    def __str__(self):        return self.name    def natural_key(self):        return (self.name,)

Field fields:

Name: required, 80 characters or less, for example, 'awessome users '.

Permissions: ManyToManyField to Permission

group.permissions = [permission_list]group.permissions.add(permission, permission, ...)group.permissions.remove(permission, permission, ...)group.permissions.clear()
Programmatically creating permissions

In addition to using Model meta to create permissions, you can also directly use code to create permissions.

For example, create a can_publish permission for the BlogPost model in the myapp application:

from myapp.models import BlogPostfrom django.contrib.auth.models import Group, Permissionfrom django.contrib.contenttypes.models import ContentTypecontent_type = ContentType.objects.get_for_model(BlogPost)permission = Permission.objects.create(codename='can_publish',                                       name='Can Publish Posts',                                       content_type=content_type)

A permission can be granted to a User object through its user_permissions attribute or a Group through its permissions attribute.

Permission Cache

Users can be cached during permission check. If a new permission is granted to a User, immediate check will not be performed. The simplest way is to refetch the User object.

From django. contrib. auth. models import Permission, Userfrom django. shortcuts import get_object_or_404def user_gains_perms (request, user_id): user = get_object_or_404 (User, pk = user_id) # The permission check caches the current permission set user. has_perm ('myapp. change_bar ') permission = Permission. objects. get (codename = 'change _ bar') user. user_permissions.add (permission) # Check the permission cache set user. has_perm ('myapp. change_bar ') # False # request the new instance user = get_object_or_404 (User, pk = user_id) # Permission cache is repopulated from the database user. has_perm ('myapp. change_bar ') # True...
Permission decorator

Permission_required (perm [, login_url = None, raise_exception = False])

Check whether a user has a certain permission, similar to @ login_required ()

from django.contrib.auth.decorators import permission_required@permission_required('polls.can_vote', login_url='/loginpage/')def my_view(request):    ...
Permissions in the template

The user permission is stored in the template variable {perms}, which is the django. contrib. auth. context_processors.PermWrapper instance.

{{ perms.foo }}

The preceding single attribute is the proxy of User. has_module_perms. True if the user has any permission in foo

{{ perms.foo.can_vote }}

The above two-level property query is the proxy of User. has_perm. if the User has foo. can_vote permission, the value is True.

For example:

{% if perms.foo %}    <p>You have permission to do something in the foo app.</p>    {% if perms.foo.can_vote %}        <p>You can vote!</p>    {% endif %}    {% if perms.foo.can_drive %}        <p>You can drive!</p>    {% endif %}{% else %}    <p>You don't have permission to do anything in the foo app.</p>{% endif %}

Or:

{% if 'foo' in perms %}    {% if 'foo.can_vote' in perms %}        <p>In lookup works, too.</p>    {% endif %}{% endif %}

  


In linux, how does one Change User Permissions so that each user has different merits?

In fact, the first floor is already detailed. I think you should first clarify several concepts: operating system users, system superusers, common users, Administrator roles, Operator roles, and common user roles.
1. First, the first three users are available for Logon on unix or linux.
2. The last three are logical concepts, which correspond to multiple operating system users. For example, "I" and "you" can be administrators, the system Super User password can be owned at the same time, but we may not be able to directly log on to the system Super User remotely. We need to "my" system user to log on remotely and su to the Super User.
3. By default, system superusers can operate on other system users. Therefore, "who" acts as the Administrator has two meanings: 1) who owns the superuser password; 2) do they own their own system users for su to Super Users?
4. Other non-system superusers cannot manage other users. Therefore, the "operator" and "common user" You call are non-system superusers on linux and unix.
5. File permissions are limited and controlled by the user owner and group.

Therefore, you need to rely on user groups and file permissions for control. For example:
Root is a super user, group is system, dns
Root can act as the administrator. The user password can be authorized to the administrator role. The administrator role can have an operating system user, such as john, whose group is stuff)
Normal user bob group is dns (can be used as operator)
The pop group for common users is stuff (it can be used as a common user)

If the network element configuration file is dns. conf, its permissions are set by the Administrator (who owns the user john ).
After logging on to the system, set the following parameters:
$ Su-root
# Chown root: dns. conf
# Chmod 775 dns. conf
After this setting, the effect is as follows:
The root user, that is, the administrator can modify the file and manage user bob and pop.
Bob user, that is, the operator, can modify the file and cannot manage root and pop users and all other users.
Pop users, that is, normal users, can only view this file. Users root and bob and all other users cannot be managed.

What is the relationship between user permissions in Web systems? Is it one-to-many or many-to-many? Are there any relationships between them?

Preface:

Permissions are often an extremely complex issue, but they can also be expressed simply as a logical expression that determines whether the logical expression "who performs how operations on what (which)" is true. For different applications, You need to weigh n solutions, such as maintainability, flexibility, and integrity, based on the actual situation of the project and the specific architecture, and select a suitable solution.

Objectives:

Intuitive, because the system will eventually be maintained by the end user, and the intuitive and easy-to-understand permission assignment makes it very important. The system has worked tirelessly to implement group inheritance, in addition to functional requirements, more importantly, it is intuitive enough.

Simple, including the simplicity of concept, quantity, meaning, and functionality. It is unrealistic to use a permission system to solve all permissions. In the design, part of the frequently-changed "Custom" features are judged as the business logic, this idea is based on the logic of determining the parts that often share the "General" characteristics as the Permission Logic.

Scalability. The group concept can be defined in groups while effectively avoiding redefinition.

Status quo:

There are generally three access control methods in the enterprise environment:

1. Autonomous access control method. At present, the access control module in most information systems in China is based on the access control list (acls) in the autonomous access control method ).

2. Forced access control method. It is used for military applications with multiple levels of security.

3. Role-Based Access Control (rbac ). It is currently recognized as an effective solution to centralized resource access control for large enterprises. The two major features are as follows: 1. Reduce the complexity of authorization management and reduce management overhead. 2. flexible support for enterprise security policies and great scalability for enterprise changes.

Terms:

Coarse granularity: indicates the class level, that is, only the type of the object is considered, not a specific feature of the object.

Instance. For example, in user management, creation and deletion are treated equally for all users, but do not differentiate the specific object instances for operations.

Fine Granularity: indicates the instance level, that is, the instance of the specific object needs to be considered.

A specific instance is considered only after a coarse-grained object category is taken into account. For example, to list and delete a contract, you must determine whether the contract instance is created by the current user.

Principles:

The permission logic works with the business logic. That is, the permission system provides services for the business logic. A considerable number of fine-grained permission issues are extremely unique and have no universal significance. They can also be understood as part of the "business logic. For example, the requirement is: "The contract resource can only be deleted by its creator, users in the same group as the creator can be modified, and all users can browse ". This can be considered as a fine-grained permission issue or a business logic issue. Here it is a problem of business logic, which should not be considered too much in the entire permission system architecture design. Of course, the permission system architecture must also support such control judgment. In other words, the system provides sufficient but not full control capabilities. That is, the design principle is: "The system only provides coarse-grained permissions, and fine-grained permissions are considered to be the responsibility of business logic ".

It should be emphasized again that the permission system described here is only an "incomplete" permission system, that is, it does not provide all solutions to the permission issue. It provides a foundation and solves the "common" (or coarse-grained) parts. Based on this, according to the unique permission Requirements of the "business logic", the remaining (or fine-grained) part of the code is complete. Back to the permission issue formula, the general design only solves the problem of who + what + how. Other permission issues are left to the business logic.

Concept:

Who: Permission owner or subject (principal, user, group, role, actor, etc)

What: the target object or resource (resource, class ).

How: specific permissions (privilege, positive authorization and negative authorization ).

Role: a role with a certain number of permissions.

Operator: operation. Indicates how to operate on what.

Note:

User: With role... the remaining full text>

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.