Bladeren bron

代码提交

SGTY 1 maand geleden
bovenliggende
commit
9a89a77dfb

+ 8 - 0
.env

@@ -0,0 +1,8 @@
+DB_HOST = 173.18.12.203
+DB_NAME = medkg
+DB_PORT = 5432
+DB_USER = knowledge
+DB_PASSWORD = qwer1234.
+
+license=
+EMBEDDING_MODEL=C:\Users\jiyua\.cache\modelscope\hub\models\BAAI\bge-m3

+ 3 - 4
db/session.py

@@ -1,9 +1,8 @@
 from sqlalchemy import create_engine
 from sqlalchemy.orm import sessionmaker, scoped_session
-from .base_class import Base
 import os
-from pgvector.sqlalchemy import Vector
-
+from dotenv import load_dotenv
+load_dotenv()  # 加载 .env 文件中的环境变量
 # 数据库配置
 # 远程PostgreSQL数据库连接配置
 # 从环境变量获取数据库连接信息,如果未设置则使用默认值
@@ -17,7 +16,7 @@ DATABASE_URL = f"postgresql://{DB_USER}:{DB_PASS}@{DB_HOST}:{DB_PORT}/{DB_NAME}"
 
 engine = create_engine(
     DATABASE_URL,
-    pool_size=20,
+    pool_size=200,
     max_overflow=10,
     pool_pre_ping=True,
     connect_args={'options': '-c search_path=public'},

BIN
license_issued/license_issued.key


+ 1 - 0
license_issued/license_issued.lic

@@ -0,0 +1 @@
+{"content": [{"name": "max_graphs_count", "value": 999}, {"name": "max_nodes_count", "value": 99999}, {"name": "max_edgess_count", "value": 999999}, {"name": "max_files_count", "value": 9999}, {"name": "api_concurrent_limit", "value": 5}, {"name": "api_invoke_max_count", "value": 999999}], "expiration_time": 1752313888, "issued_time": 1749721888.8083541, "name": "demo", "orgnization": "demo org"}

+ 9 - 0
license_issued/public.key

@@ -0,0 +1,9 @@
+-----BEGIN PUBLIC KEY-----
+MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqoUtnP2iL3EqDHlHO8Gf
++owYBrFmH1Fl0pd2ycuK49d2EnRPIYDzZnRxoWlJjUCoO8sHta+cNv5j6Y5sxDqX
+JLk8Chbn51dxD4MnU2KxMy5soerXjdNNgYA1OLDA7/mbg22WXR3uG+f0u+yJqVDw
+u1tswri633WcQmSW8hw2QzRlayWmevhx3MIhF/NlAsO06zHR5yQqTl1obrfMaXft
+3uwMGFLfgAbMTofSNm/JLe4xT+bNGpBi3tttdIwPkXL1yEMmDGu9xK6nROA6COdt
+jlIgBDN3qsLG3Cdmz28xxc2PWmC6HLB3oGu6FqgGO1icRThqiaWTaiXMmy4ijI2L
+5wIDAQAB
+-----END PUBLIC KEY-----

+ 34 - 0
utils/EncryptedString.py

@@ -0,0 +1,34 @@
+from sqlalchemy import create_engine, Column, Integer, String, TypeDecorator
+from sqlalchemy.ext.declarative import declarative_base
+from sqlalchemy.orm import sessionmaker
+from cryptography.fernet import Fernet
+import base64
+
+# 生成加密密钥 (实际应用中应该安全地存储和管理这个密钥)
+key = Fernet.generate_key()
+cipher_suite = Fernet(key)
+
+Base = declarative_base()
+
+
+class EncryptedString(TypeDecorator):
+    """自动加密/解密的字符串类型"""
+
+    impl = String  # 底层数据库类型
+
+    def process_bind_param(self, value, dialect):
+        """在写入数据库前加密数据"""
+        if value is not None:
+            # 如果是字符串则编码为bytes
+            if isinstance(value, str):
+                value = value.encode()
+            # 加密并返回base64编码的字符串(便于存储)
+            return base64.b64encode(cipher_suite.encrypt(value)).decode('utf-8')
+        return value
+
+    def process_result_value(self, value, dialect):
+        """从数据库读取后解密数据"""
+        if value is not None:
+            # 解密base64编码的字符串
+            return cipher_suite.decrypt(base64.b64decode(value)).decode('utf-8')
+        return value

+ 52 - 0
utils/TestEncryptedString.py

@@ -0,0 +1,52 @@
+from sqlalchemy import create_engine, Column, Integer, String, TypeDecorator
+from sqlalchemy.ext.declarative import declarative_base
+from sqlalchemy.orm import sessionmaker
+from db.base_class import Base
+from utils.EncryptedString import EncryptedString
+from db.session import session
+
+
+class User(Base):
+    __tablename__ = 'user'
+
+    id = Column(Integer, primary_key=True)
+    username = Column(String(255), unique=True)
+    # 使用我们的加密类型
+    password = Column(EncryptedString(255))  # 255是最大长度
+    email = Column(EncryptedString(255))
+    # 普通字段不会加密
+    public_info = Column(String(255))
+
+
+# 使用示例
+def demo():
+    # 创建用户
+    new_user = User(
+        id = 1,
+        username='johndoe',
+        password='my_secure_password',
+        email='john.doe@example.com',
+        public_info='This is public info'
+    )
+    try:
+        session.add(new_user)
+        session.commit()
+    finally:
+        session.close()
+
+    # 查询用户
+    user = session.query(User).filter_by(username='johndoe').first()
+    print(f"Username: {user.username}")
+    print(f"Password (自动解密): {user.password}")
+    print(f"Email (自动解密): {user.email}")
+    print(f"Public Info: {user.public_info}")
+
+    # 查看数据库中的加密数据
+    raw_data = session.execute("SELECT password, email FROM users WHERE username='johndoe'").fetchone()
+    print("\n数据库中的加密数据:")
+    print(f"Password: {raw_data[0]}")
+    print(f"Email: {raw_data[1]}")
+
+
+if __name__ == '__main__':
+    demo()

+ 39 - 0
utils/license.py

@@ -0,0 +1,39 @@
+from cryptography.hazmat.primitives.asymmetric import padding
+from cryptography.hazmat.primitives import hashes,serialization
+import json
+import time
+import traceback
+
+def validate_license(public_key_pem, license_json, signature):
+    public_key = serialization.load_pem_public_key(public_key_pem)
+
+    try:
+        public_key.verify(
+        signature,
+        license_json,
+        padding.PKCS1v15(),
+        hashes.SHA256()
+        )
+    except:
+        #打印异常信息
+        traceback.print_exc()
+        return False
+
+    license_data=json.loads(license_json.decode())
+    # 检查是否过期
+    if time.time()>license_data["expiration_time"]:
+        return False
+    return True
+
+if __name__ == '__main__':
+    with open("license_issued/public.key","rb") as f:
+        public_key_pem = f.read()
+    with open("license_issued/license_issued.lic","rb") as f:
+        data = json.loads(f.read())
+        license_json = json.dumps(data, sort_keys=True).encode()
+    with open("license_issued/license_issued.key","rb") as f:
+        signature = f.read()
+    if validate_license(public_key_pem,license_json, signature):
+        print("许可证有效!")
+    else:
+        print("许可证无效或已过期!")