django 用户管理系列:1 user


 

    • user
      • 创建用户
      • 创建超级用户
      • 更新密码
      • 用户验证

 


user

user 对象是授权系统的核心、用户可以分成两类 1):superuser 2):staff;下面是user表的结构

create table auth_user (
    /*
    用户
    */
    id           int(11)              not null auto_increment,
    password     varchar(128)         not null,
    last_login   datetime(6)          DEFAULT NULL,
    is_superuser tinyint(1)           not null,
    username     varchar(150)         not null,
    first_name   varchar(30)          not null,
    last_name    varchar(150)         not null,
    email        varchar(254)         not null,
    is_staff     tinyint(1)           not null,
    is_active    tinyint(1)           not null,
    date_joined  datetime(6)          not null,

    primary key (id),
    unique  key username (username)
)
  1. 创建用户

    通过user.objects.create_user方法创建用户

    import django
    django.setup()
    
    from django.contrib.auth.models import User
    
    u = User.objects.create_user('jianglegege','[email protected]','mypassword')
    

    数据库的user表保存如下行

    select  * from auth_user \G
    *************************** 1. row ***************************
              id: 1
        password: pbkdf2_sha256$100000$qOjRhC0Rrzfe$IyyhAkh31+tlPs/YrK+3HwQXupbyKWNE5ouDdDd97xg=
      last_login: NULL
    is_superuser: 0
        username: jianglegege
      first_name: 
       last_name: 
           email: 127.0.0.1@qq.com
        is_staff: 0
       is_active: 1
     date_joined: 2018-05-24 04:58:38.617093
    1 row in set (0.00 sec)      
    

    现给出源码中create_user的原型:

    class UserManager(BaseUserManager):
        use_in_migrations = True
    
        def _create_user(self, username, email, password, **extra_fields):
            """
            Create and save a user with the given username, email, and password.
            """
            if not username:
                raise ValueError('The given username must be set')
            email = self.normalize_email(email)
            username = self.model.normalize_username(username)
            user = self.model(username=username, email=email, **extra_fields)
            user.set_password(password)
            user.save(using=self._db)
            return user
    
        def create_user(self, username, email=None, password=None, **extra_fields):
            extra_fields.setdefault('is_staff', False)
            extra_fields.setdefault('is_superuser', False)
            return self._create_user(username, email, password, **extra_fields)  
            
    

    建议在创建user对象时把指定参数名、这样比较好理解

    u = User.objects.create_user(username='neeky',email='[email protected]',password='mypassword')
    

  2. 创建超级用户

    超级用户可以在命令行中创建

    python3 manage.py createsuperuser --username=admin --email[email protected]
    
    Password:
    Password (again):
    

    Django会提示输入密码和确认密码,数据库中针对超级用户会保存如下信息:

    *************************** 3. row ***************************
              id: 3
        password: pbkdf2_sha256$100000$rHeJUU5jdYjk$iV+n2op/EfHj1jmvHQSwKiNusWsg2Xt+L5as4hJhdTU=
      last_login: NULL
    is_superuser: 1
        username: admin
      first_name: 
       last_name: 
           email: 127.0.0.1@qq.com
        is_staff: 1
       is_active: 1
     date_joined: 2018-05-24 05:17:09.110324
    3 rows in set (0.00 sec)
    
  3. 更新密码

    由上面的内容可以知道django对用户密码是取胜密文保存的、人肉计算加密串是不现实的、所以还是要通过django提供的接口来修改密码;django提供了两种修改密码的方式 1):命令行 2):user对象的set_password()方法

    1)、命令行方式:

    python3 manage.py changepassword admin 
    Changing password for user 'admin'
    Password: 
    Password (again): 
    Password changed successfully for user 'admin'
    

    2)、实例方法:

    import django
    django.setup()
    
    from django.contrib.auth.models import User
    u = User.objects.get(username='admin')
    u.set_password('127.0.0.1@password')
    u.save()
    
  4. 用户验证

    django 通过authenticate函数完成用户验证

    def authenticate(request=None, **credentials):
        """
        If the given credentials are valid, return a User object.
        """
        for backend, backend_path in _get_backends(return_tuples=True):
            try:
                user = _authenticate_with_backend(backend, backend_path, request, credentials)
            except PermissionDenied:
                # This backend says to stop in our tracks - this user should not be allowed in at all.
                break
            if user is None:
                continue
            # Annotate the user object with the path of the backend.
            user.backend = backend_path
            return user
    
        # The credentials supplied are invalid to all backends, fire signal
        user_login_failed.send(sender=__name__, credentials=_clean_credentials(credentials), request=request)
    
    

    由上面定义可知在验证成功后会返回一个User类的实例、如果没有成功会返回一个None值

    from django.contrib.auth import authenticate
    u = authenticate(username='admin',password='127.0.0.1@password')
    if u != None:
        print(u.username) # admin
    else:
        print('error')
    

    注意:request参数是可选的

你可能感兴趣的:(django 用户管理系列:1 user)