Reprinted from: original source
Django permission system auth
The auth module is a standard permission management system provided by Django, which can provide user authentication, user group and permission management.
auth can be used in conjunction with the admin module to quickly build a website management system.
Add 'django.contrib.auth' in INSTALLED_APPS to use this APP, the auth module is enabled by default.
User
User is a relational schema for maintaining user information in the auth module (inheriting models.Model), and the table in the database is named auth_user.
SQL description of User table:
CREATE TABLE "auth_user" ( "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "password" varchar(128) NOT NULL, "last_login" datetime NULL, "is_superuser" bool NOT NULL, "first_name" varchar(30) NOT NULL, "last_name" varchar(30) NOT NULL, "email" varchar(254) NOT NULL, "is_staff" bool NOT NULL, "is_active" bool NOT NULL, "date_joined" datetime NOT NULL, "username" varchar(30) NOT NULL UNIQUE )
The auth module provides many APIs to manage user information. We can import the User table for operations when necessary, such as when other tables need to be associated with User.
from django.contrib.auth.models import User
new user
user = User.objects.create_user(username, email, password)
Create a user object
user.save()
The new user needs to call the save() method to write to the database,
The auth module does not store the plaintext of the user password but stores a Hash value, such as iteratively using the Md5 algorithm.
Authenticated user
Import the function first
from django.contrib.auth import authenticate
Pass the account and credentials using keyword arguments:
user = authenticate(username=username, password=password)
Whether the password of the authenticated user is valid, if valid, return the user object representing the user, if invalid, return None.
This method does not check the is_active
flag bits.
change Password
Modifying the password is an instance method of User, which does not authenticate the user:
user.set_password(new_password)
Usually this method needs to be used in conjunction with authenticate:
user = auth.authenticate(username=username, password=old_password) if user is not None: user.set_password(new_password) user.save()
Log in
First import:
from django.contrib.auth import login
Login adds SESSION_KEY to the session to facilitate user tracking:
'login(request, user)'
login does not perform authentication, nor does it check the is_active flag bit, generally used in conjunction with authenticate:
user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user)
You auth/__init__.py
can see the source code of login in.
sign out
logout will remove the user information in the request and refresh the session:
from django.contrib.auth import logout def logout_view(request): logout(request)
Allow access only to logged in users
The view function modified by the @login_required decorator will first check whether to log in through the session key. The logged in user can perform the operation normally, and the unlogged user will be redirected to the login_url
specified location.
If the login_url parameter is not specified, redirect tosettings.LOGIN_URL
from django.contrib.auth.decorators import login_required @login_required(login_url = ' /accounts/login/ ' ) # This path is filled in according to the actual path of your own login function def my_view(request):
Group
django.contrib.auth.models.Group
The model of the user group is defined, each user group has two fields of id and name, and the model is mapped to a auth_group
data table in the database.
There is a many-to-many field in the User object, and groups
the many-to-many relationship is auth_user_groups
maintained by the data table. The Group object can user_set
query the users in the user group by reverse.
We can add or remove user groups by creating and removing Group objects.
# add group = Group.objects.create(name=group_name) group.save() # the group.delete()
We can manage the relationship between users and user groups through standard many-to-many field operations:
-
User joins user group
user.groups.add(group)
orgroup.user_set.add(user)
-
User exits user group
user.groups.remove(group)
orgroup.user_set.remove(user)
-
User logged out of all user groups
user.groups.clear()
-
All users in the user group leave the group
group.user_set.clear()
Permission
Django's auth system provides model-level permission control, that is, it can check whether a user has add (add), change (change), and delete (delete) permissions on a data table.
The auth system cannot provide object-level permission control, that is, to check whether the user has permission to add, modify, or delete a record in the data table. It can be used if object-level permission control is required django-guardian
.
Assuming that there is an article data table in the blog system to manage blog posts, auth can check whether a user has management rights to all blog posts, but cannot check whether a user has management rights to a certain blog post.
Check user permissions
user.has_perm
The method is used to check if the user has permission to operate a model:
user.has_perm('blog.add_article') user.has_perm('blog.change_article') user.has_perm('blog.delete_article')
The above statement checks whether the user has the permission to add the article model in the blog app, and returns True if the user has permission.
has_perm
It's just a permission check, even if the user doesn't have permission it doesn't prevent the programmer from doing the relevant action.
permission_required
The decorator can be used instead has_perm
and redirect to the login page or throw an exception if the user does not have the appropriate permissions.
# permission_required(perm[, login_url=None, raise_exception=False]) @permission_required('blog.add_article') def post_article(request): pass
Each model has add (add), change (change), delete (delete) permissions by default. django.contrib.auth.models.Permission
All permissions in the project are saved in the model.
The model is saved as a auth_permission
data table in the database. Each permission has four fields: id, name, content_type_id, and codename.
Manage user permissions
User and Permission are user.user_permissions
associated by many-to-many fields and are maintained by auth_user_user_permissions
data tables in the database.
-
Add permission:
user.user_permissions.add(permission)
-
Delete permission:
user.user_permissions.delete(permission)
-
Clear permissions:
user.user_permissions.clear()
A user has the privileges of the user group he belongs to, and it is a more convenient method to use the user group to manage the privileges. Group contains many-to-many fields , which are maintained by data tables permissions
in the database .auth_group_permissions
-
Add permission:
group.permissions.add(permission)
-
Delete permission:
group.permissions.delete(permission)
-
Clear permissions:
group.permissions.clear()
custom permissions
Meta custom permissions can be used when defining a Model:
class Discussion(models.Model): ... class Meta: permissions = ( ("create_discussion", "Can create a discussion"), ("reply_discussion", "Can reply discussion"), )
Determine whether the user has custom permissions:
user.has_perm('blog.create_discussion')