当前位置:网站首页>Login to homepage function implementation

Login to homepage function implementation

2022-07-27 08:25:00 qishaoawei

1 Preparation for creating a new project

1.1 Create a new project in the command box

Open the specified folder , Enter cmd Open the command line
django-admin startproject Project name Create project

1.2 Create sub applications in new projects

python manage.py startapp Subapplication name

1.3 stay settings.py Registration in file

stay settings.py Register the sub application in the file
Cross domain is also done by the way
The authentication model class is also done
DRF engineering
Download third-party modules
Install in the black window
pip install djangorestframework

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
	'corsheaders',  # Configure cross domain 
    'rest_framework',   # To configure drf frame 
    ' The name of the created sub application '    # Register subapplication 
]
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    # 'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'corsheaders.middleware.CorsMiddleware'   #  Add cross domain Middleware 
]
CORS_ORIGIN_WHITELIST=[
    'http://127.0.0.1:8080',
    'http://localhost:8080'
]
CORS_ALLOW_CREDENTIALS=True
CORS_ALLOW_METHODS=('*')
CORS_ALLOW_HEADERS=('*')
# User authentication model class 
AUTH_USER_MODEL=' Subapplication name . Model class name '

1.5 Configuration database

stay settings.py In the file

#  Configuration database 
DATABASES = {
    
    'default': {
    
        'ENGINE': 'django.db.backends.mysql',  #  Use mysql database 
        'HOST': 'localhost',  #  host 
        'PORT': 3306,  		#  port 
        'USER': 'root',  	#  The user name of the database 
        'PASSWORD': ' password ', #  Database password 
        'NAME': ' Database name created ',  	#  Database name 
    }
}

1.6 Modify language and time zone

stay settings.py In the file

LANGUAGE_CODE = 'zh-Hans'  # Language 

TIME_ZONE = 'Asia/Shanghai'  # The time zone 

1.7 mount this database

In a folder with the same name as the project name init.py Install

import pymysql
pymysql.install_as_MySQLdb()

1.8 Create model classes

In the sub application folder models.py establish

from django.db import models
# Create your models here.
#user
from django.contrib.auth.models import AbstractUser
from django.utils import timezone
class User(AbstractUser):
    mobile=models.CharField(' cell-phone number ',max_length=11)
    last_login = models.DateTimeField(' Last login time ',default=timezone.now)
    def __str__(self):
        return self.username
    class Meta:
        db_table='user'

1.9 After creating the model class, migrate

Execute at the terminal within the project
Generate migration file :python manage.py makemigrations
Perform the migration :python manage.py migrate
If the migration goes wrong , Delete the database and create a new database , The generated migration file is also deleted , Redo the above 2 A step

Authentication model class

stay settings.py Registration in file

# User authentication model class 
AUTH_USER_MODEL='users.User'

Log in to the back-end interface Realization

Login interface
api: /users/logincount/
method: POST
data:
{
username: this.username,
password: this.password,
mobile: this.phone,
code: this.smscode
}
 
Respond to :
code == “204” The verification code is expired or wrong
code == “205” Wrong user name or password
code == “206” No administrator rights
code == “207” The password has been reset
code == “200” Login successful , Enter the home page
code == “201” Registered successfully , You need to apply for administrator permission backstage superuser
You must be an administrator to log in , namely is_staff=True & is_active=True; These can be used superuser Modify in the background !!!

Login logic :

  1. The first time a user logs in , Use the mobile verification code to register
    Store user name 、 password 、 cell-phone number , return 201
  2. User No Two Second and n Secondary logon , Password authentication is preferred ;
    user name 、 The passwords are correct , Check whether the user has administrator rights ( Only is_staff=True&is_active=True when , To log in ), Return the response respectively ;
  3. user 、 When password verification fails , Check whether there is SMS verification code , There is an SMS verification code ( If it passes the verification, reset the password , return 207);
    No SMS verification code , Go straight back to 205

Authoring views

from rest_framework.views import APIView
from rest_framework.response import Response
from users.models import User
import random,redis
# View of login LoginAPIView
from django.contrib.auth.hashers import check_password
from datetime import datetime
from rest_framework_jwt.utils import jwt_encode_handler,jwt_payload_handler
class LoginAPIView(APIView):
    def post(self,request):
        #1. Get the previous data 
        username=request.data.get('username')
        password=request.data.get('password')
        mobile=request.data.get('mobile')
        smsCode=request.data.get('smsCode')
        #2. Judge whether it is a new user ,
        user=User.objects.filter(username=username).first()
        redis_conn=redis.Redis(host='127.0.0.1',port=6379,password='shayebushi')
        if user:
            # This user is the second time or n Secondary logon , Password authentication is preferred , If the password is wrong, consider SMS 
            if check_password(password,user.password):
                # The password is correct , Determine whether the password is an administrator 
                if user.is_staff and user.is_active:
                    # Allow successful login 
                    token=self.gen_token(user)
                    user.last_login=datetime.now()
                    user.save()
                    return Response({
    
                        'code':200,
                        'msg':' Landing successful , Enter the home page ',
                        'data':{
    
                            'uid': user.id,
                            'username': user.username,
                            'token': token
                        }
                    })
                else:
                    return Response({
    
                        'code':206,
                        'msg':' No administrator rights '
                    })

            else:
                # Incorrect password , Consider whether there is SMS verification code , If you have any smsCode Belongs to password reset 
                if smsCode:
                    # Incoming SMS verification code from the front end , Password reset 
                    validation=self.validate_sms_code(smsCode,mobile,redis_conn)
                    if validation:
                        # Complete SMS authentication , Start rewriting the password 
                        user.set_password(password)
                        user.save()
                        return Response({
    
                            'code':207,
                            'msg':' The password has been reset '
                        })
                    else:
                        return Response({
    
                            'code':204,
                            'msg':' The verification code has expired or is wrong '
                        })
                else:
                    return Response({
    
                        'code':205,
                        'msg':' Wrong user name or password '
                    })
        else:
            # Users register for the first time , You need to use SMS verification code to authenticate 
            if smsCode:
                # Use the verification code to verify   And register 
                validation=self.validate_sms_code(smsCode,mobile,redis_conn)
                if validation:
                    # Register user information 
                    User.objects.create_user(username=username,password=password,mobile=mobile)
                    return Response({
    
                        'code':201,
                        'msg':' To register successfully, you need to apply for administrator permission '
                    })
                else:
                    return Response({
    
                        'code':204,
                        'msg':' The verification code is expired or wrong '
                    })
            else:
                return Response({
    
                    'code':208,
                    'msg':' You need to use the collection verification code for the first login '
                })
    @staticmethod
    def gen_token(user):
        ''' :param user:  User object  :return: jwt token  character string  '''
        # Generate payload Load information 
        payload=jwt_payload_handler(user)
        #  Generate token
        token=jwt_encode_handler(payload)
        return token

    @staticmethod
    def validate_sms_code(smsCode,mobile,redis_sonn):
        ''' :param smsCode:  SMS verification code   character string  :param mobile:  cell-phone number   character string  :param redis_sonn: redis  Link to  :return: Boolean '''
        # structure key
        key='sms_%s'%mobile
        # obtain redis Verification code in 
        stored_code=redis_sonn.get(key)
        # Start comparing 
        if stored_code and stored_code.decode()==smsCode:
            return True
        else:
            return False

Configure the routing

from django.urls import path
from users import views
urlpatterns = [
    # Get SMS verification code 
    path('sms_code/',views.SmsCodeAPIView.as_view()),
    #  User login 
    path('logincount/',views.LoginAPIView.as_view())
]

Login user information Front page implementation

<script> import cons from "@/components/constant"; export default {
       name: "Login", data() {
       return {
       errshow: false, errmsg: "", password: "", username: "", phone: "", smsCode: "", }; }, methods: {
       //  Get SMS verification code  getSmsCode() {
       if (!this.phone){
       this.$message({
       type:'warning', message:' Cell phone number cannot be empty ' }) return } //  Regular matching is usually added  //  Send SMS to get the verification code  this.axios.get('/v1/users/sms_code/',{
       params:{
       mobile:this.phone } }).then((result) => {
       if (result.data.code==200){
       this.$message({
       type:'success', message:result.data.msg }) }else{
       this.$message({
       type:'error', message:result.data.msg }) } }).catch((err) => {
       console.log(' Error in getting SMS verification code ',err) }); }, //  Sign in  fnLogin() {
       if (this.username == "" || this.password == "") {
       this.errmsg = " User name or password cannot be empty "; this.errshow = true; return; } //http://www.meiduo.site:8000/meiduo_admin/authorizations/ //  Send a request  this.axios.post('/v1/users/logincount/',{
       username:this.username, password:this.password, mobile:this.phone, smsCode:this.smsCode }).then((result) => {
       console.log(' Login response :',result) //  Process response  if (result.data.code==200){
       this.$message({
       type:"success", message:result.data.msg }) //  preservation  useranme uid token  localStorage.clear() localStorage.token=result.data.data.token localStorage.uid=result.data.data.uid localStorage.username=result.data.data.username //  Enter the home page of the project  this.$router.push({
      path:'/home'}) }else{
       this.errshow=true this.errmsg=result.data.msg } }).catch((err) => {
       console.log(' Login error :',err) }); }, }, }; </script>

axios matters needing attention

If the request is wrong , Just go to main.js Check it out axios Whether to configure
 Insert picture description here

Count the total number of users , Increasing day by day , Number of active days

Back end

Need to guide package import time
Use query , Get the relevant data

# A view that counts the total number of users 
class TotaCountAPIView(APIView):
    def get(self,request):
        # Count the total number of users 
        total_count=User.objects.all().count()
        return Response({
    
            'code':200,
            'total_count':total_count
        })
# View of increasing users 
class DayIncrementAPIView(APIView):
    def get(self,request):
        #  Statistics of increasing users  # Need to guide package  import time
        current_data=time.strftime('%Y-%m-%d')       # Query users registered on the same day 
        day_increment=User.objects.filter(date_joined__contains=current_data).count()
        return Response({
    
            'code':200,
            'day_increment':day_increment
        })
# Count the active users on the day   View 
class DayLiveAPIView(APIView):
    def get(self,request):
    	#  Count the active users on the day  # Need to guide package  import time
        current_data = time.strftime('%Y-%m-%d')
        day_live = User.objects.filter(last_login__contains=current_data).count()
        return Response({
    
            'code': 200,
            'day_live': day_live
        })

Configure the routing

from django.urls import path
from users import views
urlpatterns = [
    # Get SMS verification code 
    path('sms_code/',views.SmsCodeAPIView.as_view()),
    #  User login 
    path('logincount/',views.LoginAPIView.as_view()),
    # Count the total number of users 
    path('total_count/',views.TotaCountAPIView.as_view()),
    # Get more and more users 
    path('day_increment/',views.DayIncrementAPIView.as_view()),
    # Get daily users 
    path('day_live/',views.DayLiveAPIView.as_view()),
]

front end

Be careful , To find the corresponding vue Components ,
for example :CountPannel.vue
Make modifications where necessary in the component

<script> export default {
       name: 'CountPannel', data(){
       return {
       total_count:0, day_increment:0, day_active:0, day_orders:0 } }, mounted(){
       let token = localStorage.token; //  Total number of people obtained  this.axios.get('/v1/users/total_count/', {
       headers: {
       'Authorization': 'JWT ' + token }, responseType: 'json', }) .then(res=>{
       console.log(' Count the response of the total number of users ',res); // {code:200,total_count:300} this.total_count = res.data.total_count; }).catch(err=>{
       console.log(err.response); if(err.response.status==401){
       this.$router.push({
      path:'/'}); } }); //  Get the increasing number of people  this.axios.get('/v1/users/day_increment/', {
       headers: {
       'Authorization': 'JWT ' + token }, responseType: 'json', }) .then(res=>{
       console.log(' Get the response of increasing users ',res) this.day_increment = res.data.day_increment; }).catch(err=>{
       console.log(err); }); //  Get the daily number of people  this.axios.get('/v1/users/day_live/', {
       headers: {
       'Authorization': 'JWT ' + token }, responseType: 'json', }) .then(res=>{
       console.log(' Get users of daily living ',res) this.day_active = res.data.day_live; }).catch(err=>{
       console.log(err); }); } </script>
原网站

版权声明
本文为[qishaoawei]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/208/202207270501215670.html