支持删除CA和证书

This commit is contained in:
wzj 2025-06-14 11:14:00 +08:00
parent c390c63323
commit 56b4a91972

38
app.py
View File

@ -10,6 +10,7 @@ import random
import string import string
from io import BytesIO from io import BytesIO
import zipfile import zipfile
import shutil
from pypinyin import pinyin, Style from pypinyin import pinyin, Style
import uuid import uuid
@ -1119,7 +1120,6 @@ def delete_ca(ca_id):
return render_template('confirm_delete_ca.html', ca=ca) return render_template('confirm_delete_ca.html', ca=ca)
@app.route('/certificates/<int:cert_id>/delete', methods=['GET', 'POST']) @app.route('/certificates/<int:cert_id>/delete', methods=['GET', 'POST'])
@login_required @login_required
def delete_certificate(cert_id): def delete_certificate(cert_id):
@ -1136,19 +1136,38 @@ def delete_certificate(cert_id):
if request.method == 'POST': if request.method == 'POST':
# 删除文件 # 删除文件
try: try:
if os.path.exists(cert['cert_path']): # 确保所有文件路径都存在
os.remove(cert['cert_path']) files_to_delete = [
if os.path.exists(cert['key_path']): cert['cert_path'],
os.remove(cert['key_path']) cert['key_path'],
if os.path.exists(cert['csr_path']): cert['csr_path']
os.remove(cert['csr_path']) ]
# 删除证书目录
# 删除所有指定文件
for file_path in files_to_delete:
if file_path and os.path.exists(file_path):
os.remove(file_path)
# 删除证书目录及其所有内容
cert_dir = os.path.dirname(cert['cert_path']) cert_dir = os.path.dirname(cert['cert_path'])
if os.path.exists(cert_dir): if os.path.exists(cert_dir):
# 删除目录中的所有文件
for filename in os.listdir(cert_dir):
file_path = os.path.join(cert_dir, filename)
try:
if os.path.isfile(file_path) or os.path.islink(file_path):
os.unlink(file_path)
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
except Exception as e:
print(f'Failed to delete {file_path}. Reason: {e}')
# 现在删除空目录
os.rmdir(cert_dir) os.rmdir(cert_dir)
except OSError as e: except OSError as e:
print(f"文件删除错误: {e}") print(f"文件删除错误: {e}")
flash('删除文件时出错', 'danger') flash(f'删除文件时出错: {str(e)}', 'danger')
return redirect(url_for('certificate_detail', cert_id=cert_id)) return redirect(url_for('certificate_detail', cert_id=cert_id))
# 删除数据库记录 # 删除数据库记录
@ -1170,7 +1189,6 @@ def delete_certificate(cert_id):
conn.close() conn.close()
return render_template('confirm_delete_certificate.html', cert=cert) return render_template('confirm_delete_certificate.html', cert=cert)
def generate_separate_files_zip(cert, cert_ext, zip_suffix): def generate_separate_files_zip(cert, cert_ext, zip_suffix):
"""生成包含分开文件的ZIP包通用函数""" """生成包含分开文件的ZIP包通用函数"""
memory_file = BytesIO() memory_file = BytesIO()