diff --git a/.DS_Store b/.DS_Store deleted file mode 100644 index 400a01b..0000000 Binary files a/.DS_Store and /dev/null differ diff --git a/.idea/MQTT.iml b/.idea/MQTT.iml index d0876a7..2e39cc2 100644 --- a/.idea/MQTT.iml +++ b/.idea/MQTT.iml @@ -1,8 +1,30 @@ + + + + + + - + + + + + + \ No newline at end of file diff --git a/.idea/dataSources.xml b/.idea/dataSources.xml new file mode 100644 index 0000000..a3481b0 --- /dev/null +++ b/.idea/dataSources.xml @@ -0,0 +1,12 @@ + + + + + sqlite.xerial + true + org.sqlite.JDBC + jdbc:sqlite:D:\MQTT\db.sqlite3 + $ProjectFileDir$ + + + \ No newline at end of file diff --git a/.idea/inspectionProfiles/Project_Default.xml b/.idea/inspectionProfiles/Project_Default.xml deleted file mode 100644 index 8921944..0000000 --- a/.idea/inspectionProfiles/Project_Default.xml +++ /dev/null @@ -1,70 +0,0 @@ - - - - \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml index b89f1da..73a3578 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -1,4 +1,7 @@ - + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml deleted file mode 100644 index 35eb1dd..0000000 --- a/.idea/vcs.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/ChatRoomPlan.emmx b/ChatRoomPlan.emmx deleted file mode 100644 index 24c7c08..0000000 Binary files a/ChatRoomPlan.emmx and /dev/null differ diff --git a/MQTT/__init__.py b/MQTT/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/MQTT/__pycache__/__init__.cpython-310.pyc b/MQTT/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000..2073afc Binary files /dev/null and b/MQTT/__pycache__/__init__.cpython-310.pyc differ diff --git a/MQTT/__pycache__/settings.cpython-310.pyc b/MQTT/__pycache__/settings.cpython-310.pyc new file mode 100644 index 0000000..175ab40 Binary files /dev/null and b/MQTT/__pycache__/settings.cpython-310.pyc differ diff --git a/MQTT/__pycache__/urls.cpython-310.pyc b/MQTT/__pycache__/urls.cpython-310.pyc new file mode 100644 index 0000000..2a967a8 Binary files /dev/null and b/MQTT/__pycache__/urls.cpython-310.pyc differ diff --git a/MQTT/__pycache__/wsgi.cpython-310.pyc b/MQTT/__pycache__/wsgi.cpython-310.pyc new file mode 100644 index 0000000..6dd4b44 Binary files /dev/null and b/MQTT/__pycache__/wsgi.cpython-310.pyc differ diff --git a/MQTT/asgi.py b/MQTT/asgi.py new file mode 100644 index 0000000..a915e0b --- /dev/null +++ b/MQTT/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for MQTT project. + +It exposes the ASGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/5.0/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MQTT.settings') + +application = get_asgi_application() diff --git a/MQTT/settings.py b/MQTT/settings.py new file mode 100644 index 0000000..669c523 --- /dev/null +++ b/MQTT/settings.py @@ -0,0 +1,124 @@ +""" +Django settings for MQTT project. + +Generated by 'django-admin startproject' using Django 5.0.6. + +For more information on this file, see +https://docs.djangoproject.com/en/5.0/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/5.0/ref/settings/ +""" + +from pathlib import Path + +# Build paths inside the project like this: BASE_DIR / 'subdir'. +BASE_DIR = Path(__file__).resolve().parent.parent + + +# Quick-start development settings - unsuitable for production +# See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = 'django-insecure-gi1ng+ntwjj^a6qvj-mlvo6j(#hhrr!gl#q09s0i-)r!fx)=9c' + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = True + +ALLOWED_HOSTS = [] + + +# Application definition + +INSTALLED_APPS = [ + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', +] + +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', +] + +ROOT_URLCONF = 'MQTT.urls' + +TEMPLATES = [ + { + 'BACKEND': 'django.template.backends.django.DjangoTemplates', + 'DIRS': [BASE_DIR / 'templates'] + , + 'APP_DIRS': True, + 'OPTIONS': { + 'context_processors': [ + 'django.template.context_processors.debug', + 'django.template.context_processors.request', + 'django.contrib.auth.context_processors.auth', + 'django.contrib.messages.context_processors.messages', + ], + }, + }, +] + +WSGI_APPLICATION = 'MQTT.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/5.0/ref/settings/#databases + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': BASE_DIR / 'db.sqlite3', + } +} + + +# Password validation +# https://docs.djangoproject.com/en/5.0/ref/settings/#auth-password-validators + +AUTH_PASSWORD_VALIDATORS = [ + { + 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', + }, +] + + +# Internationalization +# https://docs.djangoproject.com/en/5.0/topics/i18n/ + +LANGUAGE_CODE = 'en-us' + +TIME_ZONE = 'UTC' + +USE_I18N = True + +USE_TZ = True + + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/5.0/howto/static-files/ + +STATIC_URL = 'static/' + +# Default primary key field type +# https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field + +DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' diff --git a/MQTT/urls.py b/MQTT/urls.py new file mode 100644 index 0000000..ce41050 --- /dev/null +++ b/MQTT/urls.py @@ -0,0 +1,24 @@ +""" +URL configuration for MQTT project. + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/4.2/topics/http/urls/ +Examples: +Function views + 1. Add an import: from my_app import views + 2. Add a URL to urlpatterns: path('', views.home, name='home') +Class-based views + 1. Add an import: from other_app.views import Home + 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') +Including another URLconf + 1. Import the include() function: from django.urls import include, path + 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) +""" +from django.contrib import admin +from django.urls import path, include + +urlpatterns = [ + path("admin/", admin.site.urls), + path("accounts/", include("signup.urls")) +] + diff --git a/MQTT/wsgi.py b/MQTT/wsgi.py new file mode 100644 index 0000000..866975e --- /dev/null +++ b/MQTT/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for MQTT project. + +It exposes the WSGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/5.0/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MQTT.settings') + +application = get_wsgi_application() diff --git a/db.sqlite3 b/db.sqlite3 new file mode 100644 index 0000000..7bea4a6 Binary files /dev/null and b/db.sqlite3 differ diff --git a/manage.py b/manage.py new file mode 100644 index 0000000..df1f863 --- /dev/null +++ b/manage.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python +"""Django's command-line utility for administrative tasks.""" +import os +import sys + + +def main(): + """Run administrative tasks.""" + os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MQTT.settings') + try: + from django.core.management import execute_from_command_line + except ImportError as exc: + raise ImportError( + "Couldn't import Django. Are you sure it's installed and " + "available on your PYTHONPATH environment variable? Did you " + "forget to activate a virtual environment?" + ) from exc + execute_from_command_line(sys.argv) + + +if __name__ == '__main__': + main() diff --git a/project/.DS_Store b/project/.DS_Store deleted file mode 100644 index 9c28efb..0000000 Binary files a/project/.DS_Store and /dev/null differ diff --git a/project/client/Client.py b/project/client/Client.py deleted file mode 100644 index f20d6a8..0000000 --- a/project/client/Client.py +++ /dev/null @@ -1,63 +0,0 @@ - -import paho.mqtt.client as mqtt - -from project.config.config import HOST, PORT,publish_topic -from queue import Queue -import datetime -import threading -from threading import Thread, Event -import threading -from queue import Queue -import paho.mqtt.client as mqtt - -class Client: - def __init__(self, userName=None,userNumber=None,userPwd=None): - self.userName = userName - self.userNumber=userNumber - self.userPwd = userPwd - self.lock = threading.Lock() - self.loopNum = 0 - self.start_evt = None # 这是一个Event对象,用来查看是否验证成功 - # 自动在初始化的时候进行链接 - self.client = mqtt.Client() - self.client.connect(HOST, PORT, 60) - - - def start_loop(self): - # 用线程锁来控制同时仅能一个loop_forever - if self.loopNum == 0: - self.lock.acquire() - print('进程锁加载') - self.loopNum = 1 - self.client._thread_terminate = False - self.client.loop_forever() - - def stop_loop(self): - # 停止这个线程 - if self.loopNum == 1: - self.lock.release() - print('进程锁结束!!') - self.client._thread_terminate = True - self.loopNum = 0 - - def clientStart(self):#启动进程,使用threading(python自带进程管理库)进行管理 - loopThread = threading.Thread(target=self.start_loop) - loopThread.start() - - return loopThread - - - @staticmethod - def publish_login(client, userName, userPwd, returnTopic): # 发布登入信息,returnTopic是 - data = {'user_name': userName, 'user_pwd': userPwd, 'return_topic': returnTopic} - # qos1 - client.publish(publish_topic['login_topic'], str(data).encode(), 1) - # client.loop() - print('发布信息 ', publish_topic['login_topic'], ' 成功') - -#使用方法 -a = Client() -loopThread=a.clientStart() -Client.publish_login(a.client, 'test_user', 'test_password', 'response/topic') - - diff --git a/project/config/__pycache__/config.cpython-311.pyc b/project/config/__pycache__/config.cpython-311.pyc deleted file mode 100644 index 60b4afc..0000000 Binary files a/project/config/__pycache__/config.cpython-311.pyc and /dev/null differ diff --git a/project/config/config.py b/project/config/config.py deleted file mode 100644 index 7c7b191..0000000 --- a/project/config/config.py +++ /dev/null @@ -1,16 +0,0 @@ - -#mysql -mysql_config = { - 'db_name': 'mqtt_test', - 'db_user': 'mqtt_test', - 'db_password': '12345678', - 'db_port': 3306, - 'db_host': '101.43.101.59' -} - -#MQTT broker -HOST = "101.43.101.59" -PORT = 1883 - -#topic -publish_topic={'login_topic':'login'} \ No newline at end of file diff --git a/project/mysql.py b/project/mysql.py deleted file mode 100644 index 7246e3e..0000000 --- a/project/mysql.py +++ /dev/null @@ -1,131 +0,0 @@ -from config.config import mysql_config -from peewee import * -import bcrypt -import datetime - - - -#链接数据库 -db = MySQLDatabase(mysql_config['db_name'], user=mysql_config['db_user'], password=mysql_config['db_password'], - host=mysql_config['db_host'], port=mysql_config['db_port']) - -#数据对象 -####################################################### -#基类 -class BaseModel(Model): - class Meta: - database = db - -#用户类 -class UserModel(BaseModel): - id=AutoField() - name = CharField(max_length=64) - password = CharField(max_length=32) - - - class Meta: - db_table = 'user' - - -#信息类 -class ChatModel(BaseModel): - id=AutoField() - message = TextField() - senderId=BigIntegerField() - time = DateTimeField(default=datetime.datetime.now) - class Meta: - db_table = 'chat' - -class CreateTable: - @staticmethod - def create(): - db.connect() - db.create_tables([UserModel, ChatModel]) - - -#用户操作 -########################################## -def hash_password(password): - # 生成盐值 - salt = bcrypt.gensalt() - # 生成哈希值 - hashed = bcrypt.hashpw(password.encode('utf-8'), salt) - return hashed - -# 验证密码 - -def check_password(hashed, password): - # 验证密码 - return bcrypt.checkpw(password.encode('utf-8'), hashed) - - -#用户信息传递 -class UserManage: - @staticmethod - def chackName(name):#检测用户是否存在,不存在则打印提示并返回None,否则返回UserModel - try: - user = UserModel.get(UserModel.name == name) - return user - except UserModel.DoesNotExist: - print(f"No user found with name: {name}") - return None - except Exception as error: - print(f"An error occurred: {error}") - return None - @staticmethod - def chackPassword(password):#如果密码正确则 - # 密码加密 - hashPassword = hash_password(password) - return check_password(hashPassword,password) - - - @staticmethod - def AddUser(name, password): - try: - UserModel.get(UserModel.name == name) - return 'User was existed' - except DoesNotExist: - pass - try: - pwd = hash_password(password) - UserModel.insert(name=name, password=pwd).execute() - return 'Succeed' - except Exception as error: - print(error) - return 'Fail' - - -################################################################ -class ChatManage: - - # 获取并返回所有 chat 数据 - @staticmethod - def getAllManage(): - try: - all_chats = ChatModel.select() - # 将数据转换为列表形式 - chat_list = [] - for chat in all_chats: - chat_data = { - 'id': chat.id, - 'message': chat.message, - 'senderId': chat.senderId, - 'time': chat.time - } - chat_list.append(chat_data) - return chat_list - except Exception as error: - print(error) - return None - - @staticmethod - def AddChat(message,senderId): - try: - UserModel.insert(message=message,senderId=senderId).execute() - return 'Succeed' - except Exception as error: - print(error) - return 'Fail' - - -CreateTable.create() \ No newline at end of file diff --git a/project/server/Server.py b/project/server/Server.py deleted file mode 100644 index 92696b8..0000000 --- a/project/server/Server.py +++ /dev/null @@ -1,60 +0,0 @@ - -import paho.mqtt.client as mqtt - -from project.config.config import HOST, PORT,publish_topic -from queue import Queue -import datetime -import threading -from threading import Thread, Event -import threading -from queue import Queue -import paho.mqtt.client as mqtt - -class Server: - def __init__(self): - self.client = mqtt.Client() - self.client.on_connect = self.on_connect - self.client.on_message = self.on_message - self.client.connect(HOST, PORT, 60) - self.lock = threading.Lock() - self.loopNum = 0 - - def start_loop(self): - # 用线程锁来控制同时仅能一个loop_forever - if self.loopNum == 0: - self.lock.acquire() - print('进程锁加载') - self.loopNum = 1 - self.client._thread_terminate = False - self.client.loop_forever() - - def stop_loop(self): - # 停止这个线程 - if self.loopNum == 1: - self.lock.release() - print('进程锁结束!!') - self.client._thread_terminate = True - self.loopNum = 0 - - def serverStart(self):#启动进程,使用threading(python自带进程管理库)进行管理 - loopThread = threading.Thread(target=self.start_loop) - loopThread.start() - - return loopThread - - - def on_connect(self, client, userdata, flags, rc): - if rc == 0: - print("Connected successfully") - client.subscribe('login') # 订阅 login 主题 - else: - print("Failed to connect, return code %d\n", rc) - - - def on_message(self, client, userdata, msg): - # 规定传入数据均为dict的形式 - data = eval(msg.payload.decode('utf-8')) - print(data) - -a=Server() -a.serverStart() \ No newline at end of file diff --git a/project/test.py b/project/test.py deleted file mode 100644 index b7796d4..0000000 --- a/project/test.py +++ /dev/null @@ -1,30 +0,0 @@ - - -############################################ -#此为我自己进行功能测试的文件,你们可以随意更改,随意提交 -############################################ - -import bcrypt - -# 加密密码 -def hash_password(password): - # 生成盐值 - salt = bcrypt.gensalt() - # 生成哈希值 - hashed = bcrypt.hashpw(password.encode('utf-8'), salt) - return hashed - -# 验证密码 -def check_password(hashed, password): - # 验证密码 - return bcrypt.checkpw(password.encode('utf-8'), hashed) - -# 示例使用 -if __name__ == "__main__": - password = "my_secure_password" - hashed_password = hash_password(password) - print(f"Hashed password: {hashed_password}") - - # 验证密码 - is_correct = check_password(hashed_password, "my_secur1e_password") - print(f"Password is correct: {is_correct}") \ No newline at end of file diff --git a/signup/__init__.py b/signup/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/signup/__pycache__/__init__.cpython-310.pyc b/signup/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000..752152e Binary files /dev/null and b/signup/__pycache__/__init__.cpython-310.pyc differ diff --git a/signup/__pycache__/urls.cpython-310.pyc b/signup/__pycache__/urls.cpython-310.pyc new file mode 100644 index 0000000..854a0c3 Binary files /dev/null and b/signup/__pycache__/urls.cpython-310.pyc differ diff --git a/signup/__pycache__/views.cpython-310.pyc b/signup/__pycache__/views.cpython-310.pyc new file mode 100644 index 0000000..1c60426 Binary files /dev/null and b/signup/__pycache__/views.cpython-310.pyc differ diff --git a/signup/admin.py b/signup/admin.py new file mode 100644 index 0000000..8c38f3f --- /dev/null +++ b/signup/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/signup/apps.py b/signup/apps.py new file mode 100644 index 0000000..7c36efe --- /dev/null +++ b/signup/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class SignupConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'signup' diff --git a/signup/migrations/__init__.py b/signup/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/signup/models.py b/signup/models.py new file mode 100644 index 0000000..6eaaccb --- /dev/null +++ b/signup/models.py @@ -0,0 +1,6 @@ +from django.db import models +from django.contrib.auth.models import AbstractUser +# Create your models here. +class User (AbstractUser): + #用Django内置的AbstractUser作为基类 + pass diff --git a/signup/tests.py b/signup/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/signup/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/signup/urls.py b/signup/urls.py new file mode 100644 index 0000000..7eecd52 --- /dev/null +++ b/signup/urls.py @@ -0,0 +1,7 @@ +from django.urls import path +from .views import register, login_view + +urlpatterns = [ + path('register/', register, name='register'), # 注册界面 + path('login/', login_view, name='login'), # 登录界面 +] \ No newline at end of file diff --git a/signup/views.py b/signup/views.py new file mode 100644 index 0000000..68ce7bd --- /dev/null +++ b/signup/views.py @@ -0,0 +1,34 @@ +from django.shortcuts import render, redirect +from django.contrib.auth import login, authenticate +from django.contrib.auth.forms import UserCreationForm, AuthenticationForm +# Create your views here. + +def register(request): + if request.method == 'POST': + form = UserCreationForm(request.POST) + if form.is_valid(): + user = form.save() + login(request,user) + + #username = form.cleaned_data.get('username') + #raw_password = form.cleaned_data.get('password') + #user = authenticate(username=username, password=raw_password) + #login(request, user) # 登录用户 + #return redirect('home') # 重定向到首页 + return redirect('https://bougiemoonintaurus.com') + else: + form = UserCreationForm() # 如果不是POST请求,创建一个空表单 + return render(request,'register.html',{"form":form}) +def login_view(request): + if request.method == 'POST': + form = AuthenticationForm(request, data=request.POST) + if form.is_valid(): + username = form.cleaned_data.get('username') + password = form.cleaned_data.get('password') + user = authenticate(username=username, password=password) + if user is not None: + login(request, user) # 登录用户 + return redirect('https://bougiemoonintaurus.com') # 登录失败,重新定向到登录界面 + else: + form = AuthenticationForm() + return render(request,'login.html',{'form':form}) \ No newline at end of file diff --git a/templates/login.html b/templates/login.html new file mode 100644 index 0000000..85c58b5 --- /dev/null +++ b/templates/login.html @@ -0,0 +1,6 @@ + +
+ {% csrf_token %} + {{ form.as_p }} + +
\ No newline at end of file diff --git a/templates/register.html b/templates/register.html new file mode 100644 index 0000000..dbb9562 --- /dev/null +++ b/templates/register.html @@ -0,0 +1,6 @@ + +
+ {% csrf_token %} + {{ form.as_p }} + +
\ No newline at end of file