Compare commits
88 Commits
4ef3523ea9
...
0.2.8.16
| Author | SHA1 | Date | |
|---|---|---|---|
| 0404c7e274 | |||
| 69c5747867 | |||
| d4de99971a | |||
| 27f8a64fdb | |||
| 01a3b2dfdb | |||
| 0dd7879389 | |||
| 19f805c818 | |||
| d84d0218cd | |||
| e92964ce71 | |||
| 1a3aee39e0 | |||
| 7fa7b42b1a | |||
| 26452161f8 | |||
| 07d3a4420c | |||
| 2c3c2d6acf | |||
| afc663844b | |||
| 9e3fe7150b | |||
| c9611fa622 | |||
| fe7f08ed1c | |||
| 5e38ebf856 | |||
| 71a0723a74 | |||
| 85dd7bc991 | |||
| 3596e344e2 | |||
| b0c3707ccd | |||
| f38cb5ec76 | |||
| 8c4e4e4c0d | |||
| e05791e52f | |||
| 4d83864e9f | |||
| ebe88d93c9 | |||
| 6f1abc1681 | |||
| d69858434f | |||
| 109c06e1d9 | |||
| 1163110810 | |||
| 462c744d06 | |||
| b35f603399 | |||
| b4cea89796 | |||
| ee7987aa23 | |||
| 193f739693 | |||
| 418cc798df | |||
| 14e407d06a | |||
| bfbf100595 | |||
| abc435afe6 | |||
| 6b0be35832 | |||
| 45005fcc92 | |||
| df18bdfa7e | |||
| 281ade6ac9 | |||
| 835426b133 | |||
| d001fec21e | |||
| 253de3639c | |||
| a0507b8054 | |||
| 9f803880fa | |||
| 71fe964476 | |||
| 0f5c8c08ff | |||
| e032253327 | |||
| 3f108e2138 | |||
| 2d913e397f | |||
| 74bc8aa498 | |||
| 5d747faee1 | |||
| 7bd8eeca77 | |||
| 782b2dd82e | |||
| f9c0abb3a0 | |||
| c5300591e6 | |||
| f96629566f | |||
| 8d581ac638 | |||
| acc80074ea | |||
| 62d28be032 | |||
| 5b956e1365 | |||
| 7485ba16e6 | |||
| ac580599b3 | |||
| faae7032f1 | |||
| 615d9433fe | |||
| d755f4710f | |||
| 3e598fe0a1 | |||
| 5a9d98282a | |||
| 8f9fc9c914 | |||
| b5d76be37b | |||
| 100531ddd1 | |||
| 68bc4b54f5 | |||
| 5153017a80 | |||
| 2c58c1be29 | |||
| 8c14544ca1 | |||
| 42bacbbc81 | |||
| 32ff920921 | |||
| 6e332f248f | |||
| 1392275337 | |||
| f93286a5fe | |||
| dc57d88779 | |||
| 9665e81698 | |||
| 7afc6ba06b |
129
.gitea/workflows/ci.yml
Normal file
129
.gitea/workflows/ci.yml
Normal file
@@ -0,0 +1,129 @@
|
|||||||
|
name: CI
|
||||||
|
|
||||||
|
# Required Secrets:
|
||||||
|
# - DJANGO_SECRET_KEY: Django Secret Key
|
||||||
|
# - token: Gitea API token for creating releases
|
||||||
|
# - ALIST_PUBLIC_URL: Public URL for AList download (e.g., http://alist.example.com/d/ci)
|
||||||
|
# - WEBDAV_URL: WebDAV upload URL (e.g., http://alist.example.com/dav/ci/)
|
||||||
|
# - WEBDAV_USER: WebDAV username
|
||||||
|
# - WEBDAV_PASSWORD: WebDAV password
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- Django
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
version:
|
||||||
|
description: 版本号(如 0.2.2),为空则自动生成
|
||||||
|
required: false
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: ci-${{ github.ref }}
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
docker-ci:
|
||||||
|
if: github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && contains(github.event.head_commit.message, '[ci]'))
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
container:
|
||||||
|
image: catthehacker/ubuntu:act-latest
|
||||||
|
timeout-minutes: 40
|
||||||
|
env:
|
||||||
|
DJANGO_SECRET_KEY: ${{ secrets.DJANGO_SECRET_KEY }}
|
||||||
|
DJANGO_DEBUG: "False"
|
||||||
|
DJANGO_ALLOWED_HOSTS: "127.0.0.1,localhost"
|
||||||
|
IMAGE_NAME: achievement_inputing_ci
|
||||||
|
ARTIFACT_DIR: artifacts
|
||||||
|
# 请在 Secrets 中配置 ALIST_PUBLIC_URL,例如 http://139.224.69.213:8080/d/ci
|
||||||
|
DOWNLOAD_BASE: ${{ secrets.ALIST_PUBLIC_URL }}
|
||||||
|
GITEA_SERVER: ${{ github.server_url }}
|
||||||
|
GITEA_REPO: ${{ github.repository }}
|
||||||
|
RELEASE_TOKEN: ${{ secrets.token }}
|
||||||
|
steps:
|
||||||
|
- name: Ensure source present
|
||||||
|
env:
|
||||||
|
SERVER: ${{ github.server_url }}
|
||||||
|
REPO: ${{ github.repository }}
|
||||||
|
REF: ${{ github.ref }}
|
||||||
|
SHA: ${{ github.sha }}
|
||||||
|
TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
run: |
|
||||||
|
if [ -f "$GITHUB_WORKSPACE/Dockerfile" ]; then exit 0; fi
|
||||||
|
mkdir -p "$GITHUB_WORKSPACE"
|
||||||
|
cd "$GITHUB_WORKSPACE"
|
||||||
|
git init .
|
||||||
|
if [ -z "$TOKEN" ]; then
|
||||||
|
git fetch --depth=1 "$SERVER/$REPO.git" "$REF"
|
||||||
|
else
|
||||||
|
git -c http.extraHeader="Authorization: Bearer $TOKEN" fetch --depth=1 "$SERVER/$REPO.git" "$REF"
|
||||||
|
fi
|
||||||
|
git checkout FETCH_HEAD
|
||||||
|
- name: Derive version
|
||||||
|
run: |
|
||||||
|
msg="${{ github.event.head_commit.message }}"
|
||||||
|
ver_input="${{ github.event.inputs.version }}"
|
||||||
|
ver=""
|
||||||
|
if [ -n "$ver_input" ]; then
|
||||||
|
ver="$ver_input"
|
||||||
|
else
|
||||||
|
ver=$(echo "$msg" | grep -Eo "\[[0-9]+(\.[0-9]+){1,}\]" | head -n1 | tr -d '[]')
|
||||||
|
fi
|
||||||
|
if [ -z "$ver" ]; then
|
||||||
|
ver="$(date +%Y%m%d%H%M)-${GITHUB_SHA:0:7}"
|
||||||
|
fi
|
||||||
|
echo "VERSION=$ver" >> $GITHUB_ENV
|
||||||
|
- name: Build application image
|
||||||
|
run: |
|
||||||
|
docker build -t "$IMAGE_NAME:$VERSION" -f "$GITHUB_WORKSPACE/Dockerfile" "$GITHUB_WORKSPACE"
|
||||||
|
- name: Output image info
|
||||||
|
run: |
|
||||||
|
docker image inspect "$IMAGE_NAME:$VERSION" --format '{{.Id}} {{.Size}}'
|
||||||
|
- name: Export image tar
|
||||||
|
run: |
|
||||||
|
ART="achievement_inputing_ci_${VERSION}.tar"
|
||||||
|
docker save -o "$GITHUB_WORKSPACE/$ART" "$IMAGE_NAME:$VERSION"
|
||||||
|
echo "$ART" > "$GITHUB_WORKSPACE/.artifact_name"
|
||||||
|
- name: Publish artifact locally
|
||||||
|
run: |
|
||||||
|
ART=$(cat "$GITHUB_WORKSPACE/.artifact_name")
|
||||||
|
mkdir -p "$GITHUB_WORKSPACE/$ARTIFACT_DIR"
|
||||||
|
mv "$GITHUB_WORKSPACE/$ART" "$GITHUB_WORKSPACE/$ARTIFACT_DIR/"
|
||||||
|
echo "artifact: $GITHUB_WORKSPACE/$ARTIFACT_DIR/$ART"
|
||||||
|
- name: Publish to WebDAV
|
||||||
|
env:
|
||||||
|
WEBDAV_URL: ${{ secrets.WEBDAV_URL }}
|
||||||
|
WEBDAV_USER: ${{ secrets.WEBDAV_USER }}
|
||||||
|
WEBDAV_PASSWORD: ${{ secrets.WEBDAV_PASSWORD }}
|
||||||
|
run: |
|
||||||
|
set -e
|
||||||
|
ART=$(cat "$GITHUB_WORKSPACE/.artifact_name")
|
||||||
|
FILE_PATH="$GITHUB_WORKSPACE/$ARTIFACT_DIR/$ART"
|
||||||
|
|
||||||
|
# 检查必要的 secrets 是否存在
|
||||||
|
if [ -z "$WEBDAV_URL" ]; then
|
||||||
|
echo "Error: WEBDAV_URL secret is not set."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 确保 URL 以 / 结尾
|
||||||
|
case "$WEBDAV_URL" in
|
||||||
|
*/) ;;
|
||||||
|
*) WEBDAV_URL="${WEBDAV_URL}/" ;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
echo "Uploading $ART to $WEBDAV_URL..."
|
||||||
|
curl -f -u "$WEBDAV_USER:$WEBDAV_PASSWORD" -T "$FILE_PATH" "${WEBDAV_URL}${ART}"
|
||||||
|
echo "Upload success."
|
||||||
|
- name: Create release with download link
|
||||||
|
if: env.RELEASE_TOKEN != ''
|
||||||
|
run: |
|
||||||
|
ART=$(cat "$GITHUB_WORKSPACE/.artifact_name")
|
||||||
|
BRANCH=${GITHUB_REF#refs/heads/}
|
||||||
|
TAG="$VERSION"
|
||||||
|
NAME="$VERSION"
|
||||||
|
BASE="${DOWNLOAD_BASE%/}"
|
||||||
|
DL="$BASE/$ART"
|
||||||
|
echo "download: $DL"
|
||||||
|
JSON=$(printf '{"tag_name":"%s","target_commitish":"%s","name":"%s","body":"%s"}' "$TAG" "$BRANCH" "$NAME" "$DL")
|
||||||
|
curl -sS -X POST "$GITEA_SERVER/api/v1/repos/$GITEA_REPO/releases" -H "Content-Type: application/json" -H "Authorization: token $RELEASE_TOKEN" -d "$JSON"
|
||||||
10
.gitignore
vendored
Normal file
10
.gitignore
vendored
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
|
||||||
|
/.idea/
|
||||||
|
.idea/
|
||||||
|
|
||||||
|
/media/
|
||||||
|
media/
|
||||||
|
|
||||||
|
*.tar
|
||||||
@@ -33,6 +33,7 @@ ALLOWED_HOSTS = os.environ.get('DJANGO_ALLOWED_HOSTS', '127.0.0.1,localhost').sp
|
|||||||
# Application definition
|
# Application definition
|
||||||
|
|
||||||
INSTALLED_APPS = [
|
INSTALLED_APPS = [
|
||||||
|
'django_browser_reload',
|
||||||
'django.contrib.admin',
|
'django.contrib.admin',
|
||||||
'django.contrib.auth',
|
'django.contrib.auth',
|
||||||
'django.contrib.contenttypes',
|
'django.contrib.contenttypes',
|
||||||
@@ -42,6 +43,7 @@ INSTALLED_APPS = [
|
|||||||
'accounts',
|
'accounts',
|
||||||
'main',
|
'main',
|
||||||
'elastic',
|
'elastic',
|
||||||
|
'minio_storage',
|
||||||
'django_elasticsearch_dsl',
|
'django_elasticsearch_dsl',
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -49,6 +51,7 @@ MIDDLEWARE = [
|
|||||||
'django.middleware.security.SecurityMiddleware',
|
'django.middleware.security.SecurityMiddleware',
|
||||||
'whitenoise.middleware.WhiteNoiseMiddleware',
|
'whitenoise.middleware.WhiteNoiseMiddleware',
|
||||||
'django.contrib.sessions.middleware.SessionMiddleware',
|
'django.contrib.sessions.middleware.SessionMiddleware',
|
||||||
|
'django_browser_reload.middleware.BrowserReloadMiddleware',
|
||||||
'django.middleware.common.CommonMiddleware',
|
'django.middleware.common.CommonMiddleware',
|
||||||
'django.middleware.csrf.CsrfViewMiddleware',
|
'django.middleware.csrf.CsrfViewMiddleware',
|
||||||
'django.contrib.auth.middleware.AuthenticationMiddleware',
|
'django.contrib.auth.middleware.AuthenticationMiddleware',
|
||||||
@@ -164,3 +167,4 @@ ELASTICSEARCH_INDEX_NAMES = {
|
|||||||
# AI Studio/OpenAI client settings
|
# AI Studio/OpenAI client settings
|
||||||
AISTUDIO_API_KEY = os.environ.get('AISTUDIO_API_KEY', '')
|
AISTUDIO_API_KEY = os.environ.get('AISTUDIO_API_KEY', '')
|
||||||
OPENAI_BASE_URL = os.environ.get('OPENAI_BASE_URL', 'https://aistudio.baidu.com/llm/lmapi/v3')
|
OPENAI_BASE_URL = os.environ.get('OPENAI_BASE_URL', 'https://aistudio.baidu.com/llm/lmapi/v3')
|
||||||
|
OPENAI_MODEL_NAME = os.environ.get('OPENAI_MODEL_NAME', 'ernie-4.5-turbo-vl-32k')
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ from django.conf.urls.static import static
|
|||||||
from main.views import home as main_home
|
from main.views import home as main_home
|
||||||
|
|
||||||
urlpatterns = [
|
urlpatterns = [
|
||||||
|
path("__reload__/", include("django_browser_reload.urls")),
|
||||||
path('admin/', admin.site.urls),
|
path('admin/', admin.site.urls),
|
||||||
path('accounts/', include('accounts.urls', namespace='accounts')),
|
path('accounts/', include('accounts.urls', namespace='accounts')),
|
||||||
path('main/', include('main.urls', namespace='main')),
|
path('main/', include('main.urls', namespace='main')),
|
||||||
|
|||||||
196
README.md
Normal file
196
README.md
Normal file
@@ -0,0 +1,196 @@
|
|||||||
|
# 多级权限控制数据结构说明
|
||||||
|
|
||||||
|
## 核心概念
|
||||||
|
|
||||||
|
该设计通过 **关键字匹配(Keyword Matching)** 实现数据行级权限控制,适用于学校、企业等层级组织架构场景。
|
||||||
|
|
||||||
|
### 字段定义
|
||||||
|
|
||||||
|
| 字段 | 类型 | 说明 |
|
||||||
|
|------|------|------|
|
||||||
|
| `key` | `KeywordField(multi=True)` | **身份标识关键字** - 表示用户所属的层级/组织,用于匹配"自己的数据" |
|
||||||
|
| `manage_key` | `KeywordField(multi=True)` | **管理范围关键字** - 表示用户能管理的数据范围,用于匹配"管辖范围内的数据" |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 权限模型图解
|
||||||
|
|
||||||
|
```
|
||||||
|
数据权限 = (数据.key ∩ 用户.key) ∪ (数据.key ∩ 用户.manage_key)
|
||||||
|
|
||||||
|
解释:
|
||||||
|
- 用户能看到的数据 = 自己的数据 OR 管辖范围内的数据
|
||||||
|
- 两者都满足"用户权限"(非管理员),只是数据范围不同
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 具体场景示例
|
||||||
|
|
||||||
|
### 场景1:学生视角
|
||||||
|
|
||||||
|
**用户:学生A(2024届人工智能1班)**
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"name": "张三",
|
||||||
|
"role": "学生",
|
||||||
|
"key": [
|
||||||
|
"2024届人工智能1班", // 班级(最细粒度)
|
||||||
|
"2024届", // 年级
|
||||||
|
"计算机与人工智能学院" // 学院
|
||||||
|
],
|
||||||
|
"manage_key": [] // 学生没有管理权限
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**数据匹配逻辑:**
|
||||||
|
- 查询获奖数据时,系统查找 `key` 包含 `"2024届人工智能1班"` 的数据
|
||||||
|
- 结果:只能看到自己的获奖记录
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 场景2:班导师视角
|
||||||
|
|
||||||
|
**用户:班导师B(负责2024届人工智能1班)**
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"name": "李老师",
|
||||||
|
"role": "班导师",
|
||||||
|
"key": [
|
||||||
|
"计算机与人工智能学院" // 所属学院
|
||||||
|
],
|
||||||
|
"manage_key": [
|
||||||
|
"2024届人工智能1班" // 管理的班级
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**数据匹配逻辑:**
|
||||||
|
- 查询时匹配:`key` 包含 `"计算机与人工智能学院"` **OR** `key` 包含 `"2024届人工智能1班"`
|
||||||
|
- 结果:可以看到
|
||||||
|
1. 学院层级的公共数据(通过 `key` 匹配)
|
||||||
|
2. 人工智能1班所有学生的获奖数据(通过 `manage_key` 匹配)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 场景3:扩展案例 - 多级管理员
|
||||||
|
|
||||||
|
**用户:学院教务C(管理学院所有班级)**
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"name": "王教务",
|
||||||
|
"role": "教务",
|
||||||
|
"key": [
|
||||||
|
"计算机与人工智能学院"
|
||||||
|
],
|
||||||
|
"manage_key": [
|
||||||
|
"2024届人工智能1班",
|
||||||
|
"2024届人工智能2班",
|
||||||
|
"2023届软件工程1班",
|
||||||
|
"计算机与人工智能学院" // 管理整个学院
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**权限效果:**
|
||||||
|
- 可以查看学院内所有班级的获奖数据
|
||||||
|
- 仍然只是"用户权限",只是管理范围更大
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 场景4:跨角色对比
|
||||||
|
|
||||||
|
| 角色 | key | manage_key | 可见数据范围 |
|
||||||
|
|------|-----|------------|-------------|
|
||||||
|
| **学生A** | 班级、年级、学院 | - | 仅自己的记录 |
|
||||||
|
| **班导师B** | 学院 | 班级 | 所带班级的全部记录 |
|
||||||
|
| **辅导员** | 学院 | 年级 | 整个年级的全部记录 |
|
||||||
|
| **院领导** | 学院 | 学院 | 整个学院的全部记录 |
|
||||||
|
| **校管理员** | 学校 | 学校 | 全校数据(真正的admin) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 数据结构存储示例
|
||||||
|
|
||||||
|
### 用户表(User Index)
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"user_id": "stu_2024001",
|
||||||
|
"name": "张三",
|
||||||
|
"key": ["2024届人工智能1班", "2024届", "计算机与人工智能学院"],
|
||||||
|
"manage_key": [],
|
||||||
|
"role": "student"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"user_id": "tch_10086",
|
||||||
|
"name": "李老师",
|
||||||
|
"key": ["计算机与人工智能学院"],
|
||||||
|
"manage_key": ["2024届人工智能1班"],
|
||||||
|
"role": "advisor"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 数据表(Award Index)
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"award_id": "awd_001",
|
||||||
|
"title": "校级编程大赛一等奖",
|
||||||
|
"student_name": "张三",
|
||||||
|
"key": ["2024届人工智能1班", "2024届", "计算机与人工智能学院"], // 所属层级
|
||||||
|
"created_by": "stu_2024001"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 查询逻辑伪代码
|
||||||
|
|
||||||
|
```python
|
||||||
|
def get_visible_data(current_user):
|
||||||
|
"""
|
||||||
|
获取当前用户可见的数据
|
||||||
|
"""
|
||||||
|
query = {
|
||||||
|
"bool": {
|
||||||
|
"should": [
|
||||||
|
# 条件1:数据的关键字与用户的key有交集(自己的数据)
|
||||||
|
{
|
||||||
|
"terms": {
|
||||||
|
"key": current_user.key
|
||||||
|
}
|
||||||
|
},
|
||||||
|
# 条件2:数据的关键字与用户的manage_key有交集(管辖的数据)
|
||||||
|
{
|
||||||
|
"terms": {
|
||||||
|
"key": current_user.manage_key
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"minimum_should_match": 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return es.search(index="awards", body=query)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 设计优势
|
||||||
|
|
||||||
|
1. **扁平化权限**:不需要复杂的角色表(RBAC),通过关键字即可控制权限
|
||||||
|
2. **灵活扩展**:新增班级/年级只需添加关键字,无需修改权限架构
|
||||||
|
3. **层级继承**:数据自带完整层级路径(班级→年级→学院),支持多级查询
|
||||||
|
4. **细粒度控制**:可以精确到班级级别,也可以放宽到学院级别
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
生产环境用于创建数据库结构的临时命令:
|
||||||
|
python manage.py shell -c "from elastic.es_connect import create_index_with_mapping; create_index_with_mapping()"
|
||||||
@@ -1,5 +1,23 @@
|
|||||||
import hashlib
|
import hashlib
|
||||||
import hmac
|
import hmac
|
||||||
|
import os
|
||||||
|
import base64
|
||||||
|
from typing import Tuple
|
||||||
|
|
||||||
|
try:
|
||||||
|
from cryptography.hazmat.primitives.asymmetric import rsa, padding
|
||||||
|
from cryptography.hazmat.primitives import serialization, hashes
|
||||||
|
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
|
||||||
|
from cryptography.hazmat.backends import default_backend
|
||||||
|
except Exception:
|
||||||
|
rsa = None
|
||||||
|
padding = None
|
||||||
|
serialization = None
|
||||||
|
hashes = None
|
||||||
|
Cipher = None
|
||||||
|
algorithms = None
|
||||||
|
modes = None
|
||||||
|
default_backend = None
|
||||||
|
|
||||||
|
|
||||||
def salt_for_username(username: str) -> bytes:
|
def salt_for_username(username: str) -> bytes:
|
||||||
@@ -18,3 +36,80 @@ def derive_password(password_plain: str, salt: bytes, iterations: int = 100_000,
|
|||||||
def hmac_sha256(key: bytes, message: bytes) -> bytes:
|
def hmac_sha256(key: bytes, message: bytes) -> bytes:
|
||||||
"""Compute HMAC-SHA256 signature for the given message using key bytes."""
|
"""Compute HMAC-SHA256 signature for the given message using key bytes."""
|
||||||
return hmac.new(key, message, hashlib.sha256).digest()
|
return hmac.new(key, message, hashlib.sha256).digest()
|
||||||
|
|
||||||
|
|
||||||
|
_RSA_PRIVATE = None
|
||||||
|
_RSA_PUBLIC = None
|
||||||
|
|
||||||
|
def _ensure_rsa_keys():
|
||||||
|
global _RSA_PRIVATE, _RSA_PUBLIC
|
||||||
|
if _RSA_PRIVATE is None:
|
||||||
|
if rsa is None:
|
||||||
|
raise RuntimeError("cryptography library is required for RSA operations")
|
||||||
|
_RSA_PRIVATE = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
||||||
|
_RSA_PUBLIC = _RSA_PRIVATE.public_key()
|
||||||
|
|
||||||
|
def get_public_key_spki_b64() -> str:
|
||||||
|
_ensure_rsa_keys()
|
||||||
|
spki = _RSA_PUBLIC.public_bytes(encoding=serialization.Encoding.DER, format=serialization.PublicFormat.SubjectPublicKeyInfo)
|
||||||
|
return base64.b64encode(spki).decode('ascii')
|
||||||
|
|
||||||
|
def rsa_oaep_decrypt_b64(ciphertext_b64: str) -> bytes:
|
||||||
|
_ensure_rsa_keys()
|
||||||
|
ct = base64.b64decode(ciphertext_b64)
|
||||||
|
return _RSA_PRIVATE.decrypt(ct, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None))
|
||||||
|
|
||||||
|
def aes_gcm_decrypt_b64(key_bytes: bytes, iv_b64: str, ciphertext_b64: str) -> bytes:
|
||||||
|
if Cipher is None:
|
||||||
|
raise RuntimeError("cryptography library is required for AES operations")
|
||||||
|
iv = base64.b64decode(iv_b64)
|
||||||
|
data = base64.b64decode(ciphertext_b64)
|
||||||
|
if len(data) < 16:
|
||||||
|
raise ValueError("ciphertext too short")
|
||||||
|
ct = data[:-16]
|
||||||
|
tag = data[-16:]
|
||||||
|
decryptor = Cipher(algorithms.AES(key_bytes), modes.GCM(iv, tag), backend=default_backend()).decryptor()
|
||||||
|
pt = decryptor.update(ct) + decryptor.finalize()
|
||||||
|
return pt
|
||||||
|
|
||||||
|
def gen_salt(length: int = 16) -> bytes:
|
||||||
|
return os.urandom(length)
|
||||||
|
|
||||||
|
def hash_password_with_salt(password_plain: str, salt: bytes, iterations: int = 200_000, dklen: int = 32) -> bytes:
|
||||||
|
return hashlib.pbkdf2_hmac('sha256', password_plain.encode('utf-8'), salt, iterations, dklen=dklen)
|
||||||
|
|
||||||
|
def hash_password_random_salt(password_plain: str) -> Tuple[str, str]:
|
||||||
|
salt = gen_salt(16)
|
||||||
|
h = hash_password_with_salt(password_plain, salt)
|
||||||
|
return base64.b64encode(salt).decode('ascii'), base64.b64encode(h).decode('ascii')
|
||||||
|
|
||||||
|
def verify_password(password_plain: str, salt_b64: str, hash_b64: str) -> bool:
|
||||||
|
try:
|
||||||
|
salt = base64.b64decode(salt_b64)
|
||||||
|
expected = base64.b64decode(hash_b64)
|
||||||
|
actual = hash_password_with_salt(password_plain, salt)
|
||||||
|
return hmac.compare_digest(actual, expected)
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
|
||||||
|
def generate_rsa_private_pem_b64() -> str:
|
||||||
|
if rsa is None or serialization is None:
|
||||||
|
raise RuntimeError("cryptography library is required for RSA operations")
|
||||||
|
priv = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
||||||
|
pem = priv.private_bytes(encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption())
|
||||||
|
return base64.b64encode(pem).decode('ascii')
|
||||||
|
|
||||||
|
def public_spki_b64_from_private_pem_b64(private_pem_b64: str) -> str:
|
||||||
|
if serialization is None:
|
||||||
|
raise RuntimeError("cryptography library is required for RSA operations")
|
||||||
|
priv = serialization.load_pem_private_key(base64.b64decode(private_pem_b64), password=None)
|
||||||
|
pub = priv.public_key()
|
||||||
|
spki = pub.public_bytes(encoding=serialization.Encoding.DER, format=serialization.PublicFormat.SubjectPublicKeyInfo)
|
||||||
|
return base64.b64encode(spki).decode('ascii')
|
||||||
|
|
||||||
|
def rsa_oaep_decrypt_b64_with_private_pem(private_pem_b64: str, ciphertext_b64: str) -> bytes:
|
||||||
|
if serialization is None or padding is None or hashes is None:
|
||||||
|
raise RuntimeError("cryptography library is required for RSA operations")
|
||||||
|
priv = serialization.load_pem_private_key(base64.b64decode(private_pem_b64), password=None)
|
||||||
|
ct = base64.b64decode(ciphertext_b64)
|
||||||
|
return priv.decrypt(ct, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None))
|
||||||
@@ -1,19 +1,14 @@
|
|||||||
import base64
|
import base64
|
||||||
from elastic.es_connect import get_user_by_username as es_get_user_by_username
|
from elastic.es_connect import get_user_by_username as es_get_user_by_username
|
||||||
from .crypto import salt_for_username, derive_password
|
|
||||||
|
|
||||||
def get_user_by_username(username: str):
|
def get_user_by_username(username: str):
|
||||||
"""
|
|
||||||
期望ES中存储的是明文密码,登录时按用户名盐派生后对nonce做HMAC验证。
|
|
||||||
"""
|
|
||||||
es_user = es_get_user_by_username(username)
|
es_user = es_get_user_by_username(username)
|
||||||
if es_user:
|
if es_user:
|
||||||
salt = salt_for_username(username)
|
|
||||||
derived = derive_password(es_user.get('password', ''), salt)
|
|
||||||
return {
|
return {
|
||||||
'user_id': es_user.get('user_id', 0),
|
'user_id': es_user.get('user_id', 0),
|
||||||
'username': es_user.get('username', ''),
|
'username': es_user.get('username', ''),
|
||||||
'password': base64.b64encode(derived).decode('ascii'),
|
'password_hash': es_user.get('password_hash'),
|
||||||
|
'password_salt': es_user.get('password_salt'),
|
||||||
'permission': es_user.get('permission', 1),
|
'permission': es_user.get('permission', 1),
|
||||||
}
|
}
|
||||||
return None
|
return None
|
||||||
@@ -1,64 +1,53 @@
|
|||||||
// Utility: read cookie value
|
|
||||||
function getCookie(name) {
|
function getCookie(name) {
|
||||||
const value = `; ${document.cookie}`;
|
const value = `; ${document.cookie}`;
|
||||||
const parts = value.split(`; ${name}=`);
|
const parts = value.split(`; ${name}=`);
|
||||||
if (parts.length === 2) return parts.pop().split(';').shift();
|
if (parts.length === 2) return parts.pop().split(';').shift();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Convert base64 string to ArrayBuffer
|
|
||||||
function base64ToArrayBuffer(b64) {
|
function base64ToArrayBuffer(b64) {
|
||||||
const binary = atob(b64);
|
const binary = atob(b64);
|
||||||
const bytes = new Uint8Array(binary.length);
|
const bytes = new Uint8Array(binary.length);
|
||||||
for (let i = 0; i < binary.length; i++) {
|
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
||||||
bytes[i] = binary.charCodeAt(i);
|
|
||||||
}
|
|
||||||
return bytes.buffer;
|
return bytes.buffer;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ArrayBuffer to base64
|
|
||||||
function arrayBufferToBase64(buffer) {
|
function arrayBufferToBase64(buffer) {
|
||||||
const bytes = new Uint8Array(buffer);
|
const bytes = new Uint8Array(buffer);
|
||||||
let binary = '';
|
let binary = '';
|
||||||
for (let i = 0; i < bytes.byteLength; i++) {
|
for (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]);
|
||||||
binary += String.fromCharCode(bytes[i]);
|
|
||||||
}
|
|
||||||
return btoa(binary);
|
return btoa(binary);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function deriveKey(password, saltBytes, iterations = 100000, length = 32) {
|
async function importRsaPublicKey(spkiBytes) {
|
||||||
const encoder = new TextEncoder();
|
return window.crypto.subtle.importKey('spki', spkiBytes, { name: 'RSA-OAEP', hash: 'SHA-256' }, false, ['encrypt']);
|
||||||
const keyMaterial = await window.crypto.subtle.importKey(
|
|
||||||
'raw',
|
|
||||||
encoder.encode(password),
|
|
||||||
{ name: 'PBKDF2' },
|
|
||||||
false,
|
|
||||||
['deriveBits']
|
|
||||||
);
|
|
||||||
|
|
||||||
const derivedBits = await window.crypto.subtle.deriveBits(
|
|
||||||
{
|
|
||||||
name: 'PBKDF2',
|
|
||||||
salt: saltBytes,
|
|
||||||
iterations,
|
|
||||||
hash: 'SHA-256'
|
|
||||||
},
|
|
||||||
keyMaterial,
|
|
||||||
length * 8
|
|
||||||
);
|
|
||||||
|
|
||||||
return new Uint8Array(derivedBits);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function hmacSha256(keyBytes, messageBytes) {
|
async function rsaOaepEncrypt(publicKey, dataBytes) {
|
||||||
const key = await window.crypto.subtle.importKey(
|
const encrypted = await window.crypto.subtle.encrypt({ name: 'RSA-OAEP' }, publicKey, dataBytes);
|
||||||
'raw',
|
return new Uint8Array(encrypted);
|
||||||
keyBytes,
|
}
|
||||||
{ name: 'HMAC', hash: { name: 'SHA-256' } },
|
|
||||||
false,
|
async function importAesKey(keyBytes) {
|
||||||
['sign']
|
return window.crypto.subtle.importKey('raw', keyBytes, { name: 'AES-GCM' }, false, ['encrypt']);
|
||||||
);
|
}
|
||||||
const signature = await window.crypto.subtle.sign('HMAC', key, messageBytes);
|
|
||||||
return new Uint8Array(signature);
|
async function aesGcmEncrypt(aesKey, ivBytes, dataBytes) {
|
||||||
|
const ct = await window.crypto.subtle.encrypt({ name: 'AES-GCM', iv: ivBytes }, aesKey, dataBytes);
|
||||||
|
return new Uint8Array(ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
let needCaptcha = false;
|
||||||
|
|
||||||
|
async function loadCaptcha() {
|
||||||
|
const csrftoken = getCookie('csrftoken');
|
||||||
|
const resp = await fetch('/accounts/captcha/', { method: 'GET', credentials: 'same-origin', headers: { 'X-CSRFToken': csrftoken || '' } });
|
||||||
|
const data = await resp.json();
|
||||||
|
if (resp.ok && data.ok) {
|
||||||
|
const img = document.getElementById('captchaImg');
|
||||||
|
const box = document.getElementById('captchaBox');
|
||||||
|
img.src = 'data:image/png;base64,' + data.image_b64;
|
||||||
|
box.style.display = 'block';
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
document.getElementById('loginForm').addEventListener('submit', async (e) => {
|
document.getElementById('loginForm').addEventListener('submit', async (e) => {
|
||||||
@@ -68,53 +57,70 @@ document.getElementById('loginForm').addEventListener('submit', async (e) => {
|
|||||||
|
|
||||||
const username = document.getElementById('username').value.trim();
|
const username = document.getElementById('username').value.trim();
|
||||||
const password = document.getElementById('password').value;
|
const password = document.getElementById('password').value;
|
||||||
if (!username || !password) {
|
if (!username || !password) { errorEl.textContent = '请输入账户与密码'; return; }
|
||||||
errorEl.textContent = '请输入账户与密码';
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const btn = document.getElementById('loginBtn');
|
const btn = document.getElementById('loginBtn');
|
||||||
btn.disabled = true;
|
btn.disabled = true;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Step 1: get challenge (nonce + salt)
|
|
||||||
const csrftoken = getCookie('csrftoken');
|
const csrftoken = getCookie('csrftoken');
|
||||||
const chalResp = await fetch('/accounts/challenge/', {
|
const pkResp = await fetch('/accounts/pubkey/', { method: 'GET', credentials: 'same-origin', headers: { 'X-CSRFToken': csrftoken || '' } });
|
||||||
method: 'POST',
|
if (!pkResp.ok) throw new Error('获取公钥失败');
|
||||||
credentials: 'same-origin',
|
const pkJson = await pkResp.json();
|
||||||
headers: {
|
const spkiBytes = new Uint8Array(base64ToArrayBuffer(pkJson.public_key_spki));
|
||||||
'Content-Type': 'application/json',
|
const pubKey = await importRsaPublicKey(spkiBytes);
|
||||||
'X-CSRFToken': csrftoken || ''
|
|
||||||
},
|
const aesKeyRaw = new Uint8Array(32); window.crypto.getRandomValues(aesKeyRaw);
|
||||||
body: JSON.stringify({ username })
|
const encAesKey = await rsaOaepEncrypt(pubKey, aesKeyRaw);
|
||||||
|
const encAesKeyB64 = arrayBufferToBase64(encAesKey);
|
||||||
|
|
||||||
|
const setKeyResp = await fetch('/accounts/session-key/', {
|
||||||
|
method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrftoken || '' }, body: JSON.stringify({ encrypted_key: encAesKeyB64 })
|
||||||
});
|
});
|
||||||
if (!chalResp.ok) {
|
const setKeySnapshot = await (async () => {
|
||||||
throw new Error('获取挑战失败');
|
const clone = setKeyResp.clone();
|
||||||
|
const txt = await clone.text();
|
||||||
|
let parsed = null;
|
||||||
|
try { parsed = await setKeyResp.json(); } catch (_) {}
|
||||||
|
return { txt, parsed };
|
||||||
|
})();
|
||||||
|
if (!setKeySnapshot.parsed) {
|
||||||
|
const msg = (setKeySnapshot.txt || '').trim();
|
||||||
|
const mapped = msg.toLowerCase().includes('decrypt error') ? '会话密钥解密失败,请刷新页面后重试' : (msg || '设置会话密钥失败');
|
||||||
|
throw new Error(mapped);
|
||||||
}
|
}
|
||||||
const chal = await chalResp.json();
|
const setKeyJson = setKeySnapshot.parsed;
|
||||||
const nonceBytes = new Uint8Array(base64ToArrayBuffer(chal.nonce));
|
if (!setKeyResp.ok || !setKeyJson.ok) throw new Error(setKeyJson.message || '设置会话密钥失败');
|
||||||
const saltBytes = new Uint8Array(base64ToArrayBuffer(chal.salt));
|
|
||||||
|
|
||||||
// Step 2: derive secret and compute HMAC
|
const aesKey = await importAesKey(aesKeyRaw);
|
||||||
const derived = await deriveKey(password, saltBytes, 100000, 32);
|
const iv = new Uint8Array(12); window.crypto.getRandomValues(iv);
|
||||||
const hmac = await hmacSha256(derived, nonceBytes);
|
const obj = { username, password };
|
||||||
const hmacB64 = arrayBufferToBase64(hmac);
|
if (needCaptcha) obj.captcha = (document.getElementById('captcha').value || '').trim();
|
||||||
|
const payload = new TextEncoder().encode(JSON.stringify(obj));
|
||||||
|
const ct = await aesGcmEncrypt(aesKey, iv, payload);
|
||||||
|
const ctB64 = arrayBufferToBase64(ct);
|
||||||
|
const ivB64 = arrayBufferToBase64(iv);
|
||||||
|
|
||||||
// Step 3: submit login with username and hmac
|
const submitResp = await fetch('/accounts/login/secure-submit/', {
|
||||||
const submitResp = await fetch('/accounts/login/submit/', {
|
method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrftoken || '' }, body: JSON.stringify({ iv: ivB64, ciphertext: ctB64 })
|
||||||
method: 'POST',
|
|
||||||
credentials: 'same-origin',
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'X-CSRFToken': csrftoken || ''
|
|
||||||
},
|
|
||||||
body: JSON.stringify({ username, hmac: hmacB64 })
|
|
||||||
});
|
});
|
||||||
const submitJson = await submitResp.json();
|
const submitSnapshot = await (async () => {
|
||||||
|
const clone = submitResp.clone();
|
||||||
|
const txt = await clone.text();
|
||||||
|
let parsed = null;
|
||||||
|
try { parsed = await submitResp.json(); } catch (_) {}
|
||||||
|
return { txt, parsed };
|
||||||
|
})();
|
||||||
|
if (!submitSnapshot.parsed) {
|
||||||
|
const msg = (submitSnapshot.txt || '').trim();
|
||||||
|
const mapped = msg.toLowerCase().includes('decrypt error') ? '解密失败,请刷新页面后重试' : (msg || '服务器响应异常');
|
||||||
|
throw new Error(mapped);
|
||||||
|
}
|
||||||
|
const submitJson = submitSnapshot.parsed;
|
||||||
if (!submitResp.ok || !submitJson.ok) {
|
if (!submitResp.ok || !submitJson.ok) {
|
||||||
|
if (submitJson && submitJson.captcha_required) { needCaptcha = true; await loadCaptcha(); }
|
||||||
throw new Error(submitJson.message || '登录失败');
|
throw new Error(submitJson.message || '登录失败');
|
||||||
}
|
}
|
||||||
// Redirect to home with user_id
|
|
||||||
window.location.href = submitJson.redirect_url;
|
window.location.href = submitJson.redirect_url;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(err);
|
console.error(err);
|
||||||
@@ -123,3 +129,8 @@ document.getElementById('loginForm').addEventListener('submit', async (e) => {
|
|||||||
btn.disabled = false;
|
btn.disabled = false;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
document.getElementById('refreshCaptcha').addEventListener('click', async () => {
|
||||||
|
needCaptcha = true;
|
||||||
|
await loadCaptcha();
|
||||||
|
});
|
||||||
@@ -12,7 +12,7 @@
|
|||||||
.container { max-width: 360px; margin: 12vh auto; padding: 24px; background: #fff; border-radius: 10px; box-shadow: 0 8px 24px rgba(0,0,0,0.08); }
|
.container { max-width: 360px; margin: 12vh auto; padding: 24px; background: #fff; border-radius: 10px; box-shadow: 0 8px 24px rgba(0,0,0,0.08); }
|
||||||
h1 { font-size: 20px; margin: 0 0 16px; }
|
h1 { font-size: 20px; margin: 0 0 16px; }
|
||||||
label { display: block; margin: 12px 0 6px; color: #333; }
|
label { display: block; margin: 12px 0 6px; color: #333; }
|
||||||
input { width: 100%; padding: 10px 12px; border: 1px solid #dcdde1; border-radius: 6px; }
|
input { width: 100%; padding: 10px 0px; border: 1px solid #dcdde1; border-radius: 6px; }
|
||||||
button { width: 100%; margin-top: 16px; padding: 10px 12px; background: #2d8cf0; color: #fff; border: none; border-radius: 6px; cursor: pointer; }
|
button { width: 100%; margin-top: 16px; padding: 10px 12px; background: #2d8cf0; color: #fff; border: none; border-radius: 6px; cursor: pointer; }
|
||||||
button:disabled { background: #9bbcf0; cursor: not-allowed; }
|
button:disabled { background: #9bbcf0; cursor: not-allowed; }
|
||||||
.error { color: #d93025; margin-top: 10px; min-height: 20px; }
|
.error { color: #d93025; margin-top: 10px; min-height: 20px; }
|
||||||
@@ -30,9 +30,22 @@
|
|||||||
<label for="password">密码</label>
|
<label for="password">密码</label>
|
||||||
<input id="password" name="password" type="password" autocomplete="current-password" required />
|
<input id="password" name="password" type="password" autocomplete="current-password" required />
|
||||||
|
|
||||||
|
<div id="captchaBox" style="display:none; margin-top:12px;">
|
||||||
|
<label for="captcha">验证码</label>
|
||||||
|
<div style="display:flex; gap:8px; align-items:center;">
|
||||||
|
<input id="captcha" name="captcha" type="text" autocomplete="off" style="flex:1;" />
|
||||||
|
<img id="captchaImg" alt="验证码" style="height:40px; border:1px solid #dcdde1; border-radius:6px;" />
|
||||||
|
<button id="refreshCaptcha" type="button" style="width:auto;">刷新</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<button id="loginBtn" type="submit">登录</button>
|
<button id="loginBtn" type="submit">登录</button>
|
||||||
<div id="error" class="error"></div>
|
<div id="error" class="error"></div>
|
||||||
</form>
|
</form>
|
||||||
|
<div class="hint" style="text-align:center; margin-top:12px;">
|
||||||
|
还没有账号?
|
||||||
|
<a href="/accounts/register/" style="color:#2d8cf0; text-decoration:none;">去注册</a>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script src="{% static 'accounts/login.js' %}"></script>
|
<script src="{% static 'accounts/login.js' %}"></script>
|
||||||
|
|||||||
488
accounts/templates/accounts/profile.html
Normal file
488
accounts/templates/accounts/profile.html
Normal file
@@ -0,0 +1,488 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<title>个人中心</title>
|
||||||
|
<style>
|
||||||
|
body { font-family: system-ui, -apple-system, Segoe UI, Roboto, sans-serif; background: #f5f6fa; margin: 0; }
|
||||||
|
/* 侧边栏样式 */
|
||||||
|
.sidebar { position: fixed; top: 0; left: 0; width: 180px; height: 100vh; background: #1e1e2e; color: white; padding: 20px; box-shadow: 2px 0 5px rgba(0,0,0,0.1); z-index: 1000; display: flex; flex-direction: column; align-items: center; }
|
||||||
|
.user-id-sidebar { text-align: center; margin-bottom: 0px; }
|
||||||
|
.sidebar h3 { margin-top: 0; font-size: 18px; color: #add8e6; text-align: center; margin-bottom: 20px; }
|
||||||
|
.navigation-links { width: 100%; margin-top: 60px; }
|
||||||
|
.sidebar a { display: block; color: #8be9fd; text-decoration: none; margin: 10px 0; font-size: 16px; padding: 15px; border-radius: 4px; transition: all 0.2s ease; }
|
||||||
|
.sidebar a:hover { color: #ff79c6; background-color: rgba(139, 233, 253, 0.2); }
|
||||||
|
|
||||||
|
/* 主内容区 */
|
||||||
|
.main-content { margin-left: 220px; padding: 40px; }
|
||||||
|
.profile-card { background: #fff; border-radius: 14px; box-shadow: 0 10px 24px rgba(31,35,40,0.08); padding: 30px; margin-bottom: 40px; }
|
||||||
|
.rc-card { margin-top: 18px; }
|
||||||
|
.profile-header { display: flex; align-items: center; margin-bottom: 20px; border-bottom: 1px solid #eee; padding-bottom: 20px; }
|
||||||
|
.profile-info h2 { margin: 0; color: #1e1e2e; }
|
||||||
|
.profile-info p { margin: 5px 0; color: #666; }
|
||||||
|
.label { font-weight: bold; color: #333; margin-right: 10px; }
|
||||||
|
|
||||||
|
.section-title { font-size: 20px; font-weight: bold; margin: 34px 0 24px; color: #1e1e2e; }
|
||||||
|
.image-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 20px; }
|
||||||
|
.image-item { background: #fff; border-radius: 10px; overflow: hidden; box-shadow: 0 4px 12px rgba(0,0,0,0.05); transition: transform 0.2s; }
|
||||||
|
.image-item:hover { transform: translateY(-5px); }
|
||||||
|
.image-item img { width: 100%; height: 150px; object-fit: cover; cursor: pointer; }
|
||||||
|
.image-item .info { padding: 10px; font-size: 12px; color: #888; text-align: center; }
|
||||||
|
|
||||||
|
.no-data { text-align: center; color: #999; padding: 40px; }
|
||||||
|
.form-group { margin-bottom: 14px; }
|
||||||
|
.form-group label { display:block; margin-bottom: 6px; font-weight: 600; color: #333; }
|
||||||
|
.form-group input { width: 100%; padding: 10px 12px; border: 1px solid #d1d5db; border-radius: 8px; box-sizing: border-box; }
|
||||||
|
.btn { padding: 10px 14px; border: none; border-radius: 10px; cursor: pointer; background: #4f46e5; color: #fff; }
|
||||||
|
.msg { margin-top: 10px; font-size: 13px; }
|
||||||
|
.msg.error { color: #b91c1c; }
|
||||||
|
.msg.success { color: #166534; }
|
||||||
|
|
||||||
|
/* 图片放大模态框 */
|
||||||
|
.image-modal { position: fixed; inset: 0; background: rgba(0,0,0,0.8); display: none; align-items: center; justify-content: center; z-index: 2000; overflow: hidden; }
|
||||||
|
.image-modal-content { max-width: 90%; max-height: 90%; border-radius: 8px; transform-origin: center center; cursor: grab; user-select: none; }
|
||||||
|
.image-modal-close { position: absolute; top: 20px; right: 30px; color: white; font-size: 40px; font-weight: bold; cursor: pointer; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<!-- 侧边栏 -->
|
||||||
|
<div class="sidebar">
|
||||||
|
<div class="user-id-sidebar">
|
||||||
|
<h3>你好,<span id="sidebarUsername">{{ username|default:"访客" }}</span></h3>
|
||||||
|
</div>
|
||||||
|
<div class="navigation-links">
|
||||||
|
<a href="{% url 'main:home' %}">返回主页</a>
|
||||||
|
<a id="logoutBtn" style="cursor:pointer;">退出登录</a>
|
||||||
|
{% csrf_token %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="main-content">
|
||||||
|
{% if subpage %}
|
||||||
|
<div class="profile-card">
|
||||||
|
<div class="profile-header">
|
||||||
|
<div class="profile-info">
|
||||||
|
<h2>{{ subpage_title }}</h2>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div style="margin-bottom: 12px;">
|
||||||
|
<a href="{% url 'accounts:profile' %}" style="color:#2d8cf0; text-decoration:none;">返回个人中心</a>
|
||||||
|
</div>
|
||||||
|
{% if subpage == "username" %}
|
||||||
|
<form id="nameForm">
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="newUsername">新用户名</label>
|
||||||
|
<input type="text" id="newUsername" placeholder="请输入新用户名" required>
|
||||||
|
</div>
|
||||||
|
<button type="submit" class="btn">保存</button>
|
||||||
|
<div id="nameMsg" class="msg"></div>
|
||||||
|
</form>
|
||||||
|
{% endif %}
|
||||||
|
{% if subpage == "password" %}
|
||||||
|
<form id="pwdForm">
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="newPassword">新密码</label>
|
||||||
|
<input type="password" id="newPassword" autocomplete="new-password" required>
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="confirmPassword">确认密码</label>
|
||||||
|
<input type="password" id="confirmPassword" autocomplete="new-password" required>
|
||||||
|
</div>
|
||||||
|
<button type="submit" class="btn">保存</button>
|
||||||
|
<div id="pwdMsg" class="msg"></div>
|
||||||
|
</form>
|
||||||
|
{% endif %}
|
||||||
|
{% if subpage == "registration-code" %}
|
||||||
|
<form id="rcForm">
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="newRegCode">新注册码</label>
|
||||||
|
<input type="text" id="newRegCode" placeholder="输入新注册码后替换原有 key" required>
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label>预览</label>
|
||||||
|
<div id="rcPreview" style="background:#f8fafc; border:1px solid #e5e7eb; border-radius:10px; padding:10px 12px; font-size:13px; color:#334155;">
|
||||||
|
<div style="color:#64748b;">输入注册码后自动显示 key 预览</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<button type="submit" class="btn">替换</button>
|
||||||
|
<div id="rcMsg" class="msg"></div>
|
||||||
|
</form>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
{% else %}
|
||||||
|
<div class="profile-card">
|
||||||
|
<div class="profile-header">
|
||||||
|
<div class="profile-info">
|
||||||
|
<h2>个人信息</h2>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="profile-details">
|
||||||
|
<p><span class="label">用户名:</span> <span id="profileUsername">{{ profile_user.username }}</span></p>
|
||||||
|
<p><span class="label">用户ID:</span> {{ profile_user.user_id }}</p>
|
||||||
|
<p><span class="label">注册码:</span> {{ profile_user.registration_code|default:"无" }}</p>
|
||||||
|
<p><span class="label">所属:</span> {{ profile_user.key|join:"、"|default:"未填写" }}</p>
|
||||||
|
<p><span class="label">可管理级别:</span> {{ profile_user.manage_key|join:"、"|default:"无" }}</p>
|
||||||
|
<p><span class="label">权限级别:</span> {{ permission_name }}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="profile-card">
|
||||||
|
<div class="profile-header">
|
||||||
|
<div class="profile-info">
|
||||||
|
<h2>账号设置</h2>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div style="display:flex; gap:12px; flex-wrap:wrap;">
|
||||||
|
<a class="btn" href="{% url 'accounts:profile_username' %}">修改用户名</a>
|
||||||
|
<a class="btn" href="{% url 'accounts:profile_password' %}">修改密码</a>
|
||||||
|
<a class="btn" href="{% url 'accounts:profile_registration_code' %}">替换注册码</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="section-title">我的提交</div>
|
||||||
|
{% if achievements %}
|
||||||
|
<div class="image-grid">
|
||||||
|
{% for item in achievements %}
|
||||||
|
<div class="image-item">
|
||||||
|
{% if item.image_url %}
|
||||||
|
<img src="{{ item.image_url }}" alt="提交的图片" onclick="openModal(this.src)">
|
||||||
|
{% else %}
|
||||||
|
<div style="height: 150px; background: #eee; display: flex; align-items: center; justify-content: center; color: #ccc;">无图片</div>
|
||||||
|
{% endif %}
|
||||||
|
<div style="padding: 8px; text-align: center;">
|
||||||
|
<a href="{% url 'elastic:manage_page' %}?id={{ item.id }}" style="display: inline-block; padding: 4px 12px; background: #eef2ff; color: #4f46e5; text-decoration: none; border-radius: 4px; font-size: 12px; transition: background 0.2s;">管理此条</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
{% else %}
|
||||||
|
<div class="profile-card no-data">
|
||||||
|
<p>你还没有提交过任何图片。</p>
|
||||||
|
<a href="{% url 'elastic:upload_page' %}" style="color: #2d8cf0; text-decoration: none;">去上传第一张图片吧!</a>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 图片放大模态框 -->
|
||||||
|
<div id="imageModal" class="image-modal">
|
||||||
|
<span class="image-modal-close" onclick="closeModal()">×</span>
|
||||||
|
<img id="modalImg" class="image-modal-content">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
function getCookie(name){const v=`; ${document.cookie}`;const p=v.split(`; ${name}=`);if(p.length===2) return p.pop().split(';').shift();}
|
||||||
|
|
||||||
|
// 登出功能
|
||||||
|
document.getElementById('logoutBtn').addEventListener('click', async () => {
|
||||||
|
if(!confirm('确定要退出登录吗?')) return;
|
||||||
|
const csrftoken = getCookie('csrftoken');
|
||||||
|
try {
|
||||||
|
const resp = await fetch('/accounts/logout/', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'X-CSRFToken': csrftoken || '' }
|
||||||
|
});
|
||||||
|
const data = await resp.json();
|
||||||
|
if (data.ok) window.location.href = data.redirect_url;
|
||||||
|
} catch (e) { alert('登出失败'); }
|
||||||
|
});
|
||||||
|
|
||||||
|
// 图片放大功能
|
||||||
|
let modalScale = 1;
|
||||||
|
let modalTranslateX = 0;
|
||||||
|
let modalTranslateY = 0;
|
||||||
|
let modalDragging = false;
|
||||||
|
let modalDragStartX = 0;
|
||||||
|
let modalDragStartY = 0;
|
||||||
|
let modalDragOriginX = 0;
|
||||||
|
let modalDragOriginY = 0;
|
||||||
|
|
||||||
|
function applyModalTransform() {
|
||||||
|
const modalImg = document.getElementById('modalImg');
|
||||||
|
modalImg.style.transform = `translate(${modalTranslateX}px, ${modalTranslateY}px) scale(${modalScale})`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function resetModalTransform() {
|
||||||
|
modalScale = 1;
|
||||||
|
modalTranslateX = 0;
|
||||||
|
modalTranslateY = 0;
|
||||||
|
applyModalTransform();
|
||||||
|
}
|
||||||
|
|
||||||
|
function clampScale(next) {
|
||||||
|
if (next < 0.2) return 0.2;
|
||||||
|
if (next > 5) return 5;
|
||||||
|
return next;
|
||||||
|
}
|
||||||
|
|
||||||
|
function openModal(src) {
|
||||||
|
const modal = document.getElementById('imageModal');
|
||||||
|
const modalImg = document.getElementById('modalImg');
|
||||||
|
modal.style.display = "flex";
|
||||||
|
modalImg.src = src;
|
||||||
|
resetModalTransform();
|
||||||
|
}
|
||||||
|
|
||||||
|
function closeModal() {
|
||||||
|
document.getElementById('imageModal').style.display = "none";
|
||||||
|
}
|
||||||
|
|
||||||
|
const modalEl = document.getElementById('imageModal');
|
||||||
|
const modalImgEl = document.getElementById('modalImg');
|
||||||
|
if (modalEl && modalImgEl) {
|
||||||
|
modalEl.addEventListener('click', (e) => {
|
||||||
|
if (e.target === modalEl) closeModal();
|
||||||
|
});
|
||||||
|
|
||||||
|
modalImgEl.addEventListener('mousedown', (e) => {
|
||||||
|
if (e.button !== 0) return;
|
||||||
|
e.preventDefault();
|
||||||
|
modalDragging = true;
|
||||||
|
modalDragStartX = e.clientX;
|
||||||
|
modalDragStartY = e.clientY;
|
||||||
|
modalDragOriginX = modalTranslateX;
|
||||||
|
modalDragOriginY = modalTranslateY;
|
||||||
|
modalImgEl.style.cursor = 'grabbing';
|
||||||
|
});
|
||||||
|
|
||||||
|
window.addEventListener('mousemove', (e) => {
|
||||||
|
if (!modalDragging) return;
|
||||||
|
const dx = e.clientX - modalDragStartX;
|
||||||
|
const dy = e.clientY - modalDragStartY;
|
||||||
|
modalTranslateX = modalDragOriginX + dx;
|
||||||
|
modalTranslateY = modalDragOriginY + dy;
|
||||||
|
applyModalTransform();
|
||||||
|
});
|
||||||
|
|
||||||
|
window.addEventListener('mouseup', () => {
|
||||||
|
if (!modalDragging) return;
|
||||||
|
modalDragging = false;
|
||||||
|
modalImgEl.style.cursor = 'grab';
|
||||||
|
});
|
||||||
|
|
||||||
|
modalEl.addEventListener('wheel', (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const rect = modalImgEl.getBoundingClientRect();
|
||||||
|
const cx = e.clientX - rect.left - rect.width / 2;
|
||||||
|
const cy = e.clientY - rect.top - rect.height / 2;
|
||||||
|
const nextScale = clampScale(modalScale * (e.deltaY < 0 ? 1.1 : 0.9));
|
||||||
|
const ratio = nextScale / modalScale;
|
||||||
|
modalTranslateX = (modalTranslateX - cx) * ratio + cx;
|
||||||
|
modalTranslateY = (modalTranslateY - cy) * ratio + cy;
|
||||||
|
modalScale = nextScale;
|
||||||
|
applyModalTransform();
|
||||||
|
}, { passive: false });
|
||||||
|
|
||||||
|
modalImgEl.addEventListener('touchstart', (e) => {
|
||||||
|
if (e.touches.length !== 1) return;
|
||||||
|
const t = e.touches[0];
|
||||||
|
modalDragging = true;
|
||||||
|
modalDragStartX = t.clientX;
|
||||||
|
modalDragStartY = t.clientY;
|
||||||
|
modalDragOriginX = modalTranslateX;
|
||||||
|
modalDragOriginY = modalTranslateY;
|
||||||
|
}, { passive: true });
|
||||||
|
|
||||||
|
modalImgEl.addEventListener('touchmove', (e) => {
|
||||||
|
if (!modalDragging || e.touches.length !== 1) return;
|
||||||
|
const t = e.touches[0];
|
||||||
|
const dx = t.clientX - modalDragStartX;
|
||||||
|
const dy = t.clientY - modalDragStartY;
|
||||||
|
modalTranslateX = modalDragOriginX + dx;
|
||||||
|
modalTranslateY = modalDragOriginY + dy;
|
||||||
|
applyModalTransform();
|
||||||
|
}, { passive: true });
|
||||||
|
|
||||||
|
modalImgEl.addEventListener('touchend', () => {
|
||||||
|
modalDragging = false;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const pwdForm = document.getElementById('pwdForm');
|
||||||
|
if (pwdForm) {
|
||||||
|
pwdForm.addEventListener('submit', async (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const msg = document.getElementById('pwdMsg');
|
||||||
|
msg.textContent = '';
|
||||||
|
msg.className = 'msg';
|
||||||
|
|
||||||
|
const pwd = (document.getElementById('newPassword').value || '').trim();
|
||||||
|
const cpwd = (document.getElementById('confirmPassword').value || '').trim();
|
||||||
|
if (pwd !== cpwd) {
|
||||||
|
msg.textContent = '密码和确认密码不匹配';
|
||||||
|
msg.className = 'msg error';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (pwd.length < 6) {
|
||||||
|
msg.textContent = '密码长度至少为6位';
|
||||||
|
msg.className = 'msg error';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const csrftoken = getCookie('csrftoken');
|
||||||
|
const resp = await fetch(`/elastic/users/{{ profile_user.user_id }}/update/`, {
|
||||||
|
method: 'POST',
|
||||||
|
credentials: 'same-origin',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'X-CSRFToken': csrftoken || ''
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ password: pwd })
|
||||||
|
});
|
||||||
|
const data = await resp.json();
|
||||||
|
if (resp.ok && data.status === 'success') {
|
||||||
|
msg.textContent = '修改成功';
|
||||||
|
msg.className = 'msg success';
|
||||||
|
document.getElementById('newPassword').value = '';
|
||||||
|
document.getElementById('confirmPassword').value = '';
|
||||||
|
} else {
|
||||||
|
msg.textContent = data.message || '操作失败';
|
||||||
|
msg.className = 'msg error';
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
msg.textContent = '操作失败';
|
||||||
|
msg.className = 'msg error';
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const nameForm = document.getElementById('nameForm');
|
||||||
|
if (nameForm) {
|
||||||
|
nameForm.addEventListener('submit', async (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const msg = document.getElementById('nameMsg');
|
||||||
|
msg.textContent = '';
|
||||||
|
msg.className = 'msg';
|
||||||
|
const input = document.getElementById('newUsername');
|
||||||
|
const newName = (input.value || '').trim();
|
||||||
|
const currentNameEl = document.getElementById('profileUsername');
|
||||||
|
const currentName = (currentNameEl && currentNameEl.textContent ? currentNameEl.textContent : '').trim();
|
||||||
|
if (!newName) {
|
||||||
|
msg.textContent = '请输入用户名';
|
||||||
|
msg.className = 'msg error';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (newName.length > 50) {
|
||||||
|
msg.textContent = '用户名过长';
|
||||||
|
msg.className = 'msg error';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (currentName && newName === currentName) {
|
||||||
|
msg.textContent = '用户名未变化';
|
||||||
|
msg.className = 'msg error';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const csrftoken = getCookie('csrftoken');
|
||||||
|
const resp = await fetch('/accounts/profile/username/update/', {
|
||||||
|
method: 'POST',
|
||||||
|
credentials: 'same-origin',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'X-CSRFToken': csrftoken || ''
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ username: newName })
|
||||||
|
});
|
||||||
|
const data = await resp.json();
|
||||||
|
if (resp.ok && data.ok) {
|
||||||
|
msg.textContent = '修改成功';
|
||||||
|
msg.className = 'msg success';
|
||||||
|
if (currentNameEl) currentNameEl.textContent = data.username || newName;
|
||||||
|
const sidebarName = document.getElementById('sidebarUsername');
|
||||||
|
if (sidebarName) sidebarName.textContent = data.username || newName;
|
||||||
|
input.value = '';
|
||||||
|
} else {
|
||||||
|
msg.textContent = (data && data.message) ? data.message : '操作失败';
|
||||||
|
msg.className = 'msg error';
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
msg.textContent = '操作失败';
|
||||||
|
msg.className = 'msg error';
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const rcForm = document.getElementById('rcForm');
|
||||||
|
if (rcForm) {
|
||||||
|
let rcPreviewTimer = null;
|
||||||
|
let rcPreviewSeq = 0;
|
||||||
|
const rcInput = document.getElementById('newRegCode');
|
||||||
|
const rcPreview = document.getElementById('rcPreview');
|
||||||
|
|
||||||
|
async function refreshRcPreview(code) {
|
||||||
|
const seq = ++rcPreviewSeq;
|
||||||
|
if (!code) {
|
||||||
|
rcPreview.innerHTML = '<div style="color:#64748b;">输入注册码后自动显示 key 预览</div>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
rcPreview.innerHTML = '<div style="color:#64748b;">正在查询...</div>';
|
||||||
|
try {
|
||||||
|
const resp = await fetch(`/accounts/profile/registration-code/preview/?code=${encodeURIComponent(code)}`, { method: 'GET', credentials: 'same-origin' });
|
||||||
|
const data = await resp.json();
|
||||||
|
if (seq !== rcPreviewSeq) return;
|
||||||
|
if (!(resp.ok && data && data.ok)) {
|
||||||
|
const msg = (data && data.message) ? data.message : '查询失败';
|
||||||
|
rcPreview.innerHTML = `<div style="color:#b91c1c;">${msg}</div>`;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const keys = ((data.data || {}).keys || []).map(String).filter(Boolean);
|
||||||
|
const manageKeys = ((data.data || {}).manage_keys || []).map(String).filter(Boolean);
|
||||||
|
const keysText = keys.length ? keys.join('、') : '无';
|
||||||
|
const manageText = manageKeys.length ? manageKeys.join('、') : '无';
|
||||||
|
rcPreview.innerHTML = `<div><span style="font-weight:700;">key:</span>${keysText}</div><div style="margin-top:6px;"><span style="font-weight:700;">manage_key:</span>${manageText}</div>`;
|
||||||
|
} catch (e) {
|
||||||
|
if (seq !== rcPreviewSeq) return;
|
||||||
|
rcPreview.innerHTML = '<div style="color:#b91c1c;">查询失败</div>';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (rcInput) {
|
||||||
|
rcInput.addEventListener('input', () => {
|
||||||
|
const code = (rcInput.value || '').trim();
|
||||||
|
if (rcPreviewTimer) window.clearTimeout(rcPreviewTimer);
|
||||||
|
rcPreviewTimer = window.setTimeout(() => refreshRcPreview(code), 300);
|
||||||
|
});
|
||||||
|
refreshRcPreview((rcInput.value || '').trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
rcForm.addEventListener('submit', async (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const msg = document.getElementById('rcMsg');
|
||||||
|
msg.textContent = '';
|
||||||
|
msg.className = 'msg';
|
||||||
|
const code = (document.getElementById('newRegCode').value || '').trim();
|
||||||
|
if (!code) {
|
||||||
|
msg.textContent = '请输入注册码';
|
||||||
|
msg.className = 'msg error';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!confirm('确定要替换注册码吗?该操作会替换你当前的 key。')) return;
|
||||||
|
try {
|
||||||
|
const csrftoken = getCookie('csrftoken');
|
||||||
|
const resp = await fetch('/accounts/profile/registration-code/replace/', {
|
||||||
|
method: 'POST',
|
||||||
|
credentials: 'same-origin',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'X-CSRFToken': csrftoken || ''
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ code })
|
||||||
|
});
|
||||||
|
const data = await resp.json();
|
||||||
|
if (resp.ok && data.ok) {
|
||||||
|
msg.textContent = '替换成功';
|
||||||
|
msg.className = 'msg success';
|
||||||
|
window.location.reload();
|
||||||
|
} else {
|
||||||
|
msg.textContent = (data && data.message) ? data.message : '替换失败';
|
||||||
|
msg.className = 'msg error';
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
msg.textContent = '替换失败';
|
||||||
|
msg.className = 'msg error';
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
82
accounts/templates/accounts/register.html
Normal file
82
accounts/templates/accounts/register.html
Normal file
@@ -0,0 +1,82 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<title>用户注册</title>
|
||||||
|
<style>
|
||||||
|
body { font-family: system-ui, -apple-system, Segoe UI, Roboto, sans-serif; background: #f5f6fa; }
|
||||||
|
.container { max-width: 400px; margin: 10vh auto; padding: 24px; background: #fff; border-radius: 10px; box-shadow: 0 8px 24px rgba(0,0,0,0.08); }
|
||||||
|
h1 { font-size: 20px; margin: 0 0 16px; }
|
||||||
|
label { display:block; margin: 12px 0 6px; color:#333; }
|
||||||
|
input { width:100%; padding:10px 0px; border:1px solid #dcdde1; border-radius:6px; }
|
||||||
|
button { width:100%; margin-top:16px; padding:10px 12px; background:#2d8cf0; color:#fff; border:none; border-radius:6px; cursor:pointer; }
|
||||||
|
button:disabled { background:#9bbcf0; cursor:not-allowed; }
|
||||||
|
.error { color:#d93025; margin-top:10px; min-height:20px; }
|
||||||
|
.hint { color:#888; font-size:12px; margin-top:10px; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="container">
|
||||||
|
<h1>注册新用户</h1>
|
||||||
|
<form id="regForm">
|
||||||
|
{% csrf_token %}
|
||||||
|
<label for="code">注册码(选填)</label>
|
||||||
|
<input id="code" name="code" type="text" />
|
||||||
|
<label for="email">邮箱</label>
|
||||||
|
<input id="email" name="email" type="email" required />
|
||||||
|
<button id="sendCodeBtn" type="button">发送验证码</button>
|
||||||
|
<div id="sendMsg" class="hint"></div>
|
||||||
|
<label for="email_code">邮箱验证码</label>
|
||||||
|
<input id="email_code" name="email_code" type="text" required />
|
||||||
|
<label for="username">用户名</label>
|
||||||
|
<input id="username" name="username" type="text" required />
|
||||||
|
<label for="password">密码</label>
|
||||||
|
<input id="password" name="password" type="password" required />
|
||||||
|
<label for="confirm">确认密码</label>
|
||||||
|
<input id="confirm" name="confirm" type="password" required />
|
||||||
|
<button id="regBtn" type="submit">注册</button>
|
||||||
|
<div id="error" class="error"></div>
|
||||||
|
</form>
|
||||||
|
<div class="hint">有注册码请填写,否则可留空</div>
|
||||||
|
</div>
|
||||||
|
<script>
|
||||||
|
function getCookie(name){const v=`; ${document.cookie}`;const p=v.split(`; ${name}=`);if(p.length===2) return p.pop().split(';').shift();}
|
||||||
|
document.getElementById('regForm').addEventListener('submit',async(e)=>{
|
||||||
|
e.preventDefault();
|
||||||
|
const err=document.getElementById('error'); err.textContent='';
|
||||||
|
const code=(document.getElementById('code').value||'').trim();
|
||||||
|
const email=(document.getElementById('email').value||'').trim();
|
||||||
|
const username=(document.getElementById('username').value||'').trim();
|
||||||
|
const email_code=(document.getElementById('email_code').value||'').trim();
|
||||||
|
const password=document.getElementById('password').value||'';
|
||||||
|
const confirm=document.getElementById('confirm').value||'';
|
||||||
|
if(!email||!email_code||!username||!password){err.textContent='请填写所有必填字段';return;}
|
||||||
|
if(password!==confirm){err.textContent='两次密码不一致';return;}
|
||||||
|
const btn=document.getElementById('regBtn'); btn.disabled=true;
|
||||||
|
try{
|
||||||
|
const csrftoken=getCookie('csrftoken');
|
||||||
|
const resp=await fetch('/accounts/register/submit/',{method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json','X-CSRFToken':csrftoken||''},body:JSON.stringify({code,email,email_code,username,password})});
|
||||||
|
const data=await resp.json();
|
||||||
|
if(!resp.ok||!data.ok){throw new Error(data.message||'注册失败');}
|
||||||
|
window.location.href=data.redirect_url;
|
||||||
|
}catch(e){err.textContent=e.message||'发生错误';}
|
||||||
|
finally{btn.disabled=false;}
|
||||||
|
});
|
||||||
|
document.getElementById('sendCodeBtn').addEventListener('click',async()=>{
|
||||||
|
const email=(document.getElementById('email').value||'').trim();
|
||||||
|
const msg=document.getElementById('sendMsg');
|
||||||
|
msg.textContent='';
|
||||||
|
if(!email){msg.textContent='请输入邮箱';return;}
|
||||||
|
const btn=document.getElementById('sendCodeBtn'); btn.disabled=true;
|
||||||
|
try{
|
||||||
|
const csrftoken=getCookie('csrftoken');
|
||||||
|
const resp=await fetch('/accounts/email/send-code/',{method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json','X-CSRFToken':csrftoken||''},body:JSON.stringify({email})});
|
||||||
|
const data=await resp.json();
|
||||||
|
if(!resp.ok||!data.ok){throw new Error(data.message||'发送失败');}
|
||||||
|
msg.textContent='验证码已发送,请查收邮件';
|
||||||
|
}catch(e){msg.textContent=e.message||'发送失败';}
|
||||||
|
finally{btn.disabled=false;}
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
186
accounts/templates/accounts/registration_code_requests.html
Normal file
186
accounts/templates/accounts/registration_code_requests.html
Normal file
@@ -0,0 +1,186 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<title>注册码申请管理</title>
|
||||||
|
<style>
|
||||||
|
body { margin: 0; font-family: system-ui, -apple-system, Segoe UI, Roboto, sans-serif; background: #f5f6fa; }
|
||||||
|
.sidebar { position: fixed; top: 0; left: 0; width: 180px; height: 100vh; background: #1e1e2e; color: white; padding: 20px; box-shadow: 2px 0 5px rgba(0,0,0,0.1); z-index: 1000; display: flex; flex-direction: column; align-items: center; }
|
||||||
|
.sidebar h3 { margin-top: 0; font-size: 18px; color: #add8e6; text-align: center; margin-bottom: 20px; }
|
||||||
|
.navigation-links { width: 100%; margin-top: 60px; }
|
||||||
|
.sidebar a { display: block; color: #8be9fd; text-decoration: none; margin: 10px 0; font-size: 16px; padding: 15px; border-radius: 4px; transition: all 0.2s ease; }
|
||||||
|
.sidebar a:hover { color: #ff79c6; background-color: rgba(139, 233, 253, 0.2); }
|
||||||
|
|
||||||
|
.main-content { margin-left: 220px; padding: 40px; }
|
||||||
|
.card { background: #fff; border-radius: 14px; box-shadow: 0 10px 24px rgba(31,35,40,0.08); padding: 24px; }
|
||||||
|
.header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 14px; }
|
||||||
|
.btn { padding: 8px 12px; border: none; border-radius: 10px; cursor: pointer; }
|
||||||
|
.btn-primary { background: #4f46e5; color: #fff; }
|
||||||
|
.btn-secondary { background: #64748b; color: #fff; }
|
||||||
|
.btn-danger { background: #ff4d4f; color: #fff; }
|
||||||
|
.muted { color: #6b7280; font-size: 12px; }
|
||||||
|
table { width: 100%; border-collapse: collapse; margin-top: 12px; }
|
||||||
|
th, td { text-align: left; border-bottom: 1px solid #e5e7eb; padding: 10px 8px; vertical-align: top; font-size: 13px; }
|
||||||
|
tr:hover { background: #f8fafc; }
|
||||||
|
.tag { display: inline-block; padding: 2px 8px; border-radius: 999px; font-size: 12px; background: #eef2ff; color: #3730a3; }
|
||||||
|
.tag.pending { background: #fff7ed; color: #9a3412; }
|
||||||
|
.tag.approved { background: #dcfce7; color: #166534; }
|
||||||
|
.tag.rejected { background: #fee2e2; color: #991b1b; }
|
||||||
|
</style>
|
||||||
|
{% csrf_token %}
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="sidebar">
|
||||||
|
<h3>你好,{{ username|default:"管理员" }}</h3>
|
||||||
|
<div class="navigation-links">
|
||||||
|
<a href="{% url 'main:home' %}">返回主页</a>
|
||||||
|
<a id="logoutBtn" style="cursor:pointer;">退出登录</a>
|
||||||
|
<div id="logoutMsg" class="muted" style="margin-top:6px;"></div>
|
||||||
|
{% csrf_token %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="main-content">
|
||||||
|
<div class="card">
|
||||||
|
<div class="header">
|
||||||
|
<h2 style="margin:0;">注册码申请管理</h2>
|
||||||
|
<div style="display:flex; gap:10px; align-items:center;">
|
||||||
|
<select id="statusFilter" style="padding:8px 10px; border:1px solid #d1d5db; border-radius:10px;">
|
||||||
|
<option value="pending">待审核</option>
|
||||||
|
<option value="">全部</option>
|
||||||
|
<option value="approved">已同意</option>
|
||||||
|
<option value="rejected">已拒绝</option>
|
||||||
|
</select>
|
||||||
|
<button id="refreshBtn" class="btn btn-secondary" type="button">刷新</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="muted">同意后,用户会获得“注册码管理”入口,且仅能使用自己新增的 key。</div>
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th style="width:120px;">用户</th>
|
||||||
|
<th>申请理由</th>
|
||||||
|
<th style="width:170px;">时间</th>
|
||||||
|
<th style="width:110px;">状态</th>
|
||||||
|
<th style="width:220px;">操作</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody id="reqBody"></tbody>
|
||||||
|
</table>
|
||||||
|
<div id="pageMsg" class="muted" style="margin-top:12px;"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
function getCookie(name){const v=`; ${document.cookie}`;const p=v.split(`; ${name}=`);if(p.length===2) return p.pop().split(';').shift();}
|
||||||
|
|
||||||
|
document.getElementById('logoutBtn').addEventListener('click', async () => {
|
||||||
|
const msg = document.getElementById('logoutMsg');
|
||||||
|
msg.textContent = '';
|
||||||
|
const csrftoken = getCookie('csrftoken');
|
||||||
|
try {
|
||||||
|
const resp = await fetch('/accounts/logout/', {
|
||||||
|
method: 'POST',
|
||||||
|
credentials: 'same-origin',
|
||||||
|
headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrftoken || '' },
|
||||||
|
body: JSON.stringify({})
|
||||||
|
});
|
||||||
|
const data = await resp.json();
|
||||||
|
if (data.ok) window.location.href = data.redirect_url;
|
||||||
|
} catch (e) { msg.textContent = '登出失败'; }
|
||||||
|
});
|
||||||
|
|
||||||
|
function fmtTime(t){
|
||||||
|
try{
|
||||||
|
const d = new Date(t);
|
||||||
|
if(String(d) !== 'Invalid Date'){
|
||||||
|
const pad = n=> String(n).padStart(2,'0');
|
||||||
|
return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
||||||
|
}
|
||||||
|
}catch(e){}
|
||||||
|
return t || '';
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderStatus(s){
|
||||||
|
const v = String(s || 'pending');
|
||||||
|
const cls = (v === 'approved' || v === 'rejected') ? v : 'pending';
|
||||||
|
const text = v === 'approved' ? '已同意' : (v === 'rejected' ? '已拒绝' : '待审核');
|
||||||
|
return `<span class="tag ${cls}">${text}</span>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadRequests(){
|
||||||
|
const status = document.getElementById('statusFilter').value;
|
||||||
|
const msg = document.getElementById('pageMsg');
|
||||||
|
msg.textContent = '加载中...';
|
||||||
|
const url = status ? `/accounts/registration-code/requests/list/?status=${encodeURIComponent(status)}` : '/accounts/registration-code/requests/list/';
|
||||||
|
try{
|
||||||
|
const resp = await fetch(url, { credentials: 'same-origin' });
|
||||||
|
const data = await resp.json();
|
||||||
|
if(!(resp.ok && data && data.ok)){
|
||||||
|
msg.textContent = (data && data.message) ? data.message : '加载失败';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const body = document.getElementById('reqBody');
|
||||||
|
body.innerHTML = '';
|
||||||
|
const rows = data.data || [];
|
||||||
|
if(!rows.length){
|
||||||
|
msg.textContent = '暂无数据';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
msg.textContent = '';
|
||||||
|
rows.forEach(r=>{
|
||||||
|
const tr = document.createElement('tr');
|
||||||
|
const uname = (r.username || '') + (r.user_id !== undefined ? `(${r.user_id})` : '');
|
||||||
|
const reason = String(r.reason || '').replace(/</g,'<').replace(/>/g,'>');
|
||||||
|
const created = fmtTime(r.created_at);
|
||||||
|
const statusHtml = renderStatus(r.status);
|
||||||
|
const id = r.request_id || r._id || '';
|
||||||
|
const ops = (String(r.status || 'pending') === 'pending')
|
||||||
|
? `<button class="btn btn-primary" data-act="approve" data-id="${id}">同意</button>
|
||||||
|
<button class="btn btn-danger" data-act="reject" data-id="${id}">拒绝</button>`
|
||||||
|
: `<button class="btn btn-secondary" data-act="view" data-id="${id}">查看</button>`;
|
||||||
|
tr.innerHTML = `<td>${uname}</td><td style="white-space:pre-wrap;">${reason}</td><td>${created}</td><td>${statusHtml}</td><td>${ops}</td>`;
|
||||||
|
body.appendChild(tr);
|
||||||
|
});
|
||||||
|
}catch(e){
|
||||||
|
msg.textContent = '加载失败';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function decide(id, action){
|
||||||
|
const csrftoken = getCookie('csrftoken');
|
||||||
|
const note = '';
|
||||||
|
const resp = await fetch('/accounts/registration-code/requests/decide/', {
|
||||||
|
method: 'POST',
|
||||||
|
credentials: 'same-origin',
|
||||||
|
headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrftoken || '' },
|
||||||
|
body: JSON.stringify({ request_id: id, action, note })
|
||||||
|
});
|
||||||
|
const data = await resp.json();
|
||||||
|
if(!(resp.ok && data && data.ok)){
|
||||||
|
alert((data && data.message) ? data.message : '操作失败');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
loadRequests();
|
||||||
|
}
|
||||||
|
|
||||||
|
document.getElementById('refreshBtn').addEventListener('click', loadRequests);
|
||||||
|
document.getElementById('statusFilter').addEventListener('change', loadRequests);
|
||||||
|
document.addEventListener('click', (e)=>{
|
||||||
|
const t = e.target;
|
||||||
|
if(!(t && t.dataset && t.dataset.id && t.dataset.act)) return;
|
||||||
|
const id = t.dataset.id;
|
||||||
|
const act = t.dataset.act;
|
||||||
|
if(act === 'approve'){
|
||||||
|
if(confirm('确定同意该申请吗?')) decide(id, 'approve');
|
||||||
|
}else if(act === 'reject'){
|
||||||
|
if(confirm('确定拒绝该申请吗?')) decide(id, 'reject');
|
||||||
|
}else if(act === 'view'){
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
loadRequests();
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -4,7 +4,23 @@ app_name = "accounts"
|
|||||||
|
|
||||||
urlpatterns = [
|
urlpatterns = [
|
||||||
path("login/", views.login_page, name="login"),
|
path("login/", views.login_page, name="login"),
|
||||||
path("challenge/", views.challenge, name="challenge"),
|
path("pubkey/", views.pubkey, name="pubkey"),
|
||||||
path("login/submit/", views.login_submit, name="login_submit"),
|
path("captcha/", views.captcha, name="captcha"),
|
||||||
|
path("session-key/", views.set_session_key, name="set_session_key"),
|
||||||
|
path("login/secure-submit/", views.secure_login_submit, name="secure_login_submit"),
|
||||||
path("logout/", views.logout, name="logout"),
|
path("logout/", views.logout, name="logout"),
|
||||||
|
path("register/", views.register_page, name="register"),
|
||||||
|
path("register/submit/", views.register_submit, name="register_submit"),
|
||||||
|
path("email/send-code/", views.send_email_code, name="send_email_code"),
|
||||||
|
path("profile/", views.profile_page, name="profile"),
|
||||||
|
path("profile/username/", views.profile_username_page, name="profile_username"),
|
||||||
|
path("profile/password/", views.profile_password_page, name="profile_password"),
|
||||||
|
path("profile/registration-code/", views.profile_registration_code_page, name="profile_registration_code"),
|
||||||
|
path("profile/username/update/", views.update_profile_username_view, name="update_profile_username"),
|
||||||
|
path("profile/registration-code/replace/", views.replace_registration_code_view, name="replace_registration_code"),
|
||||||
|
path("profile/registration-code/preview/", views.registration_code_preview_view, name="registration_code_preview"),
|
||||||
|
path("registration-code/request/submit/", views.submit_registration_code_request_view, name="submit_registration_code_request"),
|
||||||
|
path("registration-code/requests/", views.registration_code_requests_page, name="registration_code_requests_page"),
|
||||||
|
path("registration-code/requests/list/", views.list_registration_code_requests_view, name="list_registration_code_requests"),
|
||||||
|
path("registration-code/requests/decide/", views.decide_registration_code_request_view, name="decide_registration_code_request"),
|
||||||
]
|
]
|
||||||
@@ -1,7 +1,11 @@
|
|||||||
import base64
|
import base64
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
import hmac
|
import io
|
||||||
|
import random
|
||||||
|
import string
|
||||||
|
import time
|
||||||
|
import smtplib
|
||||||
|
|
||||||
from django.http import JsonResponse, HttpResponseBadRequest
|
from django.http import JsonResponse, HttpResponseBadRequest
|
||||||
from django.shortcuts import render, redirect
|
from django.shortcuts import render, redirect
|
||||||
@@ -10,7 +14,8 @@ from django.views.decorators.csrf import csrf_protect, ensure_csrf_cookie
|
|||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
|
|
||||||
from .es_client import get_user_by_username
|
from .es_client import get_user_by_username
|
||||||
from .crypto import salt_for_username, hmac_sha256
|
from .crypto import get_public_key_spki_b64, rsa_oaep_decrypt_b64, aes_gcm_decrypt_b64, verify_password, generate_rsa_private_pem_b64, public_spki_b64_from_private_pem_b64, rsa_oaep_decrypt_b64_with_private_pem
|
||||||
|
from elastic.es_connect import get_registration_code, get_user_by_username as es_get_user_by_username, get_all_users as es_get_all_users, write_user_data, update_user_by_id, get_user_by_id, create_registration_code_manage_request, find_pending_registration_code_manage_request, list_registration_code_manage_requests, decide_registration_code_manage_request, get_registration_code_manage_request
|
||||||
|
|
||||||
|
|
||||||
@require_http_methods(["GET"])
|
@require_http_methods(["GET"])
|
||||||
@@ -19,90 +24,166 @@ def login_page(request):
|
|||||||
return render(request, "accounts/login.html")
|
return render(request, "accounts/login.html")
|
||||||
|
|
||||||
|
|
||||||
@require_http_methods(["POST"])
|
@require_http_methods(["GET"])
|
||||||
@csrf_protect
|
@ensure_csrf_cookie
|
||||||
def challenge(request):
|
def pubkey(request):
|
||||||
|
pem_b64 = request.session.get("rsa_private_pem_b64")
|
||||||
|
if not pem_b64:
|
||||||
|
pem_b64 = generate_rsa_private_pem_b64()
|
||||||
|
request.session["rsa_private_pem_b64"] = pem_b64
|
||||||
|
pk_b64 = public_spki_b64_from_private_pem_b64(pem_b64)
|
||||||
|
return JsonResponse({"public_key_spki": pk_b64})
|
||||||
|
|
||||||
|
@require_http_methods(["GET"])
|
||||||
|
@ensure_csrf_cookie
|
||||||
|
def captcha(request):
|
||||||
try:
|
try:
|
||||||
payload = json.loads(request.body.decode("utf-8"))
|
from captcha.image import ImageCaptcha
|
||||||
except json.JSONDecodeError:
|
except Exception:
|
||||||
return HttpResponseBadRequest("Invalid JSON")
|
return JsonResponse({"ok": False, "message": "captcha unavailable"}, status=500)
|
||||||
|
code = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(5))
|
||||||
username = payload.get("username", "").strip()
|
request.session["captcha_code"] = code
|
||||||
if not username:
|
img = ImageCaptcha(width=160, height=60)
|
||||||
return HttpResponseBadRequest("Username required")
|
image = img.generate_image(code)
|
||||||
|
buf = io.BytesIO()
|
||||||
# Generate nonce and compute per-username salt
|
image.save(buf, format="PNG")
|
||||||
nonce = os.urandom(16)
|
b64 = base64.b64encode(buf.getvalue()).decode("ascii")
|
||||||
salt = salt_for_username(username)
|
return JsonResponse({"ok": True, "image_b64": b64})
|
||||||
|
|
||||||
# Persist challenge in session to prevent replay with mismatched user
|
|
||||||
request.session["challenge_nonce"] = base64.b64encode(nonce).decode("ascii")
|
|
||||||
request.session["challenge_username"] = username
|
|
||||||
|
|
||||||
return JsonResponse({
|
|
||||||
"nonce": base64.b64encode(nonce).decode("ascii"),
|
|
||||||
"salt": base64.b64encode(salt).decode("ascii"),
|
|
||||||
})
|
|
||||||
|
|
||||||
|
|
||||||
@require_http_methods(["POST"])
|
@require_http_methods(["POST"])
|
||||||
@csrf_protect
|
@csrf_protect
|
||||||
def login_submit(request):
|
def set_session_key(request):
|
||||||
try:
|
try:
|
||||||
payload = json.loads(request.body.decode("utf-8"))
|
payload = json.loads(request.body.decode("utf-8"))
|
||||||
except json.JSONDecodeError:
|
except json.JSONDecodeError:
|
||||||
return HttpResponseBadRequest("Invalid JSON")
|
return HttpResponseBadRequest("Invalid JSON")
|
||||||
|
enc_key_b64 = payload.get("encrypted_key", "")
|
||||||
username = payload.get("username", "").strip()
|
if not enc_key_b64:
|
||||||
client_hmac_b64 = payload.get("hmac", "")
|
|
||||||
if not username or not client_hmac_b64:
|
|
||||||
return HttpResponseBadRequest("Missing fields")
|
return HttpResponseBadRequest("Missing fields")
|
||||||
|
try:
|
||||||
|
pem_b64 = request.session.get("rsa_private_pem_b64")
|
||||||
|
if not pem_b64:
|
||||||
|
return HttpResponseBadRequest("Decrypt error")
|
||||||
|
key_bytes = rsa_oaep_decrypt_b64_with_private_pem(pem_b64, enc_key_b64)
|
||||||
|
except Exception:
|
||||||
|
return HttpResponseBadRequest("Decrypt error")
|
||||||
|
request.session["session_enc_key_b64"] = base64.b64encode(key_bytes).decode("ascii")
|
||||||
|
return JsonResponse({"ok": True})
|
||||||
|
|
||||||
# Validate challenge stored in session
|
def _build_profile_context(request):
|
||||||
session_username = request.session.get("challenge_username")
|
session_user_id = request.session.get("user_id")
|
||||||
nonce_b64 = request.session.get("challenge_nonce")
|
if session_user_id is None:
|
||||||
if not session_username or not nonce_b64 or session_username != username:
|
return None
|
||||||
return HttpResponseBadRequest("Challenge not found or mismatched user")
|
user = get_user_by_id(session_user_id)
|
||||||
|
if not user:
|
||||||
|
return None
|
||||||
|
from elastic.es_connect import search_all
|
||||||
|
from elastic.views import _attach_image_urls
|
||||||
|
raw_results = [r for r in search_all() if str(r.get("writer_id", "")) == str(session_user_id)]
|
||||||
|
achievements = _attach_image_urls(request, raw_results)
|
||||||
|
permission_name = "管理员" if int(user.get("permission", 1)) == 0 else "普通用户"
|
||||||
|
return {
|
||||||
|
"username": request.session.get("username"),
|
||||||
|
"profile_user": user,
|
||||||
|
"permission_name": permission_name,
|
||||||
|
"achievements": achievements,
|
||||||
|
}
|
||||||
|
|
||||||
# Lookup user in ES (placeholder)
|
@require_http_methods(["GET"])
|
||||||
|
@ensure_csrf_cookie
|
||||||
|
def profile_page(request):
|
||||||
|
context = _build_profile_context(request)
|
||||||
|
if context is None:
|
||||||
|
return redirect("/accounts/login/")
|
||||||
|
context["subpage"] = ""
|
||||||
|
return render(request, "accounts/profile.html", context)
|
||||||
|
|
||||||
|
@require_http_methods(["GET"])
|
||||||
|
@ensure_csrf_cookie
|
||||||
|
def profile_username_page(request):
|
||||||
|
context = _build_profile_context(request)
|
||||||
|
if context is None:
|
||||||
|
return redirect("/accounts/login/")
|
||||||
|
context["subpage"] = "username"
|
||||||
|
context["subpage_title"] = "修改用户名"
|
||||||
|
return render(request, "accounts/profile.html", context)
|
||||||
|
|
||||||
|
@require_http_methods(["GET"])
|
||||||
|
@ensure_csrf_cookie
|
||||||
|
def profile_password_page(request):
|
||||||
|
context = _build_profile_context(request)
|
||||||
|
if context is None:
|
||||||
|
return redirect("/accounts/login/")
|
||||||
|
context["subpage"] = "password"
|
||||||
|
context["subpage_title"] = "修改密码"
|
||||||
|
return render(request, "accounts/profile.html", context)
|
||||||
|
|
||||||
|
@require_http_methods(["GET"])
|
||||||
|
@ensure_csrf_cookie
|
||||||
|
def profile_registration_code_page(request):
|
||||||
|
context = _build_profile_context(request)
|
||||||
|
if context is None:
|
||||||
|
return redirect("/accounts/login/")
|
||||||
|
context["subpage"] = "registration-code"
|
||||||
|
context["subpage_title"] = "替换注册码"
|
||||||
|
return render(request, "accounts/profile.html", context)
|
||||||
|
|
||||||
|
@require_http_methods(["POST"])
|
||||||
|
@csrf_protect
|
||||||
|
def secure_login_submit(request):
|
||||||
|
try:
|
||||||
|
payload = json.loads(request.body.decode("utf-8"))
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
return HttpResponseBadRequest("Invalid JSON")
|
||||||
|
iv_b64 = payload.get("iv", "")
|
||||||
|
ct_b64 = payload.get("ciphertext", "")
|
||||||
|
if not iv_b64 or not ct_b64:
|
||||||
|
return HttpResponseBadRequest("Missing fields")
|
||||||
|
key_b64 = request.session.get("session_enc_key_b64")
|
||||||
|
if not key_b64:
|
||||||
|
return HttpResponseBadRequest("Session key missing")
|
||||||
|
try:
|
||||||
|
key_bytes = base64.b64decode(key_b64)
|
||||||
|
pt = aes_gcm_decrypt_b64(key_bytes, iv_b64, ct_b64)
|
||||||
|
obj = json.loads(pt.decode("utf-8"))
|
||||||
|
except Exception:
|
||||||
|
return HttpResponseBadRequest("Decrypt error")
|
||||||
|
username = (obj.get("username") or "").strip()
|
||||||
|
password = (obj.get("password") or "")
|
||||||
|
if not username or not password:
|
||||||
|
return HttpResponseBadRequest("Missing credentials")
|
||||||
|
if bool(request.session.get("login_failed_once")):
|
||||||
|
ans = (obj.get("captcha") or "").strip()
|
||||||
|
code = request.session.get("captcha_code")
|
||||||
|
if not ans or not code or ans.lower() != str(code).lower():
|
||||||
|
return JsonResponse({"ok": False, "message": "验证码错误", "captcha_required": True}, status=401)
|
||||||
user = get_user_by_username(username)
|
user = get_user_by_username(username)
|
||||||
if not user:
|
if not user:
|
||||||
return JsonResponse({"ok": False, "message": "User not found"}, status=401)
|
request.session["login_failed_once"] = True
|
||||||
|
return JsonResponse({"ok": False, "message": "用户不存在", "captcha_required": True}, status=401)
|
||||||
# Server-side HMAC verification
|
if not verify_password(password, user.get("password_salt") or "", user.get("password_hash") or ""):
|
||||||
try:
|
request.session["login_failed_once"] = True
|
||||||
nonce = base64.b64decode(nonce_b64)
|
return JsonResponse({"ok": False, "message": "账户或密码错误", "captcha_required": True}, status=401)
|
||||||
stored_derived_b64 = user.get("password", "")
|
|
||||||
stored_derived = base64.b64decode(stored_derived_b64)
|
|
||||||
server_hmac_b64 = base64.b64encode(hmac_sha256(stored_derived, nonce)).decode("ascii")
|
|
||||||
except Exception:
|
|
||||||
return HttpResponseBadRequest("Verification error")
|
|
||||||
|
|
||||||
if not hmac.compare_digest(server_hmac_b64, client_hmac_b64):
|
|
||||||
return JsonResponse({"ok": False, "message": "Invalid credentials"}, status=401)
|
|
||||||
|
|
||||||
# Successful login: rotate session key and set user session
|
|
||||||
try:
|
try:
|
||||||
request.session.cycle_key()
|
request.session.cycle_key()
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
request.session["user_id"] = user["user_id"]
|
request.session["user_id"] = user["user_id"]
|
||||||
request.session["username"] = user["username"]
|
request.session["username"] = user["username"]
|
||||||
try:
|
try:
|
||||||
request.session["permission"] = int(user["permission"]) if user.get("permission") is not None else 1
|
request.session["permission"] = int(user["permission"]) if user.get("permission") is not None else 1
|
||||||
except Exception:
|
except Exception:
|
||||||
request.session["permission"] = 1
|
request.session["permission"] = 1
|
||||||
|
if "session_enc_key_b64" in request.session:
|
||||||
# Clear challenge to prevent reuse
|
del request.session["session_enc_key_b64"]
|
||||||
for k in ("challenge_username", "challenge_nonce"):
|
if "rsa_private_pem_b64" in request.session:
|
||||||
if k in request.session:
|
del request.session["rsa_private_pem_b64"]
|
||||||
del request.session[k]
|
if "login_failed_once" in request.session:
|
||||||
|
del request.session["login_failed_once"]
|
||||||
return JsonResponse({
|
if "captcha_code" in request.session:
|
||||||
"ok": True,
|
del request.session["captcha_code"]
|
||||||
"redirect_url": f"/main/home/?user_id={user['user_id']}",
|
return JsonResponse({"ok": True, "redirect_url": f"/main/home/?user_id={user['user_id']}"})
|
||||||
})
|
|
||||||
|
|
||||||
|
|
||||||
@require_http_methods(["GET"])
|
@require_http_methods(["GET"])
|
||||||
@@ -147,3 +228,324 @@ def logout(request):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
return resp
|
return resp
|
||||||
|
|
||||||
|
@require_http_methods(["GET"])
|
||||||
|
@ensure_csrf_cookie
|
||||||
|
def register_page(request):
|
||||||
|
return render(request, "accounts/register.html")
|
||||||
|
|
||||||
|
@require_http_methods(["POST"])
|
||||||
|
@csrf_protect
|
||||||
|
def register_submit(request):
|
||||||
|
try:
|
||||||
|
payload = json.loads(request.body.decode("utf-8"))
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
return HttpResponseBadRequest("Invalid JSON")
|
||||||
|
code = (payload.get("code") or "").strip()
|
||||||
|
email = (payload.get("email") or "").strip()
|
||||||
|
email_code = (payload.get("email_code") or "").strip()
|
||||||
|
username = (payload.get("username") or "").strip()
|
||||||
|
password = (payload.get("password") or "")
|
||||||
|
if not email or not email_code or not username or not password:
|
||||||
|
return HttpResponseBadRequest("Missing fields")
|
||||||
|
v = request.session.get("email_verify") or {}
|
||||||
|
if (v.get("email") or "") != email:
|
||||||
|
return JsonResponse({"ok": False, "message": "请先验证邮箱"}, status=400)
|
||||||
|
try:
|
||||||
|
exp_ts = int(v.get("expires_at") or 0)
|
||||||
|
except Exception:
|
||||||
|
exp_ts = 0
|
||||||
|
if exp_ts < int(time.time()):
|
||||||
|
return JsonResponse({"ok": False, "message": "验证码已过期"}, status=400)
|
||||||
|
if (v.get("code") or "") != email_code:
|
||||||
|
return JsonResponse({"ok": False, "message": "邮箱验证码错误"}, status=400)
|
||||||
|
rc = None
|
||||||
|
if code:
|
||||||
|
rc = get_registration_code(code)
|
||||||
|
if not rc:
|
||||||
|
return JsonResponse({"ok": False, "message": "注册码无效"}, status=400)
|
||||||
|
try:
|
||||||
|
exp = rc.get("expires_at")
|
||||||
|
now = __import__("datetime").datetime.now(__import__("datetime").timezone.utc)
|
||||||
|
if hasattr(exp, 'isoformat'):
|
||||||
|
exp_dt = exp
|
||||||
|
else:
|
||||||
|
exp_dt = __import__("datetime").datetime.fromisoformat(str(exp))
|
||||||
|
if exp_dt <= now:
|
||||||
|
return JsonResponse({"ok": False, "message": "注册码已过期"}, status=400)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
existing = es_get_user_by_username(username)
|
||||||
|
if existing:
|
||||||
|
return JsonResponse({"ok": False, "message": "用户名已存在"}, status=409)
|
||||||
|
users = es_get_all_users()
|
||||||
|
next_id = (max([int(u.get("user_id", 0)) for u in users]) + 1) if users else 1
|
||||||
|
ok = write_user_data({
|
||||||
|
"user_id": next_id,
|
||||||
|
"username": username,
|
||||||
|
"password": password,
|
||||||
|
"permission": 1,
|
||||||
|
"email": email,
|
||||||
|
"key": (rc.get("keys") if rc else []) or [],
|
||||||
|
"manage_key": (rc.get("manage_keys") if rc else []) or [],
|
||||||
|
"registration_code": (rc.get("code") if rc else None),
|
||||||
|
})
|
||||||
|
if not ok:
|
||||||
|
return JsonResponse({"ok": False, "message": "注册失败"}, status=500)
|
||||||
|
try:
|
||||||
|
if "email_verify" in request.session:
|
||||||
|
del request.session["email_verify"]
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return JsonResponse({"ok": True, "redirect_url": "/accounts/login/"})
|
||||||
|
|
||||||
|
@require_http_methods(["POST"])
|
||||||
|
@csrf_protect
|
||||||
|
def replace_registration_code_view(request):
|
||||||
|
session_user_id = request.session.get("user_id")
|
||||||
|
if session_user_id is None:
|
||||||
|
return JsonResponse({"ok": False, "message": "未登录"}, status=401)
|
||||||
|
try:
|
||||||
|
payload = json.loads(request.body.decode("utf-8"))
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
return HttpResponseBadRequest("Invalid JSON")
|
||||||
|
code = (payload.get("code") or "").strip()
|
||||||
|
if not code:
|
||||||
|
return JsonResponse({"ok": False, "message": "请输入注册码"}, status=400)
|
||||||
|
rc = get_registration_code(code)
|
||||||
|
if not rc:
|
||||||
|
return JsonResponse({"ok": False, "message": "注册码无效"}, status=400)
|
||||||
|
try:
|
||||||
|
exp = rc.get("expires_at")
|
||||||
|
now = __import__("datetime").datetime.now(__import__("datetime").timezone.utc)
|
||||||
|
if hasattr(exp, 'isoformat'):
|
||||||
|
exp_dt = exp
|
||||||
|
else:
|
||||||
|
exp_dt = __import__("datetime").datetime.fromisoformat(str(exp))
|
||||||
|
if exp_dt <= now:
|
||||||
|
return JsonResponse({"ok": False, "message": "注册码已过期"}, status=400)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
keys = list(rc.get("keys") or [])
|
||||||
|
manage_keys = list(rc.get("manage_keys") or [])
|
||||||
|
ok = update_user_by_id(session_user_id, key=keys, manage_key=manage_keys, registration_code=code)
|
||||||
|
if not ok:
|
||||||
|
return JsonResponse({"ok": False, "message": "替换失败"}, status=500)
|
||||||
|
return JsonResponse({"ok": True})
|
||||||
|
|
||||||
|
@require_http_methods(["POST"])
|
||||||
|
@csrf_protect
|
||||||
|
def update_profile_username_view(request):
|
||||||
|
session_user_id = request.session.get("user_id")
|
||||||
|
if session_user_id is None:
|
||||||
|
return JsonResponse({"ok": False, "message": "未登录"}, status=401)
|
||||||
|
try:
|
||||||
|
payload = json.loads(request.body.decode("utf-8"))
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
return JsonResponse({"ok": False, "message": "JSON无效"}, status=400)
|
||||||
|
new_username = (payload.get("username") or "").strip()
|
||||||
|
if not new_username:
|
||||||
|
return JsonResponse({"ok": False, "message": "请输入用户名"}, status=400)
|
||||||
|
if len(new_username) > 50:
|
||||||
|
return JsonResponse({"ok": False, "message": "用户名过长"}, status=400)
|
||||||
|
me = get_user_by_id(session_user_id) or {}
|
||||||
|
if str(me.get("username", "")).strip() == new_username:
|
||||||
|
request.session["username"] = new_username
|
||||||
|
return JsonResponse({"ok": True, "username": new_username})
|
||||||
|
existing = es_get_user_by_username(new_username)
|
||||||
|
if existing and str(existing.get("user_id")) != str(session_user_id):
|
||||||
|
return JsonResponse({"ok": False, "message": "用户名已存在"}, status=409)
|
||||||
|
ok = update_user_by_id(session_user_id, username=new_username)
|
||||||
|
if not ok:
|
||||||
|
return JsonResponse({"ok": False, "message": "修改失败"}, status=500)
|
||||||
|
request.session["username"] = new_username
|
||||||
|
return JsonResponse({"ok": True, "username": new_username})
|
||||||
|
|
||||||
|
@require_http_methods(["GET"])
|
||||||
|
def registration_code_preview_view(request):
|
||||||
|
session_user_id = request.session.get("user_id")
|
||||||
|
if session_user_id is None:
|
||||||
|
return JsonResponse({"ok": False, "message": "未登录"}, status=401)
|
||||||
|
code = (request.GET.get("code") or "").strip()
|
||||||
|
if not code:
|
||||||
|
return JsonResponse({"ok": False, "message": "请输入注册码"}, status=400)
|
||||||
|
rc = get_registration_code(code)
|
||||||
|
if not rc:
|
||||||
|
return JsonResponse({"ok": False, "message": "注册码无效"}, status=400)
|
||||||
|
try:
|
||||||
|
exp = rc.get("expires_at")
|
||||||
|
now = __import__("datetime").datetime.now(__import__("datetime").timezone.utc)
|
||||||
|
if hasattr(exp, 'isoformat'):
|
||||||
|
exp_dt = exp
|
||||||
|
else:
|
||||||
|
exp_dt = __import__("datetime").datetime.fromisoformat(str(exp))
|
||||||
|
if exp_dt <= now:
|
||||||
|
return JsonResponse({"ok": False, "message": "注册码已过期"}, status=400)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return JsonResponse(
|
||||||
|
{
|
||||||
|
"ok": True,
|
||||||
|
"data": {
|
||||||
|
"code": rc.get("code"),
|
||||||
|
"keys": list(rc.get("keys") or []),
|
||||||
|
"manage_keys": list(rc.get("manage_keys") or []),
|
||||||
|
"expires_at": rc.get("expires_at"),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
@require_http_methods(["POST"])
|
||||||
|
@csrf_protect
|
||||||
|
def submit_registration_code_request_view(request):
|
||||||
|
session_user_id = request.session.get("user_id")
|
||||||
|
if session_user_id is None:
|
||||||
|
return JsonResponse({"ok": False, "message": "未登录"}, status=401)
|
||||||
|
try:
|
||||||
|
perm = int(request.session.get("permission", 1))
|
||||||
|
except Exception:
|
||||||
|
perm = 1
|
||||||
|
if perm == 0:
|
||||||
|
return JsonResponse({"ok": False, "message": "无权限"}, status=403)
|
||||||
|
me = get_user_by_id(session_user_id) or {}
|
||||||
|
if (me.get("manage_key") or []) or int(me.get("can_manage_registration_codes") or 0) == 1:
|
||||||
|
return JsonResponse({"ok": False, "message": "无需申请"}, status=400)
|
||||||
|
if str(me.get("registration_code") or "").strip():
|
||||||
|
return JsonResponse({"ok": False, "message": "已有注册码,无法申请"}, status=400)
|
||||||
|
try:
|
||||||
|
payload = json.loads(request.body.decode("utf-8"))
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
return HttpResponseBadRequest("Invalid JSON")
|
||||||
|
reason = (payload.get("reason") or "").strip()
|
||||||
|
if not reason:
|
||||||
|
return JsonResponse({"ok": False, "message": "请填写申请理由"}, status=400)
|
||||||
|
pending = find_pending_registration_code_manage_request(session_user_id)
|
||||||
|
if pending:
|
||||||
|
return JsonResponse({"ok": True, "message": "已提交申请"})
|
||||||
|
rid = create_registration_code_manage_request(session_user_id, me.get("username"), reason)
|
||||||
|
if not rid:
|
||||||
|
return JsonResponse({"ok": False, "message": "提交失败"}, status=500)
|
||||||
|
return JsonResponse({"ok": True})
|
||||||
|
|
||||||
|
@require_http_methods(["GET"])
|
||||||
|
@ensure_csrf_cookie
|
||||||
|
def registration_code_requests_page(request):
|
||||||
|
session_user_id = request.session.get("user_id")
|
||||||
|
if session_user_id is None:
|
||||||
|
return redirect("/accounts/login/")
|
||||||
|
try:
|
||||||
|
perm = int(request.session.get("permission", 1))
|
||||||
|
except Exception:
|
||||||
|
perm = 1
|
||||||
|
if perm != 0:
|
||||||
|
return redirect("/main/home/")
|
||||||
|
me = get_user_by_id(session_user_id) or {}
|
||||||
|
return render(request, "accounts/registration_code_requests.html", {"username": me.get("username")})
|
||||||
|
|
||||||
|
@require_http_methods(["GET"])
|
||||||
|
def list_registration_code_requests_view(request):
|
||||||
|
session_user_id = request.session.get("user_id")
|
||||||
|
if session_user_id is None:
|
||||||
|
return JsonResponse({"ok": False, "message": "未登录"}, status=401)
|
||||||
|
try:
|
||||||
|
perm = int(request.session.get("permission", 1))
|
||||||
|
except Exception:
|
||||||
|
perm = 1
|
||||||
|
if perm != 0:
|
||||||
|
return JsonResponse({"ok": False, "message": "无权限"}, status=403)
|
||||||
|
status = (request.GET.get("status") or "").strip() or None
|
||||||
|
data = list_registration_code_manage_requests(status=status)
|
||||||
|
return JsonResponse({"ok": True, "data": data})
|
||||||
|
|
||||||
|
@require_http_methods(["POST"])
|
||||||
|
@csrf_protect
|
||||||
|
def decide_registration_code_request_view(request):
|
||||||
|
session_user_id = request.session.get("user_id")
|
||||||
|
if session_user_id is None:
|
||||||
|
return JsonResponse({"ok": False, "message": "未登录"}, status=401)
|
||||||
|
try:
|
||||||
|
perm = int(request.session.get("permission", 1))
|
||||||
|
except Exception:
|
||||||
|
perm = 1
|
||||||
|
if perm != 0:
|
||||||
|
return JsonResponse({"ok": False, "message": "无权限"}, status=403)
|
||||||
|
try:
|
||||||
|
payload = json.loads(request.body.decode("utf-8"))
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
return HttpResponseBadRequest("Invalid JSON")
|
||||||
|
request_id = (payload.get("request_id") or "").strip()
|
||||||
|
action = (payload.get("action") or "").strip().lower()
|
||||||
|
note = (payload.get("note") or "").strip()
|
||||||
|
if not request_id or action not in ("approve", "reject"):
|
||||||
|
return JsonResponse({"ok": False, "message": "参数错误"}, status=400)
|
||||||
|
req = get_registration_code_manage_request(request_id)
|
||||||
|
if not req:
|
||||||
|
return JsonResponse({"ok": False, "message": "申请不存在"}, status=404)
|
||||||
|
status = "approved" if action == "approve" else "rejected"
|
||||||
|
ok = decide_registration_code_manage_request(request_id, status=status, reviewed_by=session_user_id, reviewer_note=note)
|
||||||
|
if not ok:
|
||||||
|
return JsonResponse({"ok": False, "message": "操作失败"}, status=500)
|
||||||
|
if status == "approved":
|
||||||
|
uid = req.get("user_id")
|
||||||
|
update_user_by_id(uid, can_manage_registration_codes=1, registration_manage_keys=[])
|
||||||
|
return JsonResponse({"ok": True})
|
||||||
|
|
||||||
|
@require_http_methods(["POST"])
|
||||||
|
@csrf_protect
|
||||||
|
def send_email_code(request):
|
||||||
|
try:
|
||||||
|
payload = json.loads(request.body.decode("utf-8"))
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
return HttpResponseBadRequest("Invalid JSON")
|
||||||
|
email = (payload.get("email") or "").strip()
|
||||||
|
if not email:
|
||||||
|
return HttpResponseBadRequest("Missing email")
|
||||||
|
if "@" not in email:
|
||||||
|
return JsonResponse({"ok": False, "message": "邮箱格式不正确"}, status=400)
|
||||||
|
verify_code = "".join(random.choice(string.digits) for _ in range(6))
|
||||||
|
ttl = int(os.environ.get("SMTP_CODE_TTL", "600") or 600)
|
||||||
|
request.session["email_verify"] = {"email": email, "code": verify_code, "expires_at": int(time.time()) + max(60, ttl)}
|
||||||
|
ok, msg = _send_smtp_email(email, verify_code)
|
||||||
|
if not ok:
|
||||||
|
return JsonResponse({"ok": False, "message": msg or "验证码发送失败"}, status=500)
|
||||||
|
return JsonResponse({"ok": True})
|
||||||
|
|
||||||
|
def _send_smtp_email(to_email: str, code: str):
|
||||||
|
host = os.environ.get("SMTP_HOST", "")
|
||||||
|
port_raw = os.environ.get("SMTP_PORT", "")
|
||||||
|
try:
|
||||||
|
port = int(port_raw) if port_raw else 0
|
||||||
|
except Exception:
|
||||||
|
port = 0
|
||||||
|
user = os.environ.get("SMTP_USERNAME") or os.environ.get("SMTP_USER") or ""
|
||||||
|
password = os.environ.get("SMTP_PASSWORD", "")
|
||||||
|
use_tls = str(os.environ.get("SMTP_USE_TLS", "")).lower() in ("1", "true", "yes")
|
||||||
|
use_ssl = str(os.environ.get("SMTP_USE_SSL", "")).lower() in ("1", "true", "yes")
|
||||||
|
sender = os.environ.get("SMTP_FROM_EMAIL") or os.environ.get("SMTP_FROM") or user or ""
|
||||||
|
subject = os.environ.get("SMTP_SUBJECT") or "邮箱验证码"
|
||||||
|
if not host or not port or not sender:
|
||||||
|
return False, "缺少SMTP配置"
|
||||||
|
body = f"您的验证码是:{code},10分钟内有效。"
|
||||||
|
msg = f"From: {sender}\r\nTo: {to_email}\r\nSubject: {subject}\r\nContent-Type: text/plain; charset=utf-8\r\n\r\n{body}"
|
||||||
|
try:
|
||||||
|
if use_ssl:
|
||||||
|
server = smtplib.SMTP_SSL(host, port)
|
||||||
|
else:
|
||||||
|
server = smtplib.SMTP(host, port)
|
||||||
|
server.ehlo()
|
||||||
|
if use_tls and not use_ssl:
|
||||||
|
server.starttls()
|
||||||
|
server.ehlo()
|
||||||
|
if user and password:
|
||||||
|
server.login(user, password)
|
||||||
|
server.sendmail(sender, [to_email], msg.encode("utf-8"))
|
||||||
|
try:
|
||||||
|
server.quit()
|
||||||
|
except Exception:
|
||||||
|
try:
|
||||||
|
server.close()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return True, ""
|
||||||
|
except Exception as e:
|
||||||
|
return False, str(e)
|
||||||
|
|||||||
BIN
db.sqlite3
BIN
db.sqlite3
Binary file not shown.
@@ -34,8 +34,16 @@ class UserDocument(Document):
|
|||||||
"""用户数据文档映射"""
|
"""用户数据文档映射"""
|
||||||
user_id = fields.LongField()
|
user_id = fields.LongField()
|
||||||
username = fields.KeywordField()
|
username = fields.KeywordField()
|
||||||
password = fields.KeywordField()
|
email = fields.KeywordField()
|
||||||
permission = fields.IntegerField()
|
registration_code = fields.KeywordField()
|
||||||
|
can_manage_registration_codes = fields.IntegerField()
|
||||||
|
registration_manage_keys = fields.KeywordField(multi=True)
|
||||||
|
password_hash = fields.KeywordField()
|
||||||
|
password_salt = fields.KeywordField()
|
||||||
|
permission = fields.IntegerField() # 还是2种权限,0为管理员,1为用户(区别在于0有全部权限,1在数据管理页面有搜索框,但是索引到的录入信息要根据其用户id查询其key,若其中之一与用户的manage_key字段匹配就显示否则不显示)
|
||||||
|
key = fields.KeywordField(multi=True) #表示该用户的关键字,举个例子:学生A的key为"2024届人工智能1班","2024届","计算机与人工智能学院" 班导师B的key为"计算机与人工智能学院"
|
||||||
|
manage_key = fields.KeywordField(multi=True) #表示该用户管理的关键字(非管理员)班导师B的manage_key为"2024届人工智能1班"
|
||||||
|
#那么学生A就可以在数据管理页面搜索到自己的获奖数据,而班导师B就可以在数据管理页面搜索到所有人工智能1班的获奖数据。也就是说学生A和班导师B都其实只有用户权限
|
||||||
|
|
||||||
class Django:
|
class Django:
|
||||||
model = User
|
model = User
|
||||||
@@ -45,6 +53,18 @@ class UserDocument(Document):
|
|||||||
@GLOBAL_INDEX.doc_type
|
@GLOBAL_INDEX.doc_type
|
||||||
class GlobalDocument(Document):
|
class GlobalDocument(Document):
|
||||||
type_list = fields.KeywordField()
|
type_list = fields.KeywordField()
|
||||||
|
keys_list = fields.KeywordField(multi=True)
|
||||||
|
|
||||||
class Django:
|
class Django:
|
||||||
model = ElasticNews
|
model = ElasticNews
|
||||||
|
|
||||||
|
@GLOBAL_INDEX.doc_type
|
||||||
|
class RegistrationCodeDocument(Document):
|
||||||
|
code = fields.KeywordField() #具体值
|
||||||
|
keys = fields.KeywordField(multi=True) #对应的key
|
||||||
|
manage_keys = fields.KeywordField(multi=True) #对应的manage_key
|
||||||
|
created_at = fields.DateField() #创建时间
|
||||||
|
expires_at = fields.DateField() #过期时间
|
||||||
|
created_by = fields.LongField() #创建者id
|
||||||
|
class Django:
|
||||||
|
model = ElasticNews
|
||||||
|
|||||||
@@ -5,11 +5,13 @@ Django版本的ES连接和操作模块
|
|||||||
from elasticsearch import Elasticsearch
|
from elasticsearch import Elasticsearch
|
||||||
from elasticsearch_dsl import connections
|
from elasticsearch_dsl import connections
|
||||||
import os
|
import os
|
||||||
from .documents import AchievementDocument, UserDocument, GlobalDocument
|
from .documents import AchievementDocument, UserDocument, GlobalDocument, RegistrationCodeDocument
|
||||||
|
from accounts.crypto import hash_password_random_salt
|
||||||
from .indexes import ACHIEVEMENT_INDEX_NAME, USER_INDEX_NAME, GLOBAL_INDEX_NAME
|
from .indexes import ACHIEVEMENT_INDEX_NAME, USER_INDEX_NAME, GLOBAL_INDEX_NAME
|
||||||
import hashlib
|
import hashlib
|
||||||
import time
|
import time
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone, timedelta
|
||||||
|
import uuid
|
||||||
import json
|
import json
|
||||||
|
|
||||||
# 使用环境变量配置ES连接,默认为本机
|
# 使用环境变量配置ES连接,默认为本机
|
||||||
@@ -63,10 +65,12 @@ def create_index_with_mapping():
|
|||||||
|
|
||||||
# --- 4. 创建默认管理员用户(可选:也可检查用户是否已存在)---
|
# --- 4. 创建默认管理员用户(可选:也可检查用户是否已存在)---
|
||||||
# 这里简单处理:每次初始化都写入(可能重复),建议加唯一性判断
|
# 这里简单处理:每次初始化都写入(可能重复),建议加唯一性判断
|
||||||
|
_salt_b64, _hash_b64 = hash_password_random_salt("admin")
|
||||||
admin_user = {
|
admin_user = {
|
||||||
"user_id": 0,
|
"user_id": 0,
|
||||||
"username": "admin",
|
"username": "admin",
|
||||||
"password": "admin", # ⚠️ 生产环境务必加密!
|
"password_hash": _hash_b64,
|
||||||
|
"password_salt": _salt_b64,
|
||||||
"permission": 0
|
"permission": 0
|
||||||
}
|
}
|
||||||
# 可选:检查 admin 是否已存在(根据 user_id 或 username)
|
# 可选:检查 admin 是否已存在(根据 user_id 或 username)
|
||||||
@@ -112,6 +116,137 @@ def ensure_type_in_list(type_name: str):
|
|||||||
except Exception:
|
except Exception:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
def get_keys_list():
|
||||||
|
try:
|
||||||
|
try:
|
||||||
|
doc = GlobalDocument.get(id='keys')
|
||||||
|
cur = list(doc.keys_list or [])
|
||||||
|
except Exception:
|
||||||
|
cur = []
|
||||||
|
doc = GlobalDocument(keys_list=cur)
|
||||||
|
doc.meta.id = 'keys'
|
||||||
|
doc.save()
|
||||||
|
return [str(t).strip().strip(';') for t in cur]
|
||||||
|
except Exception:
|
||||||
|
return []
|
||||||
|
|
||||||
|
def ensure_key_in_list(key_name: str):
|
||||||
|
if not key_name:
|
||||||
|
return False
|
||||||
|
norm = str(key_name).strip().strip(';')
|
||||||
|
try:
|
||||||
|
try:
|
||||||
|
doc = GlobalDocument.get(id='keys')
|
||||||
|
cur = list(doc.keys_list or [])
|
||||||
|
except Exception:
|
||||||
|
cur = []
|
||||||
|
doc = GlobalDocument(keys_list=cur)
|
||||||
|
doc.meta.id = 'keys'
|
||||||
|
cur_sanitized = {str(t).strip().strip(';') for t in cur}
|
||||||
|
if norm not in cur_sanitized:
|
||||||
|
cur.append(norm)
|
||||||
|
doc.keys_list = cur
|
||||||
|
doc.save()
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
|
||||||
|
def generate_registration_code(keys=None, manage_keys=None, expires_in_days: int = 30, created_by: int = None):
|
||||||
|
try:
|
||||||
|
keys = list(keys or [])
|
||||||
|
manage_keys = list(manage_keys or [])
|
||||||
|
for k in list(keys):
|
||||||
|
ensure_key_in_list(k)
|
||||||
|
for mk in list(manage_keys):
|
||||||
|
ensure_key_in_list(mk)
|
||||||
|
code = uuid.uuid4().hex + str(int(time.time()))[-6:]
|
||||||
|
now = datetime.now(timezone.utc)
|
||||||
|
expires = now + timedelta(days=max(1, int(expires_in_days or 30)))
|
||||||
|
doc = RegistrationCodeDocument(
|
||||||
|
code=code,
|
||||||
|
keys=keys,
|
||||||
|
manage_keys=manage_keys,
|
||||||
|
created_at=now.isoformat(),
|
||||||
|
expires_at=expires.isoformat(),
|
||||||
|
created_by=created_by,
|
||||||
|
)
|
||||||
|
doc.meta.id = code
|
||||||
|
doc.save()
|
||||||
|
return {
|
||||||
|
"code": code,
|
||||||
|
"keys": keys,
|
||||||
|
"manage_keys": manage_keys,
|
||||||
|
"created_at": now.isoformat(),
|
||||||
|
"expires_at": expires.isoformat(),
|
||||||
|
}
|
||||||
|
except Exception as e:
|
||||||
|
return None
|
||||||
|
|
||||||
|
def get_registration_code(code: str):
|
||||||
|
try:
|
||||||
|
doc = RegistrationCodeDocument.get(id=str(code))
|
||||||
|
return {
|
||||||
|
"code": getattr(doc, 'code', str(code)),
|
||||||
|
"keys": list(getattr(doc, 'keys', []) or []),
|
||||||
|
"manage_keys": list(getattr(doc, 'manage_keys', []) or []),
|
||||||
|
"created_at": getattr(doc, 'created_at', None),
|
||||||
|
"expires_at": getattr(doc, 'expires_at', None),
|
||||||
|
"created_by": getattr(doc, 'created_by', None),
|
||||||
|
}
|
||||||
|
except Exception:
|
||||||
|
return None
|
||||||
|
|
||||||
|
def list_registration_codes():
|
||||||
|
try:
|
||||||
|
# 增加 size=1000 以支持返回更多注册码
|
||||||
|
search = RegistrationCodeDocument.search()[:1000]
|
||||||
|
body = {
|
||||||
|
"sort": [{"created_at": {"order": "desc"}}],
|
||||||
|
"query": {"exists": {"field": "code"}}
|
||||||
|
}
|
||||||
|
search = search.update_from_dict(body)
|
||||||
|
resp = search.execute()
|
||||||
|
out = []
|
||||||
|
now = datetime.now(timezone.utc)
|
||||||
|
for hit in resp:
|
||||||
|
try:
|
||||||
|
if not getattr(hit, 'code', None):
|
||||||
|
continue
|
||||||
|
except Exception:
|
||||||
|
continue
|
||||||
|
exp = getattr(hit, 'expires_at', None)
|
||||||
|
try:
|
||||||
|
if hasattr(exp, 'isoformat'):
|
||||||
|
exp_dt = exp
|
||||||
|
else:
|
||||||
|
exp_dt = datetime.fromisoformat(str(exp))
|
||||||
|
except Exception:
|
||||||
|
exp_dt = None
|
||||||
|
active = bool(exp_dt and exp_dt > now)
|
||||||
|
out.append({
|
||||||
|
"code": getattr(hit, 'code', ''),
|
||||||
|
"keys": list(getattr(hit, 'keys', []) or []),
|
||||||
|
"manage_keys": list(getattr(hit, 'manage_keys', []) or []),
|
||||||
|
"created_at": getattr(hit, 'created_at', None),
|
||||||
|
"expires_at": getattr(hit, 'expires_at', None),
|
||||||
|
"created_by": getattr(hit, 'created_by', None),
|
||||||
|
"active": active,
|
||||||
|
})
|
||||||
|
return out
|
||||||
|
except Exception:
|
||||||
|
return []
|
||||||
|
|
||||||
|
def revoke_registration_code(code: str):
|
||||||
|
try:
|
||||||
|
doc = RegistrationCodeDocument.get(id=str(code))
|
||||||
|
now = datetime.now(timezone.utc).isoformat()
|
||||||
|
doc.expires_at = now
|
||||||
|
doc.save()
|
||||||
|
return True
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
|
||||||
def get_doc_id(data):
|
def get_doc_id(data):
|
||||||
"""
|
"""
|
||||||
根据数据内容生成唯一ID(用于去重)
|
根据数据内容生成唯一ID(用于去重)
|
||||||
@@ -163,7 +298,8 @@ def search_data(query):
|
|||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
# 使用Django-elasticsearch-dsl进行搜索
|
# 使用Django-elasticsearch-dsl进行搜索
|
||||||
search = AchievementDocument.search()
|
# 增加 size=10000 以支持返回更多结果(ES默认限制为10000,如需更多需分页)
|
||||||
|
search = AchievementDocument.search()[:10000]
|
||||||
search = search.query("multi_match", query=query, fields=['*'])
|
search = search.query("multi_match", query=query, fields=['*'])
|
||||||
response = search.execute()
|
response = search.execute()
|
||||||
|
|
||||||
@@ -173,7 +309,8 @@ def search_data(query):
|
|||||||
"_id": hit.meta.id,
|
"_id": hit.meta.id,
|
||||||
"writer_id": hit.writer_id,
|
"writer_id": hit.writer_id,
|
||||||
"data": hit.data,
|
"data": hit.data,
|
||||||
"image": hit.image
|
"image": hit.image,
|
||||||
|
"time": getattr(hit, "time", None),
|
||||||
})
|
})
|
||||||
|
|
||||||
return results
|
return results
|
||||||
@@ -184,7 +321,8 @@ def search_data(query):
|
|||||||
def search_all():
|
def search_all():
|
||||||
"""获取所有文档"""
|
"""获取所有文档"""
|
||||||
try:
|
try:
|
||||||
search = AchievementDocument.search()
|
# 增加 size=10000 以支持返回更多结果(ES默认限制为10000,如需更多需分页)
|
||||||
|
search = AchievementDocument.search()[:10000]
|
||||||
search = search.query("match_all")
|
search = search.query("match_all")
|
||||||
response = search.execute()
|
response = search.execute()
|
||||||
|
|
||||||
@@ -194,7 +332,8 @@ def search_all():
|
|||||||
"_id": hit.meta.id,
|
"_id": hit.meta.id,
|
||||||
"writer_id": hit.writer_id,
|
"writer_id": hit.writer_id,
|
||||||
"data": hit.data,
|
"data": hit.data,
|
||||||
"image": hit.image
|
"image": hit.image,
|
||||||
|
"time": getattr(hit, "time", None),
|
||||||
})
|
})
|
||||||
|
|
||||||
return results
|
return results
|
||||||
@@ -285,7 +424,8 @@ def search_by_any_field(keyword):
|
|||||||
list: 包含搜索结果的列表
|
list: 包含搜索结果的列表
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
search = AchievementDocument.search()
|
# 增加 size=10000 以支持返回更多结果(ES默认限制为10000,如需更多需分页)
|
||||||
|
search = AchievementDocument.search()[:10000]
|
||||||
|
|
||||||
# 使用multi_match查询,在所有字段中搜索
|
# 使用multi_match查询,在所有字段中搜索
|
||||||
search = search.query("multi_match",
|
search = search.query("multi_match",
|
||||||
@@ -301,7 +441,8 @@ def search_by_any_field(keyword):
|
|||||||
"_id": hit.meta.id,
|
"_id": hit.meta.id,
|
||||||
"writer_id": hit.writer_id,
|
"writer_id": hit.writer_id,
|
||||||
"data": hit.data,
|
"data": hit.data,
|
||||||
"image": hit.image
|
"image": hit.image,
|
||||||
|
"time": getattr(hit, "time", None),
|
||||||
})
|
})
|
||||||
|
|
||||||
return results
|
return results
|
||||||
@@ -355,9 +496,111 @@ def analytics_trend(gte: str = None, lte: str = None, interval: str = "day"):
|
|||||||
print(f"分析趋势失败: {str(e)}")
|
print(f"分析趋势失败: {str(e)}")
|
||||||
return []
|
return []
|
||||||
|
|
||||||
def analytics_types(gte: str = None, lte: str = None, size: int = 10):
|
def delete_key_globally(key_to_remove: str):
|
||||||
try:
|
try:
|
||||||
filters = _type_filters_from_list(limit=size)
|
# 1. 从 GlobalDocument (id='keys') 中彻底移除
|
||||||
|
try:
|
||||||
|
doc = GlobalDocument.get(id='keys')
|
||||||
|
current_keys = list(doc.keys_list or [])
|
||||||
|
# 使用列表推导式进行彻底删除,处理可能的重复项
|
||||||
|
new_keys = [k.strip().strip(';') for k in current_keys if k.strip().strip(';') != key_to_remove]
|
||||||
|
|
||||||
|
if len(new_keys) != len(current_keys):
|
||||||
|
doc.keys_list = new_keys
|
||||||
|
doc.save()
|
||||||
|
print(f"已从全局列表移除 Key: {key_to_remove}")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"从全局列表移除 Key 失败: {str(e)}")
|
||||||
|
|
||||||
|
# 2. 同步清理所有注册码中的该 key (无论是 keys 还是 manage_keys 字段)
|
||||||
|
from elasticsearch.helpers import scan
|
||||||
|
query = {
|
||||||
|
"query": {
|
||||||
|
"bool": {
|
||||||
|
"should": [
|
||||||
|
{"term": {"keys": key_to_remove}},
|
||||||
|
{"term": {"manage_keys": key_to_remove}}
|
||||||
|
],
|
||||||
|
"must": [
|
||||||
|
{"exists": {"field": "code"}} # 确保是注册码文档
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
updated_count = 0
|
||||||
|
for hit in scan(es, query=query, index=GLOBAL_INDEX_NAME):
|
||||||
|
try:
|
||||||
|
# 重新获取文档对象进行操作
|
||||||
|
doc = RegistrationCodeDocument.get(id=hit['_id'])
|
||||||
|
modified = False
|
||||||
|
|
||||||
|
if doc.keys:
|
||||||
|
old_keys = list(doc.keys)
|
||||||
|
new_ks = [k for k in old_keys if k != key_to_remove]
|
||||||
|
if len(new_ks) != len(old_keys):
|
||||||
|
doc.keys = new_ks
|
||||||
|
modified = True
|
||||||
|
|
||||||
|
if doc.manage_keys:
|
||||||
|
old_mks = list(doc.manage_keys)
|
||||||
|
new_mks = [k for k in old_mks if k != key_to_remove]
|
||||||
|
if len(new_mks) != len(old_mks):
|
||||||
|
doc.manage_keys = new_mks
|
||||||
|
modified = True
|
||||||
|
|
||||||
|
if modified:
|
||||||
|
doc.save()
|
||||||
|
updated_count += 1
|
||||||
|
except Exception as e:
|
||||||
|
print(f"同步清理注册码 {hit['_id']} 失败: {str(e)}")
|
||||||
|
|
||||||
|
# 3. 同步清理所有用户中的该 key (无论是 key 还是 manage_key 字段)
|
||||||
|
try:
|
||||||
|
user_query = {
|
||||||
|
"query": {
|
||||||
|
"bool": {
|
||||||
|
"should": [
|
||||||
|
{"term": {"key": key_to_remove}},
|
||||||
|
{"term": {"manage_key": key_to_remove}}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for user_hit in scan(es, query=user_query, index=USER_INDEX_NAME):
|
||||||
|
try:
|
||||||
|
user_doc = UserDocument.get(id=user_hit['_id'])
|
||||||
|
user_modified = False
|
||||||
|
|
||||||
|
if user_doc.key:
|
||||||
|
old_uk = list(user_doc.key)
|
||||||
|
new_uks = [k for k in old_uk if k != key_to_remove]
|
||||||
|
if len(new_uks) != len(old_uk):
|
||||||
|
user_doc.key = new_uks
|
||||||
|
user_modified = True
|
||||||
|
|
||||||
|
if user_doc.manage_key:
|
||||||
|
old_umk = list(user_doc.manage_key)
|
||||||
|
new_umks = [k for k in old_umk if k != key_to_remove]
|
||||||
|
if len(new_umks) != len(old_umk):
|
||||||
|
user_doc.manage_key = new_umks
|
||||||
|
user_modified = True
|
||||||
|
|
||||||
|
if user_modified:
|
||||||
|
user_doc.save()
|
||||||
|
except Exception as e:
|
||||||
|
print(f"同步清理用户 {user_hit['_id']} 失败: {str(e)}")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"扫描用户失败: {str(e)}")
|
||||||
|
|
||||||
|
return True, updated_count
|
||||||
|
except Exception as e:
|
||||||
|
print(f"全局删除 Key 失败: {str(e)}")
|
||||||
|
return False, 0
|
||||||
|
|
||||||
|
def analytics_types(gte: str = None, lte: str = None, limit: int = 12):
|
||||||
|
try:
|
||||||
|
filters = _type_filters_from_list(limit=limit)
|
||||||
body = {
|
body = {
|
||||||
"size": 0,
|
"size": 0,
|
||||||
"aggs": {
|
"aggs": {
|
||||||
@@ -455,6 +698,25 @@ def analytics_recent(limit: int = 10, gte: str = None, lte: str = None):
|
|||||||
pass
|
pass
|
||||||
return ""
|
return ""
|
||||||
|
|
||||||
|
def _extract_detail(s: str):
|
||||||
|
if not s:
|
||||||
|
return ""
|
||||||
|
try:
|
||||||
|
obj = json.loads(s)
|
||||||
|
if isinstance(obj, dict):
|
||||||
|
# 尝试获取常见的标题字段
|
||||||
|
for key in ["标题", "名称", "项目名称", "成果名称", "软件名称", "专利名称", "获奖名称", "证书名称", "姓名"]:
|
||||||
|
v = obj.get(key)
|
||||||
|
if isinstance(v, str) and v:
|
||||||
|
return v
|
||||||
|
# 如果没有找到常见标题,尝试获取第一个非"数据类型"的字符串值
|
||||||
|
for k, v in obj.items():
|
||||||
|
if k != "数据类型" and isinstance(v, str) and v and len(v) < 50:
|
||||||
|
return v
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return ""
|
||||||
|
|
||||||
search = AchievementDocument.search()
|
search = AchievementDocument.search()
|
||||||
body = {
|
body = {
|
||||||
"size": max(1, min(limit, 100)),
|
"size": max(1, min(limit, 100)),
|
||||||
@@ -485,11 +747,13 @@ def analytics_recent(limit: int = 10, gte: str = None, lte: str = None):
|
|||||||
except Exception:
|
except Exception:
|
||||||
uname = None
|
uname = None
|
||||||
tval = _extract_type(getattr(hit, 'data', ''))
|
tval = _extract_type(getattr(hit, 'data', ''))
|
||||||
|
dval = _extract_detail(getattr(hit, 'data', ''))
|
||||||
results.append({
|
results.append({
|
||||||
"_id": hit.meta.id,
|
"_id": hit.meta.id,
|
||||||
"writer_id": w,
|
"writer_id": w,
|
||||||
"username": uname or "",
|
"username": uname or "",
|
||||||
"type": tval or "",
|
"type": tval or "",
|
||||||
|
"detail": dval or "",
|
||||||
"time": getattr(hit, 'time', None)
|
"time": getattr(hit, 'time', None)
|
||||||
})
|
})
|
||||||
return results
|
return results
|
||||||
@@ -513,11 +777,24 @@ def write_user_data(user_data):
|
|||||||
perm_val = int(user_data.get('permission', 1))
|
perm_val = int(user_data.get('permission', 1))
|
||||||
except Exception:
|
except Exception:
|
||||||
perm_val = 1
|
perm_val = 1
|
||||||
|
pwd = str(user_data.get('password') or '').strip()
|
||||||
|
pwd_hash_b64 = user_data.get('password_hash')
|
||||||
|
pwd_salt_b64 = user_data.get('password_salt')
|
||||||
|
if pwd:
|
||||||
|
salt_b64, hash_b64 = hash_password_random_salt(pwd)
|
||||||
|
pwd_hash_b64, pwd_salt_b64 = hash_b64, salt_b64
|
||||||
user = UserDocument(
|
user = UserDocument(
|
||||||
user_id=user_data.get('user_id'),
|
user_id=user_data.get('user_id'),
|
||||||
username=user_data.get('username'),
|
username=user_data.get('username'),
|
||||||
password=user_data.get('password'),
|
password_hash=pwd_hash_b64,
|
||||||
permission=perm_val
|
password_salt=pwd_salt_b64,
|
||||||
|
permission=perm_val,
|
||||||
|
email=user_data.get('email'),
|
||||||
|
registration_code=(user_data.get('registration_code') or None),
|
||||||
|
can_manage_registration_codes=int(user_data.get('can_manage_registration_codes') or 0),
|
||||||
|
registration_manage_keys=list(user_data.get('registration_manage_keys') or []),
|
||||||
|
key=list(user_data.get('key') or []),
|
||||||
|
manage_key=list(user_data.get('manage_key') or []),
|
||||||
)
|
)
|
||||||
user.save()
|
user.save()
|
||||||
print(f"用户数据写入成功: {user_data.get('username')}")
|
print(f"用户数据写入成功: {user_data.get('username')}")
|
||||||
@@ -526,26 +803,6 @@ def write_user_data(user_data):
|
|||||||
print(f"用户数据写入失败: {str(e)}")
|
print(f"用户数据写入失败: {str(e)}")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def get_user_by_id(user_id):
|
|
||||||
try:
|
|
||||||
search = UserDocument.search()
|
|
||||||
search = search.query("term", user_id=user_id)
|
|
||||||
response = search.execute()
|
|
||||||
|
|
||||||
if response.hits:
|
|
||||||
hit = response.hits[0]
|
|
||||||
return {
|
|
||||||
"user_id": hit.user_id,
|
|
||||||
"username": hit.username,
|
|
||||||
"password": hit.password,
|
|
||||||
"permission": hit.permission
|
|
||||||
}
|
|
||||||
return None
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
print(f"获取用户数据失败: {str(e)}")
|
|
||||||
return None
|
|
||||||
|
|
||||||
def get_user_by_username(username):
|
def get_user_by_username(username):
|
||||||
"""
|
"""
|
||||||
根据用户名获取用户数据
|
根据用户名获取用户数据
|
||||||
@@ -566,7 +823,8 @@ def get_user_by_username(username):
|
|||||||
return {
|
return {
|
||||||
"user_id": hit.user_id,
|
"user_id": hit.user_id,
|
||||||
"username": hit.username,
|
"username": hit.username,
|
||||||
"password": hit.password,
|
"password_hash": getattr(hit, 'password_hash', None),
|
||||||
|
"password_salt": getattr(hit, 'password_salt', None),
|
||||||
"permission": int(hit.permission)
|
"permission": int(hit.permission)
|
||||||
}
|
}
|
||||||
return None
|
return None
|
||||||
@@ -577,18 +835,19 @@ def get_user_by_username(username):
|
|||||||
def get_all_users():
|
def get_all_users():
|
||||||
"""获取所有用户"""
|
"""获取所有用户"""
|
||||||
try:
|
try:
|
||||||
search = UserDocument.search()
|
|
||||||
search = search.query("match_all")
|
|
||||||
response = search.execute()
|
|
||||||
|
|
||||||
users = []
|
users = []
|
||||||
for hit in response:
|
for hit in UserDocument.search().query("match_all").scan():
|
||||||
users.append({
|
users.append({
|
||||||
"user_id": hit.user_id,
|
"user_id": hit.user_id,
|
||||||
"username": hit.username,
|
"username": hit.username,
|
||||||
"permission": int(hit.permission)
|
"permission": int(hit.permission),
|
||||||
|
"email": getattr(hit, 'email', None),
|
||||||
|
"registration_code": getattr(hit, 'registration_code', None),
|
||||||
|
"can_manage_registration_codes": int(getattr(hit, 'can_manage_registration_codes', 0) or 0),
|
||||||
|
"registration_manage_keys": list(getattr(hit, 'registration_manage_keys', []) or []),
|
||||||
|
"key": list(getattr(hit, 'key', []) or []),
|
||||||
|
"manage_key": list(getattr(hit, 'manage_key', []) or []),
|
||||||
})
|
})
|
||||||
|
|
||||||
return users
|
return users
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"获取所有用户失败: {str(e)}")
|
print(f"获取所有用户失败: {str(e)}")
|
||||||
@@ -605,6 +864,12 @@ def get_user_by_id(user_id):
|
|||||||
"user_id": hit.user_id,
|
"user_id": hit.user_id,
|
||||||
"username": hit.username,
|
"username": hit.username,
|
||||||
"permission": int(hit.permission),
|
"permission": int(hit.permission),
|
||||||
|
"email": getattr(hit, 'email', None),
|
||||||
|
"registration_code": getattr(hit, 'registration_code', None),
|
||||||
|
"can_manage_registration_codes": int(getattr(hit, 'can_manage_registration_codes', 0) or 0),
|
||||||
|
"registration_manage_keys": list(getattr(hit, 'registration_manage_keys', []) or []),
|
||||||
|
"key": list(getattr(hit, 'key', []) or []),
|
||||||
|
"manage_key": list(getattr(hit, 'manage_key', []) or []),
|
||||||
}
|
}
|
||||||
return None
|
return None
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -626,7 +891,7 @@ def delete_user_by_id(user_id):
|
|||||||
print(f"删除用户失败: {str(e)}")
|
print(f"删除用户失败: {str(e)}")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def update_user_by_id(user_id, username=None, permission=None, password=None):
|
def update_user_by_id(user_id, username=None, permission=None, password=None, key=None, manage_key=None, registration_code=None, can_manage_registration_codes=None, registration_manage_keys=None):
|
||||||
try:
|
try:
|
||||||
search = UserDocument.search()
|
search = UserDocument.search()
|
||||||
search = search.query("term", user_id=int(user_id))
|
search = search.query("term", user_id=int(user_id))
|
||||||
@@ -639,10 +904,123 @@ def update_user_by_id(user_id, username=None, permission=None, password=None):
|
|||||||
if permission is not None:
|
if permission is not None:
|
||||||
doc.permission = int(permission)
|
doc.permission = int(permission)
|
||||||
if password is not None:
|
if password is not None:
|
||||||
doc.password = password
|
salt_b64, hash_b64 = hash_password_random_salt(str(password))
|
||||||
|
doc.password_hash = hash_b64
|
||||||
|
doc.password_salt = salt_b64
|
||||||
|
if key is not None:
|
||||||
|
doc.key = list(key)
|
||||||
|
if manage_key is not None:
|
||||||
|
doc.manage_key = list(manage_key)
|
||||||
|
if registration_code is not None:
|
||||||
|
doc.registration_code = str(registration_code) if str(registration_code).strip() else None
|
||||||
|
if can_manage_registration_codes is not None:
|
||||||
|
try:
|
||||||
|
doc.can_manage_registration_codes = int(can_manage_registration_codes)
|
||||||
|
except Exception:
|
||||||
|
doc.can_manage_registration_codes = 0
|
||||||
|
if registration_manage_keys is not None:
|
||||||
|
doc.registration_manage_keys = list(registration_manage_keys)
|
||||||
doc.save()
|
doc.save()
|
||||||
return True
|
return True
|
||||||
return False
|
return False
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"更新用户失败: {str(e)}")
|
print(f"更新用户失败: {str(e)}")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
def _rc_request_now_iso():
|
||||||
|
return datetime.now(timezone.utc).isoformat()
|
||||||
|
|
||||||
|
def create_registration_code_manage_request(user_id: int, username: str, reason: str):
|
||||||
|
try:
|
||||||
|
rid = uuid.uuid4().hex
|
||||||
|
doc = {
|
||||||
|
"kind": "registration_code_manage_request",
|
||||||
|
"request_id": rid,
|
||||||
|
"user_id": int(user_id),
|
||||||
|
"username": str(username or ""),
|
||||||
|
"reason": str(reason or ""),
|
||||||
|
"status": "pending",
|
||||||
|
"created_at": _rc_request_now_iso(),
|
||||||
|
}
|
||||||
|
es.index(index=GLOBAL_INDEX_NAME, id=rid, body=doc)
|
||||||
|
return rid
|
||||||
|
except Exception as e:
|
||||||
|
print(f"创建注册码管理申请失败: {str(e)}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
def find_pending_registration_code_manage_request(user_id: int):
|
||||||
|
try:
|
||||||
|
body = {
|
||||||
|
"size": 1,
|
||||||
|
"query": {
|
||||||
|
"bool": {
|
||||||
|
"must": [
|
||||||
|
{"term": {"kind": "registration_code_manage_request"}},
|
||||||
|
{"term": {"user_id": int(user_id)}},
|
||||||
|
{"term": {"status": "pending"}},
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"sort": [{"created_at": {"order": "desc"}}],
|
||||||
|
}
|
||||||
|
resp = es.search(index=GLOBAL_INDEX_NAME, body=body)
|
||||||
|
hits = (resp.get("hits") or {}).get("hits") or []
|
||||||
|
if not hits:
|
||||||
|
return None
|
||||||
|
h = hits[0]
|
||||||
|
src = h.get("_source") or {}
|
||||||
|
src["_id"] = h.get("_id")
|
||||||
|
return src
|
||||||
|
except Exception as e:
|
||||||
|
print(f"查询注册码管理申请失败: {str(e)}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
def get_registration_code_manage_request(request_id: str):
|
||||||
|
try:
|
||||||
|
resp = es.get(index=GLOBAL_INDEX_NAME, id=str(request_id))
|
||||||
|
src = resp.get("_source") or {}
|
||||||
|
if (src.get("kind") or "") != "registration_code_manage_request":
|
||||||
|
return None
|
||||||
|
src["_id"] = resp.get("_id")
|
||||||
|
return src
|
||||||
|
except Exception:
|
||||||
|
return None
|
||||||
|
|
||||||
|
def list_registration_code_manage_requests(status: str = None, limit: int = 200):
|
||||||
|
try:
|
||||||
|
must = [{"term": {"kind": "registration_code_manage_request"}}]
|
||||||
|
if status:
|
||||||
|
must.append({"term": {"status": str(status)}})
|
||||||
|
body = {
|
||||||
|
"size": max(1, min(int(limit or 200), 2000)),
|
||||||
|
"query": {"bool": {"must": must}},
|
||||||
|
"sort": [{"created_at": {"order": "desc"}}],
|
||||||
|
}
|
||||||
|
resp = es.search(index=GLOBAL_INDEX_NAME, body=body)
|
||||||
|
hits = (resp.get("hits") or {}).get("hits") or []
|
||||||
|
out = []
|
||||||
|
for h in hits:
|
||||||
|
src = h.get("_source") or {}
|
||||||
|
src["_id"] = h.get("_id")
|
||||||
|
out.append(src)
|
||||||
|
return out
|
||||||
|
except Exception as e:
|
||||||
|
print(f"列出注册码管理申请失败: {str(e)}")
|
||||||
|
return []
|
||||||
|
|
||||||
|
def decide_registration_code_manage_request(request_id: str, status: str, reviewed_by: int, reviewer_note: str = None):
|
||||||
|
try:
|
||||||
|
sid = str(status or "").strip().lower()
|
||||||
|
if sid not in ("approved", "rejected"):
|
||||||
|
return False
|
||||||
|
doc = {
|
||||||
|
"status": sid,
|
||||||
|
"reviewed_at": _rc_request_now_iso(),
|
||||||
|
"reviewed_by": int(reviewed_by),
|
||||||
|
"reviewer_note": str(reviewer_note or ""),
|
||||||
|
}
|
||||||
|
es.update(index=GLOBAL_INDEX_NAME, id=str(request_id), body={"doc": doc})
|
||||||
|
return True
|
||||||
|
except Exception as e:
|
||||||
|
print(f"审批注册码管理申请失败: {str(e)}")
|
||||||
|
return False
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
INDEX_NAME = "wordsearch2666661"
|
INDEX_NAME = "wordsearch21"
|
||||||
USER_NAME = "users11111"
|
USER_NAME = "users16"
|
||||||
ACHIEVEMENT_INDEX_NAME = INDEX_NAME
|
ACHIEVEMENT_INDEX_NAME = INDEX_NAME
|
||||||
USER_INDEX_NAME = USER_NAME
|
USER_INDEX_NAME = USER_NAME
|
||||||
GLOBAL_INDEX_NAME = "global11111111211"
|
GLOBAL_INDEX_NAME = "global11121"
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
465
elastic/templates/elastic/registration_codes.html
Normal file
465
elastic/templates/elastic/registration_codes.html
Normal file
@@ -0,0 +1,465 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<title>注册码管理</title>
|
||||||
|
<style>
|
||||||
|
body { margin:0; font-family: system-ui,-apple-system, Segoe UI, Roboto, sans-serif; background:#fafafa; }
|
||||||
|
.sidebar { position:fixed; top:0; left:0; width:180px; height:100vh; background:#1e1e2e; color:#fff; padding:20px; box-shadow:2px 0 5px rgba(0,0,0,0.1); z-index:1000; display:flex; flex-direction:column; align-items:center; }
|
||||||
|
.sidebar h3 { margin:0; font-size:18px; color:#add8e6; text-align:center; margin-bottom: 20px; }
|
||||||
|
.navigation-links { width:100%; margin-top:60px; }
|
||||||
|
.sidebar a, .sidebar button { display:block; color:#8be9fd; text-decoration:none; margin:10px 0; font-size:16px; padding:15px; border-radius:4px; background:transparent; border:none; cursor:pointer; width:calc(100% - 40px); text-align:left; transition:all .2s ease; }
|
||||||
|
.sidebar a:hover, .sidebar button:hover { color:#ff79c6; background-color:rgba(139,233,253,.2); }
|
||||||
|
.main { margin-left:200px; padding:20px; color:#333; }
|
||||||
|
.card { background:#fff; border-radius:14px; box-shadow:0 10px 24px rgba(31,35,40,.08); padding:20px; margin-bottom:20px; }
|
||||||
|
.row { display:flex; gap:16px; }
|
||||||
|
.col { flex:1; }
|
||||||
|
label { display:block; margin-bottom:6px; font-weight:600; }
|
||||||
|
input[type=text], input[type=number], select { width:100%; padding:8px 12px; border:1px solid #d1d5db; border-radius:6px; box-sizing:border-box; }
|
||||||
|
.btn { padding:8px 12px; border:none; border-radius:8px; cursor:pointer; margin:0 4px; }
|
||||||
|
.btn-primary { background:#4f46e5; color:#fff; }
|
||||||
|
.btn-secondary { background:#64748b; color:#fff; }
|
||||||
|
.btn-danger { background:#ff4d4f; color:#fff; }
|
||||||
|
.btn-danger:hover { background:#ff7875 !important; }
|
||||||
|
.btn-primary:hover { background:#6366f1 !important; }
|
||||||
|
.btn-secondary:hover { background:#94a3b8 !important; }
|
||||||
|
.notice { padding:10px; border-radius:6px; margin-top:10px; display:none; }
|
||||||
|
.notice.success { background:#d4edda; color:#155724; border:1px solid #c3e6cb; }
|
||||||
|
.notice.error { background:#f8d7da; color:#721c24; border:1px solid #f5c6cb; }
|
||||||
|
.code-box { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; padding:12px; border:1px solid #e5e7eb; border-radius:8px; background:#fafafa; margin-top:10px; }
|
||||||
|
.overlay { position:fixed; inset:0; background:rgba(0,0,0,0.25); display:flex; align-items:center; justify-content:center; z-index:2000; }
|
||||||
|
.spinner { width:42px; height:42px; border:4px solid #cbd5e1; border-top-color:#4f46e5; border-radius:50%; animation:spin 0.8s linear infinite; }
|
||||||
|
@keyframes spin { to { transform: rotate(360deg); } }
|
||||||
|
.fade-in { animation: fadeUp 0.25s ease-out; }
|
||||||
|
@keyframes fadeUp { from { opacity:0; transform: translateY(6px); } to { opacity:1; transform: translateY(0); } }
|
||||||
|
table tr:hover { background-color:#f3f4f6; transition: background-color 0.2s ease; }
|
||||||
|
.btn { transition: transform 0.1s ease, box-shadow 0.2s ease; }
|
||||||
|
.btn:hover { transform: translateY(-1px); box-shadow:0 6px 16px rgba(31,35,40,0.12); }
|
||||||
|
</style>
|
||||||
|
{% csrf_token %}
|
||||||
|
<script>
|
||||||
|
const IS_ADMIN = {{ is_admin|yesno:"true,false" }};
|
||||||
|
const HAS_MANAGE_KEY = {{ has_manage_key|yesno:"true,false" }};
|
||||||
|
const CAN_MANAGE_REG = {{ can_manage_registration_codes|yesno:"true,false" }};
|
||||||
|
const MY_KEYS_RAW = JSON.parse('{{ my_keys_json|default:"[]"|escapejs }}');
|
||||||
|
const MY_KEYS_SET = new Set((Array.isArray(MY_KEYS_RAW) ? MY_KEYS_RAW : []).map(v => String(v || '').trim()).filter(Boolean));
|
||||||
|
const MY_MANAGE_KEYS_RAW = JSON.parse('{{ manage_keys_json|default:"[]"|escapejs }}');
|
||||||
|
const MY_MANAGE_KEYS_SET = new Set((Array.isArray(MY_MANAGE_KEYS_RAW) ? MY_MANAGE_KEYS_RAW : []).map(v => String(v || '').trim()).filter(Boolean));
|
||||||
|
const ALLOWED_MANAGE_KEYS_RAW = JSON.parse('{{ allowed_manage_keys_json|default:"[]"|escapejs }}');
|
||||||
|
const ALLOWED_MANAGE_KEYS_SET = new Set((Array.isArray(ALLOWED_MANAGE_KEYS_RAW) ? ALLOWED_MANAGE_KEYS_RAW : []).map(v => String(v || '').trim()).filter(Boolean));
|
||||||
|
|
||||||
|
function getCookie(name){const v=`; ${document.cookie}`;const p=v.split(`; ${name}=`);if(p.length===2) return p.pop().split(';').shift();}
|
||||||
|
async function loadKeys(){
|
||||||
|
const resp=await fetch('/elastic/registration-codes/keys/');
|
||||||
|
const data=await resp.json();
|
||||||
|
const opts=(data.data||[]);
|
||||||
|
const keySel=document.getElementById('keys');
|
||||||
|
const mkeySel=document.getElementById('manageKeys');
|
||||||
|
keySel.innerHTML=''; mkeySel.innerHTML='';
|
||||||
|
opts.forEach(k=>{
|
||||||
|
const o=document.createElement('option'); o.value=k; o.textContent=k; keySel.appendChild(o);
|
||||||
|
const o2=document.createElement('option'); o2.value=k; o2.textContent=k;
|
||||||
|
if ((!IS_ADMIN) && HAS_MANAGE_KEY) {
|
||||||
|
const v = String(k || '').trim();
|
||||||
|
if (v && !ALLOWED_MANAGE_KEYS_SET.has(v)) o2.disabled = true;
|
||||||
|
}
|
||||||
|
mkeySel.appendChild(o2);
|
||||||
|
});
|
||||||
|
if ((!IS_ADMIN) && HAS_MANAGE_KEY) {
|
||||||
|
Array.from(keySel.options).forEach(o => { if (MY_KEYS_SET.has(String(o.value || '').trim())) o.selected = true; });
|
||||||
|
Array.from(mkeySel.options).forEach(o => { o.selected = false; });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async function addKey(){
|
||||||
|
const keyName=(document.getElementById('newKey').value||'').trim();
|
||||||
|
if(!keyName) return;
|
||||||
|
const csrftoken=getCookie('csrftoken');
|
||||||
|
const resp=await fetch('/elastic/registration-codes/keys/add/',{method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json','X-CSRFToken':csrftoken||''},body:JSON.stringify({key:keyName})});
|
||||||
|
const data=await resp.json();
|
||||||
|
const msg=document.getElementById('msg');
|
||||||
|
if(resp.ok && data.status==='success'){
|
||||||
|
if ((!IS_ADMIN) && HAS_MANAGE_KEY) {
|
||||||
|
ALLOWED_MANAGE_KEYS_SET.add(keyName);
|
||||||
|
}
|
||||||
|
msg.textContent='新增key成功'; msg.className='notice success'; msg.style.display='block'; document.getElementById('newKey').value=''; loadKeys();
|
||||||
|
}
|
||||||
|
else{msg.textContent=data.message||'新增失败'; msg.className='notice error'; msg.style.display='block';}
|
||||||
|
}
|
||||||
|
async function deleteSelectedKey(){
|
||||||
|
const keySel = document.getElementById('keys');
|
||||||
|
const mkeySel = document.getElementById('manageKeys');
|
||||||
|
|
||||||
|
// 优先获取左侧选中的,如果没有则获取右侧选中的
|
||||||
|
const selectedKey = keySel.value || mkeySel.value;
|
||||||
|
|
||||||
|
if(!selectedKey){
|
||||||
|
alert('请先在下方列表中选择一个要删除的Key');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if ((!IS_ADMIN) && HAS_MANAGE_KEY) {
|
||||||
|
const v = String(selectedKey || '').trim();
|
||||||
|
if (!v || !ALLOWED_MANAGE_KEYS_SET.has(v)) {
|
||||||
|
const msg=document.getElementById('msg');
|
||||||
|
msg.textContent='只能删除自己新增的 key';
|
||||||
|
msg.className='notice error';
|
||||||
|
msg.style.display='block';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if(!confirm(`确定要全局删除Key \"${selectedKey}\" 吗?\n该操作将:\n1. 从全局可选Key列表中移除\n2. 从所有包含此Key的注册码中同步清除\n此操作不可恢复!`)) return;
|
||||||
|
|
||||||
|
const ov=document.getElementById('overlay'); ov.style.display='flex';
|
||||||
|
const csrftoken=getCookie('csrftoken');
|
||||||
|
const url = '/elastic/registration-codes/keys/remove/';
|
||||||
|
const resp=await fetch(url,{method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json','X-CSRFToken':csrftoken||''},body:JSON.stringify({key:selectedKey})});
|
||||||
|
const data=await resp.json();
|
||||||
|
const msg=document.getElementById('msg');
|
||||||
|
if(resp.ok && data.status==='success'){
|
||||||
|
if ((!IS_ADMIN) && HAS_MANAGE_KEY) {
|
||||||
|
ALLOWED_MANAGE_KEYS_SET.delete(String(selectedKey||'').trim());
|
||||||
|
}
|
||||||
|
msg.textContent = data.message || '删除成功';
|
||||||
|
msg.className='notice success';
|
||||||
|
msg.style.display='block';
|
||||||
|
loadKeys(); // 重新加载keys列表
|
||||||
|
loadCodes(); // 重新加载注册码列表
|
||||||
|
} else {
|
||||||
|
msg.textContent=data.message||'删除失败';
|
||||||
|
msg.className='notice error';
|
||||||
|
msg.style.display='block';
|
||||||
|
}
|
||||||
|
ov.style.display='none';
|
||||||
|
}
|
||||||
|
function selectedValues(sel){return Array.from(sel.selectedOptions).map(o=>o.value);}
|
||||||
|
function enableToggleSelect(sel){
|
||||||
|
sel.addEventListener('mousedown', function(e){
|
||||||
|
if(e.target && e.target.tagName==='OPTION'){
|
||||||
|
e.preventDefault();
|
||||||
|
const op=e.target;
|
||||||
|
if (op.disabled) return;
|
||||||
|
op.selected = !op.selected;
|
||||||
|
this.dispatchEvent(new Event('change',{bubbles:true}));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
function clearSelection(id){
|
||||||
|
const sel=document.getElementById(id);
|
||||||
|
Array.from(sel.options).forEach(o=>{ o.selected = false; });
|
||||||
|
}
|
||||||
|
async function generateCode(){
|
||||||
|
const ov=document.getElementById('overlay'); ov.style.display='flex';
|
||||||
|
const csrftoken=getCookie('csrftoken');
|
||||||
|
const keySel = document.getElementById('keys');
|
||||||
|
let keys=selectedValues(keySel);
|
||||||
|
if ((!IS_ADMIN) && HAS_MANAGE_KEY) {
|
||||||
|
const selected = new Set(keys.map(k=>String(k||'').trim()).filter(Boolean));
|
||||||
|
const missing = Array.from(MY_KEYS_SET).filter(k => !selected.has(k));
|
||||||
|
if (missing.length) {
|
||||||
|
const msg=document.getElementById('msg');
|
||||||
|
msg.textContent = `必须选择导师原有的 key:${missing.join('、')}`;
|
||||||
|
msg.className='notice error';
|
||||||
|
msg.style.display='block';
|
||||||
|
ov.style.display='none';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let manageKeys=selectedValues(document.getElementById('manageKeys'));
|
||||||
|
if ((!IS_ADMIN) && HAS_MANAGE_KEY) {
|
||||||
|
const hasForbidden = manageKeys.some(k => !ALLOWED_MANAGE_KEYS_SET.has(String(k || '').trim()));
|
||||||
|
if (hasForbidden) {
|
||||||
|
const msg=document.getElementById('msg');
|
||||||
|
msg.textContent='manage_key 只能选择本页新增的 key';
|
||||||
|
msg.className='notice error';
|
||||||
|
msg.style.display='block';
|
||||||
|
ov.style.display='none';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const mode=document.getElementById('expireMode').value;
|
||||||
|
let days=30; if(mode==='month') days=30; else if(mode==='fouryears') days=1460; else { const d=parseInt(document.getElementById('customDays').value||'30'); days=isNaN(d)?30:Math.max(1,d);}
|
||||||
|
const resp=await fetch('/elastic/registration-codes/generate/',{method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json','X-CSRFToken':csrftoken||''},body:JSON.stringify({keys,manage_keys:manageKeys,expires_in_days:days})});
|
||||||
|
const data=await resp.json();
|
||||||
|
const out=document.getElementById('codeOut');
|
||||||
|
const msg=document.getElementById('msg');
|
||||||
|
if(resp.ok && data.status==='success'){out.textContent=data.data.code; msg.textContent='生成成功'; msg.className='notice success'; msg.style.display='block';}
|
||||||
|
else{msg.textContent=data.message||'生成失败'; msg.className='notice error'; msg.style.display='block';}
|
||||||
|
ov.style.display='none';
|
||||||
|
}
|
||||||
|
async function loadCodes(){
|
||||||
|
const ov=document.getElementById('overlay'); ov.style.display='flex';
|
||||||
|
const resp=await fetch('/elastic/registration-codes/list/');
|
||||||
|
const data=await resp.json();
|
||||||
|
const tbody=document.getElementById('codesBody');
|
||||||
|
if(!tbody) return;
|
||||||
|
tbody.innerHTML='';
|
||||||
|
if(resp.ok && data.status==='success'){
|
||||||
|
(data.data||[]).forEach(it=>{
|
||||||
|
const tr=document.createElement('tr');
|
||||||
|
const status = it.active? '有效' : '失效';
|
||||||
|
const ka = Array.isArray(it.keys)? it.keys.join('、') : '';
|
||||||
|
const mka = Array.isArray(it.manage_keys)? it.manage_keys.join('、') : '';
|
||||||
|
tr.innerHTML = `<td>${it.code||''}</td><td>${ka}</td><td>${mka}</td><td>${formatDate(it.created_at)}</td><td>${formatDate(it.expires_at)}</td><td>${status}</td><td>${it.active? '<button class=\"btn btn-secondary\" data-code=\"'+it.code+'\">作废</button>':''}</td>`;
|
||||||
|
tbody.appendChild(tr);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
ov.style.display='none';
|
||||||
|
}
|
||||||
|
function formatDate(t){ if(!t) return ''; try{ const d = new Date(t); if(String(d)!='Invalid Date'){ const p=n=>String(n).padStart(2,'0'); return `${d.getFullYear()}-${p(d.getMonth()+1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;} }catch(e){} return ''; }
|
||||||
|
async function revokeCode(code){ const csrftoken=getCookie('csrftoken'); const resp=await fetch('/elastic/registration-codes/revoke/',{method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json','X-CSRFToken':csrftoken||''},body:JSON.stringify({code})}); const msg=document.getElementById('msg'); const data=await resp.json(); if(resp.ok && data.status==='success'){ msg.textContent='已作废'; msg.className='notice success'; msg.style.display='block'; loadCodes(); } else { msg.textContent=data.message||'作废失败'; msg.className='notice error'; msg.style.display='block'; } }
|
||||||
|
document.addEventListener('click',function(e){ const btn=e.target; if(btn && btn.matches('button[data-code]')){ revokeCode(btn.getAttribute('data-code')); }});
|
||||||
|
document.addEventListener('DOMContentLoaded',()=>{
|
||||||
|
loadKeys();
|
||||||
|
enableToggleSelect(document.getElementById('keys'));
|
||||||
|
enableToggleSelect(document.getElementById('manageKeys'));
|
||||||
|
loadCodes();
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="overlay" class="overlay" style="display:none"><div class="spinner"></div></div>
|
||||||
|
<div class="sidebar">
|
||||||
|
<h3>你好,{{ username|default:"访客" }}</h3>
|
||||||
|
<div class="navigation-links">
|
||||||
|
<a href="{% url 'main:home' %}">返回主页</a>
|
||||||
|
<a id="logoutBtn">退出登录</a>
|
||||||
|
<div id="logoutMsg"></div>
|
||||||
|
{% csrf_token %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="main">
|
||||||
|
<div class="card fade-in">
|
||||||
|
<h2>管理注册码</h2>
|
||||||
|
{% if is_admin or has_manage_key or can_manage_registration_codes %}
|
||||||
|
<div class="row">
|
||||||
|
<div class="col">
|
||||||
|
<label>管理 Key</label>
|
||||||
|
<div style="display:flex; gap:8px;">
|
||||||
|
<input id="newKey" type="text" placeholder="输入新的key进行新增,或在下方选择后删除" style="flex: 1;" />
|
||||||
|
<button class="btn btn-secondary" onclick="addKey()">新增 Key</button>
|
||||||
|
{% if is_admin or has_manage_key %}
|
||||||
|
<button class="btn btn-danger" onclick="deleteSelectedKey()">删除选中 Key</button>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
<div class="row" style="margin-top:12px;">
|
||||||
|
<div class="col">
|
||||||
|
<label>选择 keys</label>
|
||||||
|
<select id="keys" multiple size="10"></select>
|
||||||
|
<div style="margin-top:8px;"><button class="btn btn-secondary" style="width: 100%;" onclick="clearSelection('keys')">清空 keys 选择</button></div>
|
||||||
|
</div>
|
||||||
|
<div class="col">
|
||||||
|
<label>选择 manage_keys</label>
|
||||||
|
<select id="manageKeys" multiple size="10"></select>
|
||||||
|
<div style="margin-top:8px;">
|
||||||
|
<button class="btn btn-secondary" style="width: 100%;" onclick="clearSelection('manageKeys')">清空 manage_keys 选择</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="row" style="margin-top:12px;">
|
||||||
|
<div class="col">
|
||||||
|
<label>有效期</label>
|
||||||
|
<select id="expireMode">
|
||||||
|
<option value="month">一个月</option>
|
||||||
|
<option value="fouryears">四年</option>
|
||||||
|
<option value="custom">自定义天数</option>
|
||||||
|
</select>
|
||||||
|
<input id="customDays" type="number" min="1" placeholder="自定义天数" />
|
||||||
|
</div>
|
||||||
|
<div class="col" style="display:flex; align-items:flex-end;">
|
||||||
|
<button class="btn btn-primary" onclick="generateCode()">生成注册码</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div id="msg" class="notice"></div>
|
||||||
|
<div class="code-box" id="codeOut"></div>
|
||||||
|
<div class="row" style="margin-top:12px;">
|
||||||
|
<div class="col">
|
||||||
|
<div style="display:flex; justify-content:space-between; align-items:center;">
|
||||||
|
<h3>已生成的注册码</h3>
|
||||||
|
<div>
|
||||||
|
<button class="btn btn-secondary" onclick="loadCodes()">刷新列表</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<table style="width:100%; border-collapse:collapse; margin-top:10px;">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th style="text-align:left; border-bottom:1px solid #e5e7eb; padding:8px;">code</th>
|
||||||
|
<th style="text-align:left; border-bottom:1px solid #e5e7eb; padding:8px;">keys</th>
|
||||||
|
<th style="text-align:left; border-bottom:1px solid #e5e7eb; padding:8px;">manage_keys</th>
|
||||||
|
<th style="text-align:left; border-bottom:1px solid #e5e7eb; padding:8px;">创建时间</th>
|
||||||
|
<th style="text-align:left; border-bottom:1px solid #e5e7eb; padding:8px;">过期时间</th>
|
||||||
|
<th style="text-align:left; border-bottom:1px solid #e5e7eb; padding:8px;">状态</th>
|
||||||
|
<th style="text-align:left; border-bottom:1px solid #e5e7eb; padding:8px;">操作</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody id="codesBody"></tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<script>
|
||||||
|
// 获取CSRF令牌的函数
|
||||||
|
function getCookie(name) {
|
||||||
|
const value = `; ${document.cookie}`;
|
||||||
|
const parts = value.split(`; ${name}=`);
|
||||||
|
if (parts.length === 2) return parts.pop().split(';').shift();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 导航点击处理函数,提供备用URL
|
||||||
|
function handleNavClick(element, fallbackUrl) {
|
||||||
|
// 尝试使用Django模板生成的URL,如果失败则使用备用URL
|
||||||
|
try {
|
||||||
|
// 如果模板渲染正常,直接返回true让默认行为处理
|
||||||
|
return true;
|
||||||
|
} catch (e) {
|
||||||
|
// 如果模板渲染有问题,使用备用URL
|
||||||
|
window.location.href = fallbackUrl;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 修复用户管理链接跳转问题
|
||||||
|
document.addEventListener('DOMContentLoaded', function() {
|
||||||
|
// 为用户管理链接添加事件监听器,确保正确跳转
|
||||||
|
const userManagementLink = document.querySelector('a[href*="get_users"]');
|
||||||
|
if (userManagementLink) {
|
||||||
|
userManagementLink.addEventListener('click', function(e) {
|
||||||
|
// 阻止默认行为
|
||||||
|
e.preventDefault();
|
||||||
|
|
||||||
|
// 获取备用URL
|
||||||
|
const fallbackUrl = this.getAttribute('onclick').match(/'([^']+)'/g)[1].replace(/'/g, '');
|
||||||
|
|
||||||
|
// 直接跳转到用户管理页面
|
||||||
|
window.location.href = fallbackUrl;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// 登出功能
|
||||||
|
document.getElementById('logoutBtn').addEventListener('click', async () => {
|
||||||
|
const msg = document.getElementById('logoutMsg');
|
||||||
|
msg.textContent = '';
|
||||||
|
const csrftoken = getCookie('csrftoken');
|
||||||
|
try {
|
||||||
|
const resp = await fetch('/accounts/logout/', {
|
||||||
|
method: 'POST',
|
||||||
|
credentials: 'same-origin',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'X-CSRFToken': csrftoken || ''
|
||||||
|
},
|
||||||
|
body: JSON.stringify({})
|
||||||
|
});
|
||||||
|
const data = await resp.json();
|
||||||
|
if (!resp.ok || !data.ok) {
|
||||||
|
throw new Error('登出失败');
|
||||||
|
}
|
||||||
|
document.cookie = 'sessionid=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/';
|
||||||
|
document.cookie = 'csrftoken=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/';
|
||||||
|
window.location.href = data.redirect_url;
|
||||||
|
} catch (e) {
|
||||||
|
msg.textContent = e.message || '发生错误';
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
function fetchJSON(url){ return fetch(url, {credentials:'same-origin'}).then(r=>r.json()); }
|
||||||
|
function qs(params){ const u = new URLSearchParams(params); return u.toString(); }
|
||||||
|
|
||||||
|
const trendChart = echarts.init(document.getElementById('chartTrend'));
|
||||||
|
const typesChart = echarts.init(document.getElementById('chartTypes'));
|
||||||
|
const typesTrendChart = echarts.init(document.getElementById('chartTypesTrend'));
|
||||||
|
|
||||||
|
async function loadTrend(){
|
||||||
|
const url = '/elastic/analytics/trend/?' + qs({ from:'now-90d', to:'now', interval:'day' });
|
||||||
|
const res = await fetchJSON(url);
|
||||||
|
if(res.status!=='success') return;
|
||||||
|
const buckets = res.data || [];
|
||||||
|
const x = buckets.map(b=>b.key_as_string||'');
|
||||||
|
const y = buckets.map(b=>b.doc_count||0);
|
||||||
|
trendChart.setOption({
|
||||||
|
tooltip:{trigger:'axis'},
|
||||||
|
xAxis:{type:'category', data:x},
|
||||||
|
yAxis:{type:'value'},
|
||||||
|
series:[{ type:'line', areaStyle:{}, data:y, smooth:true, color:'#4f46e5' }]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadTypes(){
|
||||||
|
const url = '/elastic/analytics/types/?' + qs({ from:'now-30d', to:'now', size:10 });
|
||||||
|
const res = await fetchJSON(url);
|
||||||
|
if(res.status!=='success') return;
|
||||||
|
const buckets = res.data || [];
|
||||||
|
const data = buckets.map(b=>({ name: String(b.key||'未知'), value: b.doc_count||0 }));
|
||||||
|
typesChart.setOption({
|
||||||
|
tooltip:{trigger:'item'},
|
||||||
|
legend:{type:'scroll'},
|
||||||
|
series:[{ type:'pie', radius:['40%','70%'], data }]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadTypesTrend(){
|
||||||
|
const url = '/elastic/analytics/types_trend/?' + qs({ from:'now-180d', to:'now', interval:'week', size:6 });
|
||||||
|
const res = await fetchJSON(url);
|
||||||
|
if(res.status!=='success') return;
|
||||||
|
const rows = res.data || [];
|
||||||
|
const x = rows.map(r=>r.key_as_string||'');
|
||||||
|
const typeSet = new Set();
|
||||||
|
rows.forEach(r=> (r.types||[]).forEach(t=> typeSet.add(String(t.key||'未知'))));
|
||||||
|
const types = Array.from(typeSet);
|
||||||
|
const series = types.map(tp=>({
|
||||||
|
name: tp,
|
||||||
|
type:'line',
|
||||||
|
smooth:true,
|
||||||
|
data: rows.map(r=>{
|
||||||
|
const b = (r.types||[]).find(x=>String(x.key||'')===tp);
|
||||||
|
return b? b.doc_count||0 : 0;
|
||||||
|
})
|
||||||
|
}));
|
||||||
|
typesTrendChart.setOption({
|
||||||
|
tooltip:{trigger:'axis'},
|
||||||
|
legend:{type:'scroll'},
|
||||||
|
xAxis:{type:'category', data:x},
|
||||||
|
yAxis:{type:'value'},
|
||||||
|
series
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatTime(t){
|
||||||
|
try{
|
||||||
|
const d = new Date(t);
|
||||||
|
if(String(d) !== 'Invalid Date'){
|
||||||
|
const pad = n=> String(n).padStart(2,'0');
|
||||||
|
return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
||||||
|
}
|
||||||
|
}catch(e){}
|
||||||
|
return t||'';
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadRecent(){
|
||||||
|
const listEl = document.getElementById('recentList');
|
||||||
|
const url = '/elastic/analytics/recent/?' + qs({ from:'now-7d', to:'now', limit:10 });
|
||||||
|
const res = await fetchJSON(url);
|
||||||
|
if(res.status!=='success') return;
|
||||||
|
const items = res.data || [];
|
||||||
|
listEl.innerHTML = '';
|
||||||
|
items.forEach(it=>{
|
||||||
|
const li = document.createElement('li');
|
||||||
|
const t = formatTime(it.time);
|
||||||
|
const u = it.username || '';
|
||||||
|
const ty = it.type || '未知';
|
||||||
|
li.textContent = `${t},${u},${ty}`;
|
||||||
|
listEl.appendChild(li);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
loadTrend();
|
||||||
|
loadTypes();
|
||||||
|
loadTypesTrend();
|
||||||
|
loadRecent();
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -4,282 +4,87 @@
|
|||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<title>图片上传与识别</title>
|
<title>图片上传与识别</title>
|
||||||
<style>
|
<style>
|
||||||
body {
|
body {margin: 0;font-family: system-ui, -apple-system, Segoe UI, Roboto, sans-serif;background: #fafafa;}
|
||||||
margin: 0;
|
/* 导航栏样式 */
|
||||||
font-family: system-ui, -apple-system, Segoe UI, Roboto, sans-serif;
|
.sidebar {position: fixed;top: 0;left: 0;width: 180px;height: 100vh;background: #1e1e2e;color: white;padding: 20px;box-shadow: 2px 0 5px rgba(0,0,0,0.1);z-index: 1000;display: flex;
|
||||||
background: #fafafa;
|
flex-direction: column;align-items: center;}
|
||||||
}
|
.user-id {text-align: center;margin-bottom: 0px;}
|
||||||
|
.sidebar h3 {margin-top: 0;font-size: 18px;color: #add8e6;text-align: center; margin-bottom: 20px;}
|
||||||
/* 导航栏样式 - 保持原有样式 */
|
.navigation-links {width: 100%;margin-top: 60px;}
|
||||||
.sidebar {
|
|
||||||
position: fixed;
|
|
||||||
top: 0;
|
|
||||||
left: 0;
|
|
||||||
width: 180px;
|
|
||||||
height: 100vh;
|
|
||||||
background: #1e1e2e;
|
|
||||||
color: white;
|
|
||||||
padding: 20px;
|
|
||||||
box-shadow: 2px 0 5px rgba(0,0,0,0.1);
|
|
||||||
z-index: 1000;
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
align-items: center;
|
|
||||||
}
|
|
||||||
|
|
||||||
.user-id {
|
|
||||||
text-align: center;
|
|
||||||
margin-bottom: 0px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.sidebar h3 {
|
|
||||||
margin-top: 0;
|
|
||||||
font-size: 18px;
|
|
||||||
color: #add8e6;
|
|
||||||
text-align: center;
|
|
||||||
margin-bottom: 20px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.navigation-links {
|
|
||||||
width: 100%;
|
|
||||||
margin-top: 60px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.sidebar a,
|
.sidebar a,
|
||||||
.sidebar button {
|
.sidebar button {display: block;color: #8be9fd;text-decoration: none;margin: 10px 0;font-size: 16px;padding: 15px;border-radius: 4px;background: transparent;
|
||||||
display: block;
|
border: none;cursor: pointer; width: calc(100% - 40px);text-align: left;transition: all 0.2s ease;}
|
||||||
color: #8be9fd;
|
|
||||||
text-decoration: none;
|
|
||||||
margin: 10px 0;
|
|
||||||
font-size: 16px;
|
|
||||||
padding: 15px;
|
|
||||||
border-radius: 4px;
|
|
||||||
background: transparent;
|
|
||||||
border: none;
|
|
||||||
cursor: pointer;
|
|
||||||
width: calc(100% - 40px);
|
|
||||||
text-align: left;
|
|
||||||
transition: all 0.2s ease;
|
|
||||||
}
|
|
||||||
|
|
||||||
.sidebar a:hover,
|
.sidebar a:hover,
|
||||||
.sidebar button:hover {
|
.sidebar button:hover {color: #ff79c6;background-color: rgba(139, 233, 253, 0.2);}
|
||||||
color: #ff79c6;
|
|
||||||
background-color: rgba(139, 233, 253, 0.2);
|
|
||||||
}
|
|
||||||
|
|
||||||
/* 主内容区 - 改进后的样式 */
|
/* 主内容区 - 改进后的样式 */
|
||||||
.main-content {
|
.main-content {margin-left: 200px;padding: 20px;color: #333;}
|
||||||
margin-left: 200px;
|
.container { max-width: 1200px;margin: 0 auto;background: #fff;border-radius: 14px;box-shadow: 0 10px 24px rgba(31,35,40,0.08);
|
||||||
padding: 20px;
|
padding: 24px;}
|
||||||
color: #333;
|
.header {display: flex;align-items: center;justify-content: space-between;margin-bottom: 12px;}
|
||||||
}
|
.header h2 {margin: 0; color: #1e293b;}
|
||||||
|
.header p {margin: 5px 0 0 0;color: #64748b;font-size: 14px;}
|
||||||
.container {
|
.upload-section { background: #f8fafc; border: 2px dashed #cbd5e1; border-radius: 12px;padding: 32px; text-align: center;transition: all 0.3s ease;
|
||||||
max-width: 1200px;
|
margin-bottom: 24px;}
|
||||||
margin: 0 auto;
|
.upload-section:hover {border-color: #4f46e5; background: #f1f5f9; }
|
||||||
background: #fff;
|
.upload-section.drag-over {border-color: #4f46e5; background: #e0e7ff; }
|
||||||
border-radius: 14px;
|
.upload-section input[type="file"] {margin: 15px 0;}
|
||||||
box-shadow: 0 10px 24px rgba(31,35,40,0.08);
|
.btn {padding: 10px 16px;border: none;border-radius: 8px;cursor: pointer;margin: 0 4px;font-size: 14px;transition: all 0.2s ease; }
|
||||||
padding: 24px;
|
.btn-primary { background: #4f46e5; color: #fff; }
|
||||||
}
|
.btn-primary:hover { background: #4338ca;}
|
||||||
|
.btn-secondary {background: #e2e8f0;color: #334155; }
|
||||||
.header {
|
.btn-secondary:hover { background: #cbd5e1;}
|
||||||
display: flex;
|
.btn-danger { background: #ef4444;color: #fff;}
|
||||||
align-items: center;
|
.btn-danger:hover { background: #dc2626;}
|
||||||
justify-content: space-between;
|
.preview-container {display: flex; gap: 24px; margin: 24px 0;}
|
||||||
margin-bottom: 12px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.header h2 {
|
|
||||||
margin: 0;
|
|
||||||
color: #1e293b;
|
|
||||||
}
|
|
||||||
|
|
||||||
.header p {
|
|
||||||
margin: 5px 0 0 0;
|
|
||||||
color: #64748b;
|
|
||||||
font-size: 14px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.upload-section {
|
|
||||||
background: #f8fafc;
|
|
||||||
border: 2px dashed #cbd5e1;
|
|
||||||
border-radius: 12px;
|
|
||||||
padding: 32px;
|
|
||||||
text-align: center;
|
|
||||||
transition: all 0.3s ease;
|
|
||||||
margin-bottom: 24px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.upload-section:hover {
|
|
||||||
border-color: #4f46e5;
|
|
||||||
background: #f1f5f9;
|
|
||||||
}
|
|
||||||
|
|
||||||
.upload-section.drag-over {
|
|
||||||
border-color: #4f46e5;
|
|
||||||
background: #e0e7ff;
|
|
||||||
}
|
|
||||||
|
|
||||||
.upload-section input[type="file"] {
|
|
||||||
margin: 15px 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.btn {
|
|
||||||
padding: 10px 16px;
|
|
||||||
border: none;
|
|
||||||
border-radius: 8px;
|
|
||||||
cursor: pointer;
|
|
||||||
margin: 0 4px;
|
|
||||||
font-size: 14px;
|
|
||||||
transition: all 0.2s ease;
|
|
||||||
}
|
|
||||||
|
|
||||||
.btn-primary {
|
|
||||||
background: #4f46e5;
|
|
||||||
color: #fff;
|
|
||||||
}
|
|
||||||
|
|
||||||
.btn-primary:hover {
|
|
||||||
background: #4338ca;
|
|
||||||
}
|
|
||||||
|
|
||||||
.btn-secondary {
|
|
||||||
background: #e2e8f0;
|
|
||||||
color: #334155;
|
|
||||||
}
|
|
||||||
|
|
||||||
.btn-secondary:hover {
|
|
||||||
background: #cbd5e1;
|
|
||||||
}
|
|
||||||
|
|
||||||
.btn-danger {
|
|
||||||
background: #ef4444;
|
|
||||||
color: #fff;
|
|
||||||
}
|
|
||||||
|
|
||||||
.btn-danger:hover {
|
|
||||||
background: #dc2626;
|
|
||||||
}
|
|
||||||
|
|
||||||
.preview-container {
|
|
||||||
display: flex;
|
|
||||||
gap: 24px;
|
|
||||||
margin: 24px 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
@media (max-width: 768px) {
|
@media (max-width: 768px) {
|
||||||
.preview-container {
|
.preview-container {flex-direction: column;}
|
||||||
flex-direction: column;
|
|
||||||
}
|
}
|
||||||
|
.preview-box {flex: 1; text-align: center; }
|
||||||
|
.preview-box h3 {margin-top: 0;color: #334155; }
|
||||||
|
.preview-box img { max-width: 100%;max-height: 300px;border: 1px solid #e2e8f0;border-radius: 8px;object-fit: contain;}
|
||||||
|
.preview-list {display: grid;grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));gap: 12px; margin-top: 20px;}
|
||||||
|
.preview-item {position: relative;}
|
||||||
|
.preview-item img {width: 100%;max-height: 220px;border: 1px solid #e2e8f0;border-radius: 8px;object-fit: contain;}
|
||||||
|
.preview-remove {position: absolute;top: 6px;right: 6px;border: none;border-radius: 999px;background: rgba(15,23,42,0.8);color: #fff;width: 24px;height: 24px;cursor: pointer;display: flex;align-items: center;justify-content: center;font-size: 14px;line-height: 1;}
|
||||||
|
.result-box {flex: 1;}
|
||||||
|
.result-box h3 { margin-top: 0; color: #334155;}
|
||||||
|
.form-controls { display: flex;gap: 8px;margin-bottom: 12px;flex-wrap: wrap;}
|
||||||
|
.pending-item { background: #fff; border: 1px solid #e2e8f0; border-radius: 12px; padding: 20px; margin-bottom: 24px; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1); }
|
||||||
|
.pending-item-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px; border-bottom: 1px solid #f1f5f9; padding-bottom: 12px; }
|
||||||
|
.pending-item-title { font-weight: 600; color: #1e293b; font-size: 16px; }
|
||||||
|
.pending-item-body { display: flex; gap: 20px; }
|
||||||
|
.pending-item-preview { flex: 0 0 240px; }
|
||||||
|
.pending-item-preview img { width: 100%; border-radius: 8px; border: 1px solid #f1f5f9; }
|
||||||
|
.pending-item-edit { flex: 1; }
|
||||||
|
.pending-item-footer { margin-top: 16px; text-align: right; }
|
||||||
|
@media (max-width: 992px) {
|
||||||
|
.pending-item-body { flex-direction: column; }
|
||||||
|
.pending-item-preview { flex: 0 0 auto; }
|
||||||
}
|
}
|
||||||
|
.form-row {display: grid;grid-template-columns: 1fr 1fr auto;gap: 8px; margin-bottom: 6px; align-items: center;}
|
||||||
.preview-box {
|
.form-row input {padding: 8px;border: 1px solid #cbd5e1;border-radius: 4px; width: 100%; box-sizing: border-box;}
|
||||||
flex: 1;
|
.kv-form-container {border: 1px solid #e2e8f0; border-radius: 8px; padding: 12px; max-height: 400px; overflow: auto; margin-bottom: 12px; background: #f8fafc;}
|
||||||
text-align: center;
|
.form-header { display: grid; grid-template-columns: 1fr 1fr auto; gap: 8px; margin-bottom: 8px; padding: 0 4px; font-weight: 600; color: #475569; font-size: 14px;}
|
||||||
}
|
.result-textarea { width: 100%; min-height: 120px; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 13px; padding: 10px; border: 1px solid #e2e8f0; border-radius: 8px; resize: vertical; box-sizing: border-box; }
|
||||||
|
.status-message { padding: 10px; margin: 10px 0; border-radius: 6px; display: none; }
|
||||||
.preview-box h3 {
|
.status-message.success { background-color: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
|
||||||
margin-top: 0;
|
.status-message.error { background-color: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
|
||||||
color: #334155;
|
.action-buttons { margin-top: 16px; display: flex; gap: 8px; flex-wrap: wrap; }
|
||||||
}
|
.progress {position: relative; height: 12px; background: #e2e8f0; border-radius: 8px; overflow: hidden;}
|
||||||
|
.progress-bar {height: 100%; width: 0; background: linear-gradient(90deg, #4f46e5 0%, #60a5fa 100%); transition: width .2s ease;}
|
||||||
.preview-box img {
|
.progress-wrap {display:none; margin-top: 8px;}
|
||||||
max-width: 100%;
|
.progress-text {margin-top: 6px; font-size: 12px; color: #334155;}
|
||||||
max-height: 300px;
|
|
||||||
border: 1px solid #e2e8f0;
|
|
||||||
border-radius: 8px;
|
|
||||||
object-fit: contain;
|
|
||||||
}
|
|
||||||
|
|
||||||
.result-box {
|
|
||||||
flex: 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
.result-box h3 {
|
|
||||||
margin-top: 0;
|
|
||||||
color: #334155;
|
|
||||||
}
|
|
||||||
|
|
||||||
.form-controls {
|
|
||||||
display: flex;
|
|
||||||
gap: 8px;
|
|
||||||
margin-bottom: 12px;
|
|
||||||
flex-wrap: wrap;
|
|
||||||
}
|
|
||||||
|
|
||||||
#kvForm {
|
|
||||||
border: 1px solid #e2e8f0;
|
|
||||||
border-radius: 8px;
|
|
||||||
padding: 12px;
|
|
||||||
max-height: 300px;
|
|
||||||
overflow: auto;
|
|
||||||
margin-bottom: 12px;
|
|
||||||
background: white;
|
|
||||||
}
|
|
||||||
|
|
||||||
.form-row {
|
|
||||||
display: grid;
|
|
||||||
grid-template-columns: 1fr 1fr auto;
|
|
||||||
gap: 8px;
|
|
||||||
margin-bottom: 6px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.form-row input {
|
|
||||||
padding: 8px;
|
|
||||||
border: 1px solid #cbd5e1;
|
|
||||||
border-radius: 4px;
|
|
||||||
}
|
|
||||||
|
|
||||||
#resultBox {
|
|
||||||
width: 100%;
|
|
||||||
min-height: 200px;
|
|
||||||
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
|
||||||
font-size: 14px;
|
|
||||||
padding: 12px;
|
|
||||||
border: 1px solid #e2e8f0;
|
|
||||||
border-radius: 8px;
|
|
||||||
resize: vertical;
|
|
||||||
box-sizing: border-box;
|
|
||||||
}
|
|
||||||
|
|
||||||
.status-message {
|
|
||||||
padding: 10px;
|
|
||||||
margin: 10px 0;
|
|
||||||
border-radius: 6px;
|
|
||||||
display: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
.status-message.success {
|
|
||||||
background-color: #d4edda;
|
|
||||||
color: #155724;
|
|
||||||
border: 1px solid #c3e6cb;
|
|
||||||
}
|
|
||||||
|
|
||||||
.status-message.error {
|
|
||||||
background-color: #f8d7da;
|
|
||||||
color: #721c24;
|
|
||||||
border: 1px solid #f5c6cb;
|
|
||||||
}
|
|
||||||
|
|
||||||
.action-buttons {
|
|
||||||
margin-top: 16px;
|
|
||||||
display: flex;
|
|
||||||
gap: 8px;
|
|
||||||
flex-wrap: wrap;
|
|
||||||
}
|
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<!-- 左侧固定栏目 -->
|
<!-- 左侧固定栏目 -->
|
||||||
<div class="sidebar">
|
<div class="sidebar">
|
||||||
<div class="user-id">
|
<div class="user-id">
|
||||||
<h3>用户ID:{{ user_id }}</h3>
|
<h3>你好,{{ username|default:"访客" }}</h3>
|
||||||
</div>
|
</div>
|
||||||
<div class="navigation-links">
|
<div class="navigation-links">
|
||||||
<a href="{% url 'main:home' %}">主页</a>
|
<a href="{% url 'main:home' %}">返回主页</a>
|
||||||
<button id="logoutBtn">退出登录</button>
|
<a id="logoutBtn">退出登录</a>
|
||||||
<div id="logoutMsg"></div>
|
<div id="logoutMsg"></div>
|
||||||
{% csrf_token %}
|
{% csrf_token %}
|
||||||
</div>
|
</div>
|
||||||
@@ -290,37 +95,36 @@
|
|||||||
<div class="container">
|
<div class="container">
|
||||||
<div class="header">
|
<div class="header">
|
||||||
<div>
|
<div>
|
||||||
<h2>图片上传与识别</h2>
|
<h2>图片与PDF上传识别</h2>
|
||||||
<p>选择图片后上传,服务端调用大模型解析为可编辑的 JSON,再确认入库。</p>
|
<p>选择图片或PDF文件后上传,服务端调用大模型解析为可编辑的 JSON,再确认入库。</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="upload-section" id="dropArea">
|
<div class="upload-section" id="dropArea">
|
||||||
<h3>上传图片</h3>
|
<h3>上传文件</h3>
|
||||||
<p>点击下方按钮选择图片,或拖拽图片到此区域</p>
|
<p>点击下方按钮选择图片或PDF文件,或拖拽文件到此区域</p>
|
||||||
|
<p style="margin: 8px 0 0; font-size: 13px; color: #64748b;">单次最多上传 {{ max_single_upload_count|default:"3" }} 个文件。</p>
|
||||||
<form id="uploadForm" enctype="multipart/form-data">
|
<form id="uploadForm" enctype="multipart/form-data">
|
||||||
{% csrf_token %}
|
{% csrf_token %}
|
||||||
<input type="file" id="fileInput" name="file" accept="image/*" required />
|
<input type="file" id="fileInput" name="file" accept="image/*,.pdf" multiple />
|
||||||
|
<span id="fileHint" class="muted"></span>
|
||||||
|
<div id="previewList" class="preview-list"></div>
|
||||||
<br>
|
<br>
|
||||||
<button type="submit" class="btn btn-primary">上传并识别</button>
|
<button type="submit" class="btn btn-primary">上传并识别</button>
|
||||||
</form>
|
</form>
|
||||||
<div class="status-message" id="uploadMsg"></div>
|
<div class="status-message" id="uploadMsg"></div>
|
||||||
|
<div class="progress-wrap" id="progressWrap">
|
||||||
|
<div class="progress"><div class="progress-bar" id="progressBar"></div></div>
|
||||||
|
<div class="progress-text" id="progressText"></div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="preview-container">
|
<div class="preview-container">
|
||||||
<div class="preview-box">
|
|
||||||
<h3>图片预览</h3>
|
|
||||||
<img id="preview" alt="预览" />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="result-box">
|
<div class="result-box">
|
||||||
<h3>识别结果(可编辑)</h3>
|
<h3>待处理文件列表</h3>
|
||||||
<div class="form-controls">
|
<div id="pendingItems" class="pending-list">
|
||||||
<button id="addFieldBtn" class="btn btn-secondary" type="button">添加字段</button>
|
<!-- 这里将动态生成每个文件的预览和编辑区域 -->
|
||||||
<button id="syncFromTextBtn" class="btn btn-secondary" type="button">从文本区刷新表单</button>
|
|
||||||
</div>
|
</div>
|
||||||
<div id="kvForm"></div>
|
|
||||||
<textarea id="resultBox" placeholder="识别结果JSON将显示在这里"></textarea>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -341,18 +145,60 @@ function getCookie(name) {
|
|||||||
|
|
||||||
const uploadForm = document.getElementById('uploadForm');
|
const uploadForm = document.getElementById('uploadForm');
|
||||||
const fileInput = document.getElementById('fileInput');
|
const fileInput = document.getElementById('fileInput');
|
||||||
const preview = document.getElementById('preview');
|
const fileHint = document.getElementById('fileHint');
|
||||||
const resultBox = document.getElementById('resultBox');
|
const previewList = document.getElementById('previewList');
|
||||||
|
const pendingItems = document.getElementById('pendingItems');
|
||||||
const uploadMsg = document.getElementById('uploadMsg');
|
const uploadMsg = document.getElementById('uploadMsg');
|
||||||
const confirmBtn = document.getElementById('confirmBtn');
|
const confirmBtn = document.getElementById('confirmBtn');
|
||||||
const clearBtn = document.getElementById('clearBtn');
|
const clearBtn = document.getElementById('clearBtn');
|
||||||
const confirmMsg = document.getElementById('confirmMsg');
|
const confirmMsg = document.getElementById('confirmMsg');
|
||||||
const kvForm = document.getElementById('kvForm');
|
|
||||||
const addFieldBtn = document.getElementById('addFieldBtn');
|
|
||||||
const syncFromTextBtn = document.getElementById('syncFromTextBtn');
|
|
||||||
const dropArea = document.getElementById('dropArea');
|
const dropArea = document.getElementById('dropArea');
|
||||||
|
const progressWrap = document.getElementById('progressWrap');
|
||||||
|
const progressBar = document.getElementById('progressBar');
|
||||||
|
const progressText = document.getElementById('progressText');
|
||||||
|
const MAX_SINGLE_UPLOAD_COUNT = Number('{{ max_single_upload_count|default:"3" }}');
|
||||||
|
|
||||||
let currentImageRel = '';
|
let currentItems = []; // 存储当前待处理的所有文件结果
|
||||||
|
let selectedFiles = [];
|
||||||
|
|
||||||
|
function setProgress(p, text){
|
||||||
|
const v = Math.max(0, Math.min(100, Math.round(p||0)));
|
||||||
|
progressBar.style.width = v + '%';
|
||||||
|
progressText.textContent = (text||'') + (text? ' ' : '') + v + '%';
|
||||||
|
}
|
||||||
|
function showProgress(){
|
||||||
|
progressWrap.style.display = 'block';
|
||||||
|
}
|
||||||
|
function hideProgress(){
|
||||||
|
progressWrap.style.display = 'none';
|
||||||
|
setProgress(0, '');
|
||||||
|
}
|
||||||
|
|
||||||
|
async function convertToJpeg(file){
|
||||||
|
const url = URL.createObjectURL(file);
|
||||||
|
let img;
|
||||||
|
try{
|
||||||
|
const blob = await fetch(url).then(r=>r.blob());
|
||||||
|
img = await createImageBitmap(blob);
|
||||||
|
}catch(e){
|
||||||
|
img = await new Promise((resolve,reject)=>{const i=new Image();i.onload=()=>resolve(i);i.onerror=reject;i.src=url;});
|
||||||
|
}
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
const maxDim = 2000;
|
||||||
|
const w = img.width;
|
||||||
|
const h = img.height;
|
||||||
|
const scale = Math.min(1, maxDim/Math.max(w,h));
|
||||||
|
const nw = Math.round(w*scale);
|
||||||
|
const nh = Math.round(h*scale);
|
||||||
|
const canvas = document.createElement('canvas');
|
||||||
|
canvas.width = nw;
|
||||||
|
canvas.height = nh;
|
||||||
|
const ctx = canvas.getContext('2d');
|
||||||
|
ctx.drawImage(img, 0, 0, nw, nh);
|
||||||
|
const blob = await new Promise(resolve=>canvas.toBlob(resolve,'image/jpeg',0.82));
|
||||||
|
const name = (file.name||'image').replace(/\.[^/.]+$/, '') + '.jpg';
|
||||||
|
return new File([blob], name, {type:'image/jpeg'});
|
||||||
|
}
|
||||||
|
|
||||||
// 拖拽上传功能
|
// 拖拽上传功能
|
||||||
['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
|
['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
|
||||||
@@ -386,25 +232,85 @@ function handleDrop(e) {
|
|||||||
const dt = e.dataTransfer;
|
const dt = e.dataTransfer;
|
||||||
const files = dt.files;
|
const files = dt.files;
|
||||||
if (files.length) {
|
if (files.length) {
|
||||||
fileInput.files = files;
|
addFiles(files);
|
||||||
const event = new Event('change', { bubbles: true });
|
|
||||||
fileInput.dispatchEvent(event);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 文件选择后预览
|
function setPreviewList(urls) {
|
||||||
fileInput.addEventListener('change', function(e) {
|
previewList.innerHTML = '';
|
||||||
const file = e.target.files[0];
|
(urls || []).forEach((url, index) => {
|
||||||
if (file && file.type.startsWith('image/')) {
|
if (!url) return;
|
||||||
const reader = new FileReader();
|
const item = document.createElement('div');
|
||||||
reader.onload = function(e) {
|
item.className = 'preview-item';
|
||||||
preview.src = e.target.result;
|
item.dataset.index = String(index);
|
||||||
};
|
const img = document.createElement('img');
|
||||||
reader.readAsDataURL(file);
|
img.src = url;
|
||||||
|
img.alt = '预览';
|
||||||
|
const btn = document.createElement('button');
|
||||||
|
btn.type = 'button';
|
||||||
|
btn.className = 'preview-remove';
|
||||||
|
btn.textContent = '×';
|
||||||
|
btn.onclick = () => {
|
||||||
|
const idx = Number(item.dataset.index);
|
||||||
|
if (!Number.isNaN(idx)) {
|
||||||
|
selectedFiles.splice(idx, 1);
|
||||||
|
const urls = selectedFiles.map(f => {
|
||||||
|
if (f.name.toLowerCase().endsWith('.pdf')) {
|
||||||
|
return 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI0OCIgaGVpZ2h0PSI0OCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9IiNlZjQ0NDQiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIj48cGF0aCBkPSJNMTQgMmgyYTIgMiAwIDAgMSAyIDJ2MTZhMiAyIDAgMCAxLTIgMmgtMTJhMiAyIDAgMCAxLTItMlY0YTIgMiAwIDAgMSAyLTJoMiIvPjxwYXRoIGQ9Ik0xNCAydjRjMCAxLjEgLjkgMiAyIDJoNCIvPjxwYXRoIGQ9Ik03IDloNSIvPjxwYXRoIGQ9Ik03IDEzaDUiLz48cGF0aCBkPSJNNyAxN2g4Ii8+PC9zdmc+';
|
||||||
}
|
}
|
||||||
|
return URL.createObjectURL(f);
|
||||||
|
});
|
||||||
|
setPreviewList(urls);
|
||||||
|
updateFileHint();
|
||||||
|
setTimeout(() => urls.forEach(u => { if (u.startsWith('blob:')) URL.revokeObjectURL(u); }), 0);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
item.appendChild(img);
|
||||||
|
item.appendChild(btn);
|
||||||
|
previewList.appendChild(item);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateFileHint() {
|
||||||
|
const count = selectedFiles.length;
|
||||||
|
fileHint.textContent = count ? `已选择 ${count} 个文件` : '未选择文件';
|
||||||
|
}
|
||||||
|
|
||||||
|
function addFiles(files) {
|
||||||
|
const incoming = Array.from(files || []).filter(f => f && (f.type.startsWith('image/') || f.name.toLowerCase().endsWith('.pdf')));
|
||||||
|
const existingKeys = new Set(selectedFiles.map(f => `${f.name}|${f.size}|${f.lastModified}`));
|
||||||
|
const rejected = [];
|
||||||
|
incoming.forEach(f => {
|
||||||
|
const key = `${f.name}|${f.size}|${f.lastModified}`;
|
||||||
|
if (!existingKeys.has(key) && selectedFiles.length < MAX_SINGLE_UPLOAD_COUNT) {
|
||||||
|
existingKeys.add(key);
|
||||||
|
selectedFiles.push(f);
|
||||||
|
} else if (!existingKeys.has(key) && selectedFiles.length >= MAX_SINGLE_UPLOAD_COUNT) {
|
||||||
|
rejected.push(f.name);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if (rejected.length) {
|
||||||
|
uploadMsg.textContent = `单次最多上传 ${MAX_SINGLE_UPLOAD_COUNT} 个文件,以下文件未加入:${rejected.join('、')}`;
|
||||||
|
uploadMsg.className = 'status-message error';
|
||||||
|
uploadMsg.style.display = 'block';
|
||||||
|
}
|
||||||
|
const urls = selectedFiles.map(f => {
|
||||||
|
if (f.name.toLowerCase().endsWith('.pdf')) {
|
||||||
|
return 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI0OCIgaGVpZ2h0PSI0OCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9IiNlZjQ0NDQiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIj48cGF0aCBkPSJNMTQgMmgyYTIgMiAwIDAgMSAyIDJ2MTZhMiAyIDAgMCAxLTIgMmgtMTJhMiAyIDAgMCAxLTItMlY0YTIgMiAwIDAgMSAyLTJoMiIvPjxwYXRoIGQ9Ik0xNCAydjRjMCAxLjEgLjkgMiAyIDJoNCIvPjxwYXRoIGQ9Ik03IDloNSIvPjxwYXRoIGQ9Ik03IDEzaDUiLz48cGF0aCBkPSJNNyAxN2g4Ii8+PC9zdmc+';
|
||||||
|
}
|
||||||
|
return URL.createObjectURL(f);
|
||||||
|
});
|
||||||
|
setPreviewList(urls);
|
||||||
|
updateFileHint();
|
||||||
|
setTimeout(() => urls.forEach(u => { if (u.startsWith('blob:')) URL.revokeObjectURL(u); }), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
fileInput.addEventListener('change', function(e) {
|
||||||
|
addFiles(e.target.files || []);
|
||||||
|
fileInput.value = '';
|
||||||
});
|
});
|
||||||
|
|
||||||
function createRow(k = '', v = '') {
|
function createKvRow(k = '', v = '', onInput) {
|
||||||
const row = document.createElement('div');
|
const row = document.createElement('div');
|
||||||
row.className = 'form-row';
|
row.className = 'form-row';
|
||||||
const keyInput = document.createElement('input');
|
const keyInput = document.createElement('input');
|
||||||
@@ -419,123 +325,224 @@ function createRow(k = '', v = '') {
|
|||||||
delBtn.type = 'button';
|
delBtn.type = 'button';
|
||||||
delBtn.className = 'btn btn-danger';
|
delBtn.className = 'btn btn-danger';
|
||||||
delBtn.textContent = '删除';
|
delBtn.textContent = '删除';
|
||||||
|
|
||||||
delBtn.onclick = () => {
|
delBtn.onclick = () => {
|
||||||
if (kvForm.children.length > 1) {
|
const container = row.parentElement;
|
||||||
kvForm.removeChild(row);
|
if (container.querySelectorAll('.form-row').length > 1) {
|
||||||
|
container.removeChild(row);
|
||||||
} else {
|
} else {
|
||||||
keyInput.value = '';
|
keyInput.value = '';
|
||||||
valInput.value = '';
|
valInput.value = '';
|
||||||
}
|
}
|
||||||
syncTextarea();
|
if (onInput) onInput();
|
||||||
};
|
};
|
||||||
keyInput.oninput = syncTextarea;
|
|
||||||
valInput.oninput = syncTextarea;
|
keyInput.oninput = onInput;
|
||||||
|
valInput.oninput = onInput;
|
||||||
|
|
||||||
row.appendChild(keyInput);
|
row.appendChild(keyInput);
|
||||||
row.appendChild(valInput);
|
row.appendChild(valInput);
|
||||||
row.appendChild(delBtn);
|
row.appendChild(delBtn);
|
||||||
return row;
|
return row;
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderFormFromObject(obj) {
|
function renderPendingItems(items) {
|
||||||
kvForm.innerHTML = '';
|
pendingItems.innerHTML = '';
|
||||||
Object.keys(obj || {}).forEach(k => {
|
currentItems = items;
|
||||||
kvForm.appendChild(createRow(k, obj[k]));
|
|
||||||
});
|
|
||||||
if (!kvForm.children.length) kvForm.appendChild(createRow());
|
|
||||||
syncTextarea();
|
|
||||||
}
|
|
||||||
|
|
||||||
function objectFromForm() {
|
items.forEach((item, index) => {
|
||||||
|
const itemEl = document.createElement('div');
|
||||||
|
itemEl.className = 'pending-item';
|
||||||
|
|
||||||
|
const header = document.createElement('div');
|
||||||
|
header.className = 'pending-item-header';
|
||||||
|
header.innerHTML = `<span class="pending-item-title">${index + 1}. ${item.name}</span>`;
|
||||||
|
|
||||||
|
const removeBtn = document.createElement('button');
|
||||||
|
removeBtn.className = 'btn btn-danger';
|
||||||
|
removeBtn.textContent = '忽略此项';
|
||||||
|
removeBtn.onclick = () => {
|
||||||
|
currentItems.splice(index, 1);
|
||||||
|
renderPendingItems(currentItems);
|
||||||
|
};
|
||||||
|
header.appendChild(removeBtn);
|
||||||
|
|
||||||
|
const body = document.createElement('div');
|
||||||
|
body.className = 'pending-item-body';
|
||||||
|
|
||||||
|
const preview = document.createElement('div');
|
||||||
|
preview.className = 'pending-item-preview';
|
||||||
|
const mainImg = document.createElement('img');
|
||||||
|
mainImg.src = item.image_urls[0];
|
||||||
|
preview.appendChild(mainImg);
|
||||||
|
if (item.image_urls.length > 1) {
|
||||||
|
const hint = document.createElement('p');
|
||||||
|
hint.className = 'muted';
|
||||||
|
hint.style.textAlign = 'center';
|
||||||
|
hint.textContent = `共 ${item.image_urls.length} 页`;
|
||||||
|
preview.appendChild(hint);
|
||||||
|
}
|
||||||
|
|
||||||
|
const edit = document.createElement('div');
|
||||||
|
edit.className = 'pending-item-edit';
|
||||||
|
|
||||||
|
const controls = document.createElement('div');
|
||||||
|
controls.className = 'form-controls';
|
||||||
|
const addBtn = document.createElement('button');
|
||||||
|
addBtn.className = 'btn btn-secondary';
|
||||||
|
addBtn.textContent = '添加字段';
|
||||||
|
const syncBtn = document.createElement('button');
|
||||||
|
syncBtn.className = 'btn btn-secondary';
|
||||||
|
syncBtn.textContent = '刷新表单';
|
||||||
|
controls.appendChild(addBtn);
|
||||||
|
controls.appendChild(syncBtn);
|
||||||
|
|
||||||
|
const kvForm = document.createElement('div');
|
||||||
|
kvForm.className = 'kv-form-container';
|
||||||
|
kvForm.innerHTML = '<div class="form-header"><div>字段名</div><div>字段值</div><div>操作</div></div>';
|
||||||
|
|
||||||
|
const textarea = document.createElement('textarea');
|
||||||
|
textarea.className = 'result-textarea';
|
||||||
|
|
||||||
|
const syncData = () => {
|
||||||
const obj = {};
|
const obj = {};
|
||||||
Array.from(kvForm.children).forEach(row => {
|
kvForm.querySelectorAll('.form-row').forEach(row => {
|
||||||
const [kInput, vInput] = row.querySelectorAll('input');
|
const inputs = row.querySelectorAll('input');
|
||||||
const k = (kInput.value || '').trim();
|
const k = inputs[0].value.trim();
|
||||||
if (!k) return;
|
if (!k) return;
|
||||||
const raw = vInput.value;
|
try { obj[k] = JSON.parse(inputs[1].value); } catch(e) { obj[k] = inputs[1].value; }
|
||||||
try {
|
|
||||||
obj[k] = JSON.parse(raw);
|
|
||||||
} catch (_) {
|
|
||||||
obj[k] = raw;
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
return obj;
|
item.data = obj;
|
||||||
}
|
textarea.value = JSON.stringify(obj, null, 2);
|
||||||
|
};
|
||||||
|
|
||||||
function syncTextarea() {
|
Object.entries(item.data).forEach(([k, v]) => {
|
||||||
const obj = objectFromForm();
|
kvForm.appendChild(createKvRow(k, v, syncData));
|
||||||
resultBox.value = JSON.stringify(obj, null, 2);
|
});
|
||||||
}
|
if (kvForm.querySelectorAll('.form-row').length === 0) {
|
||||||
|
kvForm.appendChild(createKvRow('', '', syncData));
|
||||||
addFieldBtn.addEventListener('click', () => {
|
|
||||||
kvForm.appendChild(createRow());
|
|
||||||
syncTextarea();
|
|
||||||
});
|
|
||||||
|
|
||||||
syncFromTextBtn.addEventListener('click', () => {
|
|
||||||
try {
|
|
||||||
const obj = JSON.parse(resultBox.value || '{}');
|
|
||||||
renderFormFromObject(obj);
|
|
||||||
uploadMsg.textContent = '已从文本区刷新表单';
|
|
||||||
uploadMsg.className = 'status-message success';
|
|
||||||
uploadMsg.style.display = 'block';
|
|
||||||
setTimeout(() => {
|
|
||||||
uploadMsg.style.display = 'none';
|
|
||||||
}, 2000);
|
|
||||||
} catch (e) {
|
|
||||||
uploadMsg.textContent = '文本区不是有效JSON';
|
|
||||||
uploadMsg.className = 'status-message error';
|
|
||||||
uploadMsg.style.display = 'block';
|
|
||||||
}
|
}
|
||||||
});
|
|
||||||
|
addBtn.onclick = () => {
|
||||||
|
kvForm.appendChild(createKvRow('', '', syncData));
|
||||||
|
syncData();
|
||||||
|
};
|
||||||
|
|
||||||
|
syncBtn.onclick = () => {
|
||||||
|
try {
|
||||||
|
const obj = JSON.parse(textarea.value);
|
||||||
|
kvForm.innerHTML = '<div class="form-header"><div>字段名</div><div>字段值</div><div>操作</div></div>';
|
||||||
|
Object.entries(obj).forEach(([k, v]) => kvForm.appendChild(createKvRow(k, v, syncData)));
|
||||||
|
item.data = obj;
|
||||||
|
} catch(e) { alert('JSON格式错误'); }
|
||||||
|
};
|
||||||
|
|
||||||
|
textarea.value = JSON.stringify(item.data, null, 2);
|
||||||
|
textarea.oninput = () => { item.data = JSON.parse(textarea.value); };
|
||||||
|
|
||||||
|
edit.appendChild(controls);
|
||||||
|
edit.appendChild(kvForm);
|
||||||
|
edit.appendChild(textarea);
|
||||||
|
|
||||||
|
body.appendChild(preview);
|
||||||
|
body.appendChild(edit);
|
||||||
|
|
||||||
|
itemEl.appendChild(header);
|
||||||
|
itemEl.appendChild(body);
|
||||||
|
pendingItems.appendChild(itemEl);
|
||||||
|
});
|
||||||
|
|
||||||
|
confirmBtn.disabled = items.length === 0;
|
||||||
|
}
|
||||||
|
|
||||||
uploadForm.addEventListener('submit', async (e) => {
|
uploadForm.addEventListener('submit', async (e) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
uploadMsg.textContent = '';
|
uploadMsg.textContent = '';
|
||||||
confirmMsg.textContent = '';
|
confirmMsg.textContent = '';
|
||||||
confirmBtn.disabled = true;
|
confirmBtn.disabled = true;
|
||||||
resultBox.value = '';
|
previewList.innerHTML = '';
|
||||||
currentImageRel = '';
|
pendingItems.innerHTML = '';
|
||||||
|
currentItems = [];
|
||||||
|
|
||||||
const file = fileInput.files[0];
|
if (!selectedFiles.length) {
|
||||||
if (!file) {
|
uploadMsg.textContent = '请选择文件';
|
||||||
uploadMsg.textContent = '请选择图片文件';
|
uploadMsg.className = 'status-message error';
|
||||||
|
uploadMsg.style.display = 'block';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (selectedFiles.length > MAX_SINGLE_UPLOAD_COUNT) {
|
||||||
|
uploadMsg.textContent = `单次最多上传 ${MAX_SINGLE_UPLOAD_COUNT} 个文件,请分批上传`;
|
||||||
uploadMsg.className = 'status-message error';
|
uploadMsg.className = 'status-message error';
|
||||||
uploadMsg.style.display = 'block';
|
uploadMsg.style.display = 'block';
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
showProgress();
|
||||||
|
setProgress(5, '预处理中');
|
||||||
const formData = new FormData();
|
const formData = new FormData();
|
||||||
|
for (let i = 0; i < selectedFiles.length; i++) {
|
||||||
|
const file = selectedFiles[i];
|
||||||
|
if (file.type.startsWith('image/')) {
|
||||||
|
setProgress(5 + Math.round((i/selectedFiles.length)*45), '转换图片');
|
||||||
|
try {
|
||||||
|
const jpegFile = await convertToJpeg(file);
|
||||||
|
formData.append('file', jpegFile);
|
||||||
|
} catch (_) {
|
||||||
formData.append('file', file);
|
formData.append('file', file);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
formData.append('file', file);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
let prog = 50;
|
||||||
|
setProgress(prog, '识别中');
|
||||||
|
const timer = setInterval(() => {
|
||||||
|
prog = Math.min(95, prog + 1);
|
||||||
|
setProgress(prog, '识别中');
|
||||||
|
}, 200);
|
||||||
|
|
||||||
const resp = await fetch('/elastic/upload/', {
|
const resp = await fetch('/elastic/upload/', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
credentials: 'same-origin',
|
credentials: 'same-origin',
|
||||||
headers: { 'X-CSRFToken': getCookie('csrftoken') || '' },
|
headers: { 'X-CSRFToken': getCookie('csrftoken') || '' },
|
||||||
body: formData,
|
body: formData,
|
||||||
});
|
});
|
||||||
|
clearInterval(timer);
|
||||||
|
const ct = (resp.headers.get('content-type') || '').toLowerCase();
|
||||||
|
if (!ct.includes('application/json')) {
|
||||||
|
const text = await resp.text();
|
||||||
|
throw new Error(text ? String(text).slice(0, 200) : `HTTP ${resp.status}`);
|
||||||
|
}
|
||||||
const data = await resp.json();
|
const data = await resp.json();
|
||||||
if (!resp.ok || data.status !== 'success') {
|
if (!resp.ok || data.status !== 'success') {
|
||||||
throw new Error(data.message || '上传识别失败');
|
throw new Error(data.message || '上传识别失败');
|
||||||
}
|
}
|
||||||
|
setProgress(100, '识别完成');
|
||||||
uploadMsg.textContent = data.message || '识别成功';
|
uploadMsg.textContent = data.message || '识别成功';
|
||||||
uploadMsg.className = 'status-message success';
|
uploadMsg.className = 'status-message success';
|
||||||
uploadMsg.style.display = 'block';
|
uploadMsg.style.display = 'block';
|
||||||
preview.src = data.image_url;
|
|
||||||
renderFormFromObject(data.data || {});
|
renderPendingItems(data.items || []);
|
||||||
currentImageRel = data.image;
|
setTimeout(hideProgress, 800);
|
||||||
confirmBtn.disabled = false;
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
uploadMsg.textContent = e.message || '发生错误';
|
uploadMsg.textContent = e.message || '发生错误';
|
||||||
uploadMsg.className = 'status-message error';
|
uploadMsg.className = 'status-message error';
|
||||||
uploadMsg.style.display = 'block';
|
uploadMsg.style.display = 'block';
|
||||||
|
progressText.textContent = '识别失败';
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
confirmBtn.addEventListener('click', async () => {
|
confirmBtn.addEventListener('click', async () => {
|
||||||
confirmMsg.textContent = '';
|
confirmMsg.textContent = '正在录入...';
|
||||||
try {
|
try {
|
||||||
const edited = objectFromForm();
|
const payload = {
|
||||||
|
items: currentItems.map(it => ({
|
||||||
|
data: it.data,
|
||||||
|
image: it.images
|
||||||
|
}))
|
||||||
|
};
|
||||||
const resp = await fetch('/elastic/confirm/', {
|
const resp = await fetch('/elastic/confirm/', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
credentials: 'same-origin',
|
credentials: 'same-origin',
|
||||||
@@ -543,7 +550,7 @@ confirmBtn.addEventListener('click', async () => {
|
|||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
'X-CSRFToken': getCookie('csrftoken') || ''
|
'X-CSRFToken': getCookie('csrftoken') || ''
|
||||||
},
|
},
|
||||||
body: JSON.stringify({ data: edited, image: currentImageRel })
|
body: JSON.stringify(payload)
|
||||||
});
|
});
|
||||||
const data = await resp.json();
|
const data = await resp.json();
|
||||||
if (!resp.ok || data.status !== 'success') {
|
if (!resp.ok || data.status !== 'success') {
|
||||||
@@ -551,6 +558,12 @@ confirmBtn.addEventListener('click', async () => {
|
|||||||
}
|
}
|
||||||
confirmMsg.textContent = data.message || '录入成功';
|
confirmMsg.textContent = data.message || '录入成功';
|
||||||
confirmMsg.style.color = '#179957';
|
confirmMsg.style.color = '#179957';
|
||||||
|
// 录入成功后清空待处理列表
|
||||||
|
pendingItems.innerHTML = '';
|
||||||
|
currentItems = [];
|
||||||
|
selectedFiles = [];
|
||||||
|
updateFileHint();
|
||||||
|
confirmBtn.disabled = true;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
confirmMsg.textContent = e.message || '发生错误';
|
confirmMsg.textContent = e.message || '发生错误';
|
||||||
confirmMsg.style.color = '#d14343';
|
confirmMsg.style.color = '#d14343';
|
||||||
@@ -559,15 +572,18 @@ confirmBtn.addEventListener('click', async () => {
|
|||||||
|
|
||||||
clearBtn.addEventListener('click', () => {
|
clearBtn.addEventListener('click', () => {
|
||||||
fileInput.value = '';
|
fileInput.value = '';
|
||||||
preview.src = '';
|
previewList.innerHTML = '';
|
||||||
resultBox.value = '';
|
pendingItems.innerHTML = '';
|
||||||
kvForm.innerHTML = '';
|
|
||||||
kvForm.appendChild(createRow()); // 保留一个空行
|
|
||||||
uploadMsg.textContent = '';
|
uploadMsg.textContent = '';
|
||||||
confirmMsg.textContent = '';
|
confirmMsg.textContent = '';
|
||||||
confirmBtn.disabled = true;
|
confirmBtn.disabled = true;
|
||||||
|
currentItems = [];
|
||||||
|
selectedFiles = [];
|
||||||
|
updateFileHint();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
updateFileHint();
|
||||||
|
|
||||||
// 退出登录处理
|
// 退出登录处理
|
||||||
document.getElementById('logoutBtn').addEventListener('click', async () => {
|
document.getElementById('logoutBtn').addEventListener('click', async () => {
|
||||||
const msg = document.getElementById('logoutMsg');
|
const msg = document.getElementById('logoutMsg');
|
||||||
|
|||||||
@@ -4,70 +4,18 @@
|
|||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<title>用户管理</title>
|
<title>用户管理</title>
|
||||||
<style>
|
<style>
|
||||||
body {
|
body {margin: 0;font-family: system-ui, -apple-system, Segoe UI, Roboto, sans-serif;background: #fafafa;}
|
||||||
margin: 0;
|
|
||||||
font-family: system-ui, -apple-system, Segoe UI, Roboto, sans-serif;
|
|
||||||
background: #fafafa;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* 导航栏样式 */
|
/* 导航栏样式 */
|
||||||
.sidebar {
|
.sidebar {position: fixed;top: 0;left: 0;width: 180px;height: 100vh;background: #1e1e2e;color: white;padding: 20px;box-shadow: 2px 0 5px rgba(0,0,0,0.1);z-index: 1000;display: flex;
|
||||||
position: fixed;
|
flex-direction: column;align-items: center;}
|
||||||
top: 0;
|
.user-id {text-align: center;margin-bottom: 0px;}
|
||||||
left: 0;
|
.sidebar h3 {margin-top: 0;font-size: 18px;color: #add8e6;text-align: center; margin-bottom: 20px;}
|
||||||
width: 180px;
|
.navigation-links {width: 100%;margin-top: 60px;}
|
||||||
height: 100vh;
|
|
||||||
background: #1e1e2e;
|
|
||||||
color: white;
|
|
||||||
padding: 20px;
|
|
||||||
box-shadow: 2px 0 5px rgba(0,0,0,0.1);
|
|
||||||
z-index: 1000;
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
align-items: center;
|
|
||||||
}
|
|
||||||
|
|
||||||
.user-id {
|
|
||||||
text-align: center;
|
|
||||||
margin-bottom: 0px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.sidebar h3 {
|
|
||||||
margin-top: 0;
|
|
||||||
font-size: 18px;
|
|
||||||
color: #add8e6;
|
|
||||||
text-align: center;
|
|
||||||
margin-bottom: 20px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.navigation-links {
|
|
||||||
width: 100%;
|
|
||||||
margin-top: 60px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.sidebar a,
|
.sidebar a,
|
||||||
.sidebar button {
|
.sidebar button {display: block;color: #8be9fd;text-decoration: none;margin: 10px 0;font-size: 16px;padding: 15px;border-radius: 4px;background: transparent;
|
||||||
display: block;
|
border: none;cursor: pointer; width: calc(100% - 40px);text-align: left;transition: all 0.2s ease;}
|
||||||
color: #8be9fd;
|
|
||||||
text-decoration: none;
|
|
||||||
margin: 10px 0;
|
|
||||||
font-size: 16px;
|
|
||||||
padding: 15px;
|
|
||||||
border-radius: 4px;
|
|
||||||
background: transparent;
|
|
||||||
border: none;
|
|
||||||
cursor: pointer;
|
|
||||||
width: calc(100% - 40px);
|
|
||||||
text-align: left;
|
|
||||||
transition: all 0.2s ease;
|
|
||||||
}
|
|
||||||
|
|
||||||
.sidebar a:hover,
|
.sidebar a:hover,
|
||||||
.sidebar button:hover {
|
.sidebar button:hover {color: #ff79c6;background-color: rgba(139, 233, 253, 0.2);}
|
||||||
color: #ff79c6;
|
|
||||||
background-color: rgba(139, 233, 253, 0.2);
|
|
||||||
}
|
|
||||||
|
|
||||||
/* 主内容区 */
|
/* 主内容区 */
|
||||||
.main-content {
|
.main-content {
|
||||||
margin-left: 200px;
|
margin-left: 200px;
|
||||||
@@ -186,6 +134,13 @@
|
|||||||
border-radius: 6px;
|
border-radius: 6px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.search-container select {
|
||||||
|
padding: 8px 12px;
|
||||||
|
border: 1px solid #d1d5db;
|
||||||
|
border-radius: 6px;
|
||||||
|
background: #fff;
|
||||||
|
}
|
||||||
|
|
||||||
.search-container button {
|
.search-container button {
|
||||||
padding: 8px 15px;
|
padding: 8px 15px;
|
||||||
background: #4f46e5;
|
background: #4f46e5;
|
||||||
@@ -208,7 +163,7 @@
|
|||||||
|
|
||||||
.modal-content {
|
.modal-content {
|
||||||
background-color: white;
|
background-color: white;
|
||||||
margin: 10% auto;
|
margin: 6% auto;
|
||||||
padding: 20px;
|
padding: 20px;
|
||||||
border-radius: 8px;
|
border-radius: 8px;
|
||||||
width: 80%;
|
width: 80%;
|
||||||
@@ -252,41 +207,103 @@
|
|||||||
margin-top: 5px;
|
margin-top: 5px;
|
||||||
text-align: center;
|
text-align: center;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.keys-box {
|
||||||
|
max-height: 140px;
|
||||||
|
overflow: auto;
|
||||||
|
border: 1px solid #d1d5db;
|
||||||
|
border-radius: 6px;
|
||||||
|
padding: 8px 10px;
|
||||||
|
background: #fff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.key-item {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
padding: 4px 0;
|
||||||
|
font-size: 14px;
|
||||||
|
color: #111827;
|
||||||
|
user-select: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.key-item input[type="checkbox"] {
|
||||||
|
width: auto;
|
||||||
|
padding: 0;
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.key-edit-row {
|
||||||
|
display: flex;
|
||||||
|
gap: 10px;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.selected-keys {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 8px;
|
||||||
|
margin-top: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.key-tag {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
padding: 6px 10px;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: #eef2ff;
|
||||||
|
color: #1f2937;
|
||||||
|
border: 1px solid #c7d2fe;
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.key-tag button {
|
||||||
|
border: none;
|
||||||
|
background: transparent;
|
||||||
|
cursor: pointer;
|
||||||
|
color: #4b5563;
|
||||||
|
font-size: 14px;
|
||||||
|
line-height: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.key-tag.locked {
|
||||||
|
background: #f3f4f6;
|
||||||
|
border: 1px solid #e5e7eb;
|
||||||
|
color: #374151;
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<!-- 左侧固定栏目 -->
|
<!-- 左侧固定栏目 -->
|
||||||
<div class="sidebar">
|
<div class="sidebar">
|
||||||
<div class="user-id">
|
<div class="user-id">
|
||||||
<h3>用户ID:{{ user_id }}</h3>
|
<h3>你好,{{ username|default:"访客" }}</h3>
|
||||||
</div>
|
</div>
|
||||||
<div class="navigation-links">
|
<div class="navigation-links">
|
||||||
<a href="{% url 'main:home' %}" onclick="return handleNavClick(this, '/');">主页</a>
|
<a href="{% url 'main:home' %}" onclick="return handleNavClick(this, '/');">返回主页</a>
|
||||||
<button id="logoutBtn">退出登录</button>
|
<a id="logoutBtn">退出登录</a>
|
||||||
<div id="logoutMsg"></div>
|
<div id="logoutMsg"></div>
|
||||||
{% csrf_token %}
|
{% csrf_token %}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- 主内容区域 -->
|
|
||||||
<div class="main-content">
|
<div class="main-content">
|
||||||
<div class="card">
|
<div class="card">
|
||||||
<div class="header">
|
<div class="header">
|
||||||
<h2>用户管理</h2>
|
<h2>用户管理</h2>
|
||||||
<button id="addUserBtn" class="btn btn-primary">添加用户</button>
|
{% if is_admin %}<button id="addUserBtn" class="btn btn-primary">添加用户</button>{% endif %}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="notification success" id="successNotification">
|
<div class="notification success" id="successNotification">操作成功!</div>
|
||||||
操作成功!
|
<div class="notification error" id="errorNotification">操作失败!</div>
|
||||||
</div>
|
|
||||||
<div class="notification error" id="errorNotification">
|
|
||||||
操作失败!
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="search-container">
|
<div class="search-container">
|
||||||
<input type="text" id="searchInput" placeholder="搜索用户名...">
|
<input type="text" id="searchInput" placeholder="搜索用户名...">
|
||||||
|
<select id="keyFilter"></select>
|
||||||
<button id="searchBtn">搜索</button>
|
<button id="searchBtn">搜索</button>
|
||||||
<button id="resetBtn">重置</button>
|
<button id="resetBtn">重置</button>
|
||||||
|
<button id="clearKeyBtn">清空Key</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="table-container">
|
<div class="table-container">
|
||||||
@@ -295,13 +312,13 @@
|
|||||||
<tr>
|
<tr>
|
||||||
<th>用户ID</th>
|
<th>用户ID</th>
|
||||||
<th>用户名</th>
|
<th>用户名</th>
|
||||||
|
<th>Key</th>
|
||||||
|
<th>Manage Key</th>
|
||||||
<th>权限</th>
|
<th>权限</th>
|
||||||
<th>操作</th>
|
<th>操作</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody id="usersTableBody">
|
<tbody id="usersTableBody"></tbody>
|
||||||
<!-- 用户数据将通过JavaScript加载 -->
|
|
||||||
</tbody>
|
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -319,7 +336,7 @@
|
|||||||
<label for="username">用户名</label>
|
<label for="username">用户名</label>
|
||||||
<input type="text" id="username" name="username" required>
|
<input type="text" id="username" name="username" required>
|
||||||
</div>
|
</div>
|
||||||
<div class="form-group">
|
<div class="form-group" id="permissionGroup">
|
||||||
<label for="permission">权限</label>
|
<label for="permission">权限</label>
|
||||||
<select id="permission" name="permission" required>
|
<select id="permission" name="permission" required>
|
||||||
<option value="0">管理员</option>
|
<option value="0">管理员</option>
|
||||||
@@ -327,6 +344,28 @@
|
|||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label>Key(从已有 Key 中选择)</label>
|
||||||
|
<div class="key-edit-row">
|
||||||
|
<select id="userKeySelect"></select>
|
||||||
|
<button type="button" id="addUserKeyBtn" class="btn btn-primary">添加</button>
|
||||||
|
<button type="button" id="clearUserKeyBtn" class="btn">清空</button>
|
||||||
|
</div>
|
||||||
|
<div id="userKeysSelected" class="selected-keys"></div>
|
||||||
|
<div id="userKeysReadonlyGroup" style="display:none; margin-top: 10px;">
|
||||||
|
<div style="font-weight: 600; color: #374151; font-size: 13px; margin-bottom: 6px;">导师Key(不可修改)</div>
|
||||||
|
<div id="userKeysReadonly" class="selected-keys"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="form-group" id="manageKeyGroup">
|
||||||
|
<label>Manage Key(从已有 Key 中选择)</label>
|
||||||
|
<div class="key-edit-row">
|
||||||
|
<select id="userManageKeySelect"></select>
|
||||||
|
<button type="button" id="addUserManageKeyBtn" class="btn btn-primary">添加</button>
|
||||||
|
<button type="button" id="clearUserManageKeyBtn" class="btn">清空</button>
|
||||||
|
</div>
|
||||||
|
<div id="userManageKeysSelected" class="selected-keys"></div>
|
||||||
|
</div>
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label for="password">密码</label>
|
<label for="password">密码</label>
|
||||||
<input type="password" id="password" name="password" required>
|
<input type="password" id="password" name="password" required>
|
||||||
@@ -353,6 +392,14 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
|
const IS_ADMIN = {{ is_admin|yesno:"true,false" }};
|
||||||
|
const IS_TUTOR = {{ is_tutor|yesno:"true,false" }};
|
||||||
|
const MY_MANAGE_KEYS_RAW = JSON.parse('{{ manage_keys_json|default:"[]"|escapejs }}');
|
||||||
|
const MY_KEYS_RAW = JSON.parse('{{ my_keys_json|default:"[]"|escapejs }}');
|
||||||
|
let KEY_OPTIONS_CACHE = null;
|
||||||
|
let MODAL_SELECTED_KEYS = [];
|
||||||
|
let MODAL_SELECTED_MANAGE_KEYS = [];
|
||||||
|
|
||||||
// 获取CSRF令牌的函数
|
// 获取CSRF令牌的函数
|
||||||
function getCookie(name) {
|
function getCookie(name) {
|
||||||
const value = `; ${document.cookie}`;
|
const value = `; ${document.cookie}`;
|
||||||
@@ -388,11 +435,12 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 获取所有用户
|
// 获取所有用户
|
||||||
async function loadUsers(searchTerm = '') {
|
async function loadUsers(searchTerm = '', key = '') {
|
||||||
try {
|
try {
|
||||||
const url = searchTerm ?
|
const params = new URLSearchParams();
|
||||||
`/elastic/users/?search=${encodeURIComponent(searchTerm)}` :
|
if ((searchTerm || '').trim()) params.set('search', (searchTerm || '').trim());
|
||||||
'/elastic/users/';
|
if ((key || '').trim()) params.set('key', (key || '').trim());
|
||||||
|
const url = params.toString() ? `/elastic/users/?${params.toString()}` : '/elastic/users/';
|
||||||
|
|
||||||
const response = await fetch(url);
|
const response = await fetch(url);
|
||||||
const result = await response.json();
|
const result = await response.json();
|
||||||
@@ -409,10 +457,16 @@
|
|||||||
|
|
||||||
// 根据权限值显示权限名称
|
// 根据权限值显示权限名称
|
||||||
const permissionText = Number(user.permission) === 0 ? '管理员' : '普通用户';
|
const permissionText = Number(user.permission) === 0 ? '管理员' : '普通用户';
|
||||||
|
const keys = Array.isArray(user.key) ? user.key : (user.key ? [user.key] : []);
|
||||||
|
const keysText = keys.map(k => String(k || '').trim()).filter(Boolean).join('、') || '-';
|
||||||
|
const manageKeys = Array.isArray(user.manage_key) ? user.manage_key : (user.manage_key ? [user.manage_key] : []);
|
||||||
|
const manageKeysText = manageKeys.map(k => String(k || '').trim()).filter(Boolean).join('、') || '-';
|
||||||
|
|
||||||
row.innerHTML = `
|
row.innerHTML = `
|
||||||
<td>${user.user_id}</td>
|
<td>${user.user_id}</td>
|
||||||
<td>${user.username}</td>
|
<td>${user.username}</td>
|
||||||
|
<td>${keysText}</td>
|
||||||
|
<td>${manageKeysText}</td>
|
||||||
<td>${permissionText}</td>
|
<td>${permissionText}</td>
|
||||||
<td class="action-buttons">
|
<td class="action-buttons">
|
||||||
<button class="btn btn-success edit-btn" data-user='${JSON.stringify(user)}'>编辑</button>
|
<button class="btn btn-success edit-btn" data-user='${JSON.stringify(user)}'>编辑</button>
|
||||||
@@ -431,22 +485,225 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function initKeyFilter() {
|
||||||
|
const select = document.getElementById('keyFilter');
|
||||||
|
if (!select) return;
|
||||||
|
select.innerHTML = '<option value="">全部Key</option>';
|
||||||
|
try {
|
||||||
|
const keys = await fetchKeyOptions();
|
||||||
|
keys.forEach(k => {
|
||||||
|
const opt = document.createElement('option');
|
||||||
|
opt.value = String(k || '').trim();
|
||||||
|
opt.textContent = String(k || '').trim();
|
||||||
|
if (opt.value) select.appendChild(opt);
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
}
|
||||||
|
select.addEventListener('change', () => {
|
||||||
|
const searchTerm = document.getElementById('searchInput').value;
|
||||||
|
loadUsers(searchTerm, select.value);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeStr(v) {
|
||||||
|
return String(v || '').trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
const MY_MANAGE_KEYS = (Array.isArray(MY_MANAGE_KEYS_RAW) ? MY_MANAGE_KEYS_RAW : [])
|
||||||
|
.map(normalizeStr)
|
||||||
|
.filter(Boolean);
|
||||||
|
const MY_MANAGE_KEYS_SET = new Set(MY_MANAGE_KEYS);
|
||||||
|
const MY_KEYS = (Array.isArray(MY_KEYS_RAW) ? MY_KEYS_RAW : [])
|
||||||
|
.map(normalizeStr)
|
||||||
|
.filter(Boolean);
|
||||||
|
const MY_KEYS_SET = new Set(MY_KEYS);
|
||||||
|
|
||||||
|
async function fetchKeyOptions() {
|
||||||
|
if (Array.isArray(KEY_OPTIONS_CACHE)) return KEY_OPTIONS_CACHE;
|
||||||
|
try {
|
||||||
|
const resp = await fetch('/elastic/keys-for-filter/', { credentials: 'same-origin' });
|
||||||
|
const data = await resp.json();
|
||||||
|
if (data.status !== 'success') return [];
|
||||||
|
const keys = (data.data || []).map(normalizeStr).filter(Boolean);
|
||||||
|
KEY_OPTIONS_CACHE = keys;
|
||||||
|
return keys;
|
||||||
|
} catch (e) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function setSelectOptions(selectId, options) {
|
||||||
|
const select = document.getElementById(selectId);
|
||||||
|
if (!select) return;
|
||||||
|
select.innerHTML = '<option value="">请选择Key</option>';
|
||||||
|
(options || []).forEach(k => {
|
||||||
|
const s = normalizeStr(k);
|
||||||
|
if (!s) return;
|
||||||
|
const opt = document.createElement('option');
|
||||||
|
opt.value = s;
|
||||||
|
opt.textContent = s;
|
||||||
|
select.appendChild(opt);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function setSelectOptionsMixed(selectId, enabledOptions, disabledOptions) {
|
||||||
|
const select = document.getElementById(selectId);
|
||||||
|
if (!select) return;
|
||||||
|
select.innerHTML = '<option value="">请选择Key</option>';
|
||||||
|
(enabledOptions || []).forEach(k => {
|
||||||
|
const s = normalizeStr(k);
|
||||||
|
if (!s) return;
|
||||||
|
const opt = document.createElement('option');
|
||||||
|
opt.value = s;
|
||||||
|
opt.textContent = s;
|
||||||
|
select.appendChild(opt);
|
||||||
|
});
|
||||||
|
(disabledOptions || []).forEach(k => {
|
||||||
|
const s = normalizeStr(k);
|
||||||
|
if (!s) return;
|
||||||
|
const opt = document.createElement('option');
|
||||||
|
opt.value = s;
|
||||||
|
opt.textContent = s;
|
||||||
|
opt.disabled = true;
|
||||||
|
select.appendChild(opt);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderSelectedTags(containerId, selectedArr) {
|
||||||
|
const container = document.getElementById(containerId);
|
||||||
|
if (!container) return;
|
||||||
|
container.innerHTML = '';
|
||||||
|
(selectedArr || []).forEach(k => {
|
||||||
|
const tag = document.createElement('span');
|
||||||
|
tag.className = 'key-tag';
|
||||||
|
const text = document.createElement('span');
|
||||||
|
text.textContent = k;
|
||||||
|
const btn = document.createElement('button');
|
||||||
|
btn.type = 'button';
|
||||||
|
btn.textContent = '×';
|
||||||
|
btn.addEventListener('click', () => {
|
||||||
|
const idx = selectedArr.indexOf(k);
|
||||||
|
if (idx >= 0) selectedArr.splice(idx, 1);
|
||||||
|
renderSelectedTags(containerId, selectedArr);
|
||||||
|
});
|
||||||
|
tag.appendChild(text);
|
||||||
|
tag.appendChild(btn);
|
||||||
|
container.appendChild(tag);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderReadonlyTags(containerId, keysArr) {
|
||||||
|
const container = document.getElementById(containerId);
|
||||||
|
if (!container) return;
|
||||||
|
container.innerHTML = '';
|
||||||
|
(keysArr || []).forEach(k => {
|
||||||
|
const tag = document.createElement('span');
|
||||||
|
tag.className = 'key-tag locked';
|
||||||
|
const text = document.createElement('span');
|
||||||
|
text.textContent = k;
|
||||||
|
tag.appendChild(text);
|
||||||
|
container.appendChild(tag);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function setReadonlyKeysVisible(visible) {
|
||||||
|
const group = document.getElementById('userKeysReadonlyGroup');
|
||||||
|
if (group) group.style.display = visible ? '' : 'none';
|
||||||
|
}
|
||||||
|
|
||||||
|
function setKeyEditorDisabled(prefix, disabled) {
|
||||||
|
const select = document.getElementById(prefix + 'Select');
|
||||||
|
const addBtn = document.getElementById('add' + prefix.charAt(0).toUpperCase() + prefix.slice(1) + 'Btn');
|
||||||
|
const clearBtn = document.getElementById('clear' + prefix.charAt(0).toUpperCase() + prefix.slice(1) + 'Btn');
|
||||||
|
if (select) select.disabled = !!disabled;
|
||||||
|
if (addBtn) addBtn.disabled = !!disabled;
|
||||||
|
if (clearBtn) clearBtn.disabled = !!disabled;
|
||||||
|
}
|
||||||
|
|
||||||
|
function addFromSelect(selectId, selectedArr, renderId) {
|
||||||
|
const select = document.getElementById(selectId);
|
||||||
|
if (!select) return;
|
||||||
|
const v = normalizeStr(select.value);
|
||||||
|
if (!v) return;
|
||||||
|
if (!selectedArr.includes(v)) selectedArr.push(v);
|
||||||
|
renderSelectedTags(renderId, selectedArr);
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearSelected(selectedArr, renderId) {
|
||||||
|
selectedArr.length = 0;
|
||||||
|
renderSelectedTags(renderId, selectedArr);
|
||||||
|
}
|
||||||
|
|
||||||
// 打开添加用户模态框
|
// 打开添加用户模态框
|
||||||
function openAddModal() {
|
async function openAddModal() {
|
||||||
document.getElementById('modalTitle').textContent = '添加用户';
|
document.getElementById('modalTitle').textContent = '添加用户';
|
||||||
document.getElementById('userForm').reset();
|
document.getElementById('userForm').reset();
|
||||||
document.getElementById('userId').value = '';
|
document.getElementById('userId').value = '';
|
||||||
|
document.getElementById('username').disabled = false;
|
||||||
|
document.getElementById('permission').disabled = false;
|
||||||
|
document.getElementById('permissionGroup').style.display = '';
|
||||||
|
document.getElementById('manageKeyGroup').style.display = '';
|
||||||
|
const options = await fetchKeyOptions();
|
||||||
|
if ((!IS_ADMIN) && IS_TUTOR) {
|
||||||
|
const enabled = (options || []).map(normalizeStr).filter(k => k && !MY_KEYS_SET.has(k));
|
||||||
|
setSelectOptionsMixed('userKeySelect', enabled, MY_KEYS);
|
||||||
|
} else {
|
||||||
|
setSelectOptions('userKeySelect', options);
|
||||||
|
}
|
||||||
|
setSelectOptions('userManageKeySelect', options);
|
||||||
|
MODAL_SELECTED_KEYS = [];
|
||||||
|
MODAL_SELECTED_MANAGE_KEYS = [];
|
||||||
|
renderSelectedTags('userKeysSelected', MODAL_SELECTED_KEYS);
|
||||||
|
renderSelectedTags('userManageKeysSelected', MODAL_SELECTED_MANAGE_KEYS);
|
||||||
|
setReadonlyKeysVisible(false);
|
||||||
|
renderReadonlyTags('userKeysReadonly', []);
|
||||||
|
setKeyEditorDisabled('userKey', false);
|
||||||
|
setKeyEditorDisabled('userManageKey', false);
|
||||||
document.getElementById('password').required = true;
|
document.getElementById('password').required = true;
|
||||||
document.getElementById('confirmPassword').required = true;
|
document.getElementById('confirmPassword').required = true;
|
||||||
document.getElementById('userModal').style.display = 'block';
|
document.getElementById('userModal').style.display = 'block';
|
||||||
}
|
}
|
||||||
|
|
||||||
// 打开编辑用户模态框
|
// 打开编辑用户模态框
|
||||||
function openEditModal(user) {
|
async function openEditModal(user) {
|
||||||
document.getElementById('modalTitle').textContent = '编辑用户';
|
document.getElementById('modalTitle').textContent = '编辑用户';
|
||||||
document.getElementById('username').value = user.username;
|
document.getElementById('username').value = user.username;
|
||||||
document.getElementById('userId').value = user.user_id;
|
document.getElementById('userId').value = user.user_id;
|
||||||
document.getElementById('permission').value = user.permission;
|
document.getElementById('permission').value = user.permission;
|
||||||
|
const options = await fetchKeyOptions();
|
||||||
|
setSelectOptions('userManageKeySelect', options);
|
||||||
|
const allUserKeys = (Array.isArray(user.key) ? user.key : (user.key ? [user.key] : [])).map(normalizeStr).filter(Boolean);
|
||||||
|
const lockedKeys = allUserKeys.filter(k => MY_KEYS_SET.has(k));
|
||||||
|
if ((!IS_ADMIN) && IS_TUTOR) {
|
||||||
|
const enabled = (options || []).map(normalizeStr).filter(k => k && !MY_KEYS_SET.has(k));
|
||||||
|
setSelectOptionsMixed('userKeySelect', enabled, MY_KEYS);
|
||||||
|
} else {
|
||||||
|
setSelectOptions('userKeySelect', options);
|
||||||
|
}
|
||||||
|
MODAL_SELECTED_KEYS = IS_ADMIN ? allUserKeys : allUserKeys.filter(k => !MY_KEYS_SET.has(k));
|
||||||
|
MODAL_SELECTED_MANAGE_KEYS = (Array.isArray(user.manage_key) ? user.manage_key : (user.manage_key ? [user.manage_key] : [])).map(normalizeStr).filter(Boolean);
|
||||||
|
MODAL_SELECTED_KEYS = Array.from(new Set(MODAL_SELECTED_KEYS));
|
||||||
|
MODAL_SELECTED_MANAGE_KEYS = Array.from(new Set(MODAL_SELECTED_MANAGE_KEYS));
|
||||||
|
renderSelectedTags('userKeysSelected', MODAL_SELECTED_KEYS);
|
||||||
|
renderSelectedTags('userManageKeysSelected', MODAL_SELECTED_MANAGE_KEYS);
|
||||||
|
setReadonlyKeysVisible((!IS_ADMIN) && IS_TUTOR && lockedKeys.length > 0);
|
||||||
|
renderReadonlyTags('userKeysReadonly', ((!IS_ADMIN) && IS_TUTOR) ? Array.from(new Set(lockedKeys)) : []);
|
||||||
|
|
||||||
|
if (IS_ADMIN) {
|
||||||
|
document.getElementById('username').disabled = false;
|
||||||
|
document.getElementById('permission').disabled = false;
|
||||||
|
document.getElementById('permissionGroup').style.display = '';
|
||||||
|
document.getElementById('manageKeyGroup').style.display = '';
|
||||||
|
setKeyEditorDisabled('userKey', false);
|
||||||
|
setKeyEditorDisabled('userManageKey', false);
|
||||||
|
} else {
|
||||||
|
document.getElementById('username').disabled = true;
|
||||||
|
document.getElementById('permission').disabled = true;
|
||||||
|
document.getElementById('permissionGroup').style.display = 'none';
|
||||||
|
document.getElementById('manageKeyGroup').style.display = 'none';
|
||||||
|
setKeyEditorDisabled('userKey', !IS_TUTOR);
|
||||||
|
setKeyEditorDisabled('userManageKey', true);
|
||||||
|
}
|
||||||
document.getElementById('password').required = false;
|
document.getElementById('password').required = false;
|
||||||
document.getElementById('confirmPassword').required = false;
|
document.getElementById('confirmPassword').required = false;
|
||||||
document.getElementById('userModal').style.display = 'block';
|
document.getElementById('userModal').style.display = 'block';
|
||||||
@@ -482,10 +739,15 @@
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const data = {
|
const data = {};
|
||||||
username: username,
|
if (IS_ADMIN) {
|
||||||
permission: parseInt(permission)
|
data.username = username;
|
||||||
};
|
data.permission = parseInt(permission);
|
||||||
|
data.key = MODAL_SELECTED_KEYS;
|
||||||
|
data.manage_key = MODAL_SELECTED_MANAGE_KEYS;
|
||||||
|
} else {
|
||||||
|
data.key = MODAL_SELECTED_KEYS;
|
||||||
|
}
|
||||||
|
|
||||||
if (password) {
|
if (password) {
|
||||||
data.password = password;
|
data.password = password;
|
||||||
@@ -522,7 +784,9 @@
|
|||||||
if (result.status === 'success') {
|
if (result.status === 'success') {
|
||||||
showNotification(userId ? '用户更新成功' : '用户添加成功');
|
showNotification(userId ? '用户更新成功' : '用户添加成功');
|
||||||
document.getElementById('userModal').style.display = 'none';
|
document.getElementById('userModal').style.display = 'none';
|
||||||
loadUsers();
|
const searchTerm = (document.getElementById('searchInput') || {}).value || '';
|
||||||
|
const key = (document.getElementById('keyFilter') || {}).value || '';
|
||||||
|
loadUsers(searchTerm, key);
|
||||||
} else {
|
} else {
|
||||||
showNotification(result.message || '操作失败', false);
|
showNotification(result.message || '操作失败', false);
|
||||||
}
|
}
|
||||||
@@ -563,7 +827,10 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 事件监听器
|
// 事件监听器
|
||||||
document.getElementById('addUserBtn').addEventListener('click', openAddModal);
|
const addBtn = document.getElementById('addUserBtn');
|
||||||
|
if (addBtn) {
|
||||||
|
addBtn.addEventListener('click', openAddModal);
|
||||||
|
}
|
||||||
|
|
||||||
document.getElementById('userForm').addEventListener('submit', saveUser);
|
document.getElementById('userForm').addEventListener('submit', saveUser);
|
||||||
|
|
||||||
@@ -575,15 +842,59 @@
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
document.getElementById('searchBtn').addEventListener('click', function() {
|
const searchBtn = document.getElementById('searchBtn');
|
||||||
|
if (searchBtn) {
|
||||||
|
searchBtn.addEventListener('click', function() {
|
||||||
const searchTerm = document.getElementById('searchInput').value;
|
const searchTerm = document.getElementById('searchInput').value;
|
||||||
loadUsers(searchTerm);
|
const key = (document.getElementById('keyFilter') || {}).value || '';
|
||||||
|
loadUsers(searchTerm, key);
|
||||||
});
|
});
|
||||||
|
}
|
||||||
|
|
||||||
document.getElementById('resetBtn').addEventListener('click', function() {
|
const resetBtn = document.getElementById('resetBtn');
|
||||||
|
if (resetBtn) {
|
||||||
|
resetBtn.addEventListener('click', function() {
|
||||||
document.getElementById('searchInput').value = '';
|
document.getElementById('searchInput').value = '';
|
||||||
loadUsers();
|
const select = document.getElementById('keyFilter');
|
||||||
|
if (select) select.value = '';
|
||||||
|
loadUsers('', '');
|
||||||
});
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const clearKeyBtn = document.getElementById('clearKeyBtn');
|
||||||
|
if (clearKeyBtn) {
|
||||||
|
clearKeyBtn.addEventListener('click', function() {
|
||||||
|
const select = document.getElementById('keyFilter');
|
||||||
|
if (select) select.value = '';
|
||||||
|
const searchTerm = document.getElementById('searchInput').value;
|
||||||
|
loadUsers(searchTerm, '');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const addUserKeyBtn = document.getElementById('addUserKeyBtn');
|
||||||
|
if (addUserKeyBtn) {
|
||||||
|
addUserKeyBtn.addEventListener('click', function() {
|
||||||
|
addFromSelect('userKeySelect', MODAL_SELECTED_KEYS, 'userKeysSelected');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const clearUserKeyBtn = document.getElementById('clearUserKeyBtn');
|
||||||
|
if (clearUserKeyBtn) {
|
||||||
|
clearUserKeyBtn.addEventListener('click', function() {
|
||||||
|
clearSelected(MODAL_SELECTED_KEYS, 'userKeysSelected');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const addUserManageKeyBtn = document.getElementById('addUserManageKeyBtn');
|
||||||
|
if (addUserManageKeyBtn) {
|
||||||
|
addUserManageKeyBtn.addEventListener('click', function() {
|
||||||
|
addFromSelect('userManageKeySelect', MODAL_SELECTED_MANAGE_KEYS, 'userManageKeysSelected');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const clearUserManageKeyBtn = document.getElementById('clearUserManageKeyBtn');
|
||||||
|
if (clearUserManageKeyBtn) {
|
||||||
|
clearUserManageKeyBtn.addEventListener('click', function() {
|
||||||
|
clearSelected(MODAL_SELECTED_MANAGE_KEYS, 'userManageKeysSelected');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// 点击模态框外部关闭模态框
|
// 点击模态框外部关闭模态框
|
||||||
window.addEventListener('click', function(event) {
|
window.addEventListener('click', function(event) {
|
||||||
@@ -624,7 +935,12 @@
|
|||||||
|
|
||||||
// 页面加载时获取用户列表
|
// 页面加载时获取用户列表
|
||||||
document.addEventListener('DOMContentLoaded', function() {
|
document.addEventListener('DOMContentLoaded', function() {
|
||||||
loadUsers();
|
initKeyFilter();
|
||||||
|
const tbody = document.getElementById('usersTableBody');
|
||||||
|
if (tbody) {
|
||||||
|
const select = document.getElementById('keyFilter');
|
||||||
|
loadUsers('', select ? select.value : '');
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// 为表格中的编辑和删除按钮添加事件监听器
|
// 为表格中的编辑和删除按钮添加事件监听器
|
||||||
|
|||||||
@@ -17,6 +17,13 @@ urlpatterns = [
|
|||||||
path('search/', views.search, name='search'),
|
path('search/', views.search, name='search'),
|
||||||
path('fuzzy-search/', views.fuzzy_search, name='fuzzy_search'),
|
path('fuzzy-search/', views.fuzzy_search, name='fuzzy_search'),
|
||||||
path('all-data/', views.get_all_data, name='get_all_data'),
|
path('all-data/', views.get_all_data, name='get_all_data'),
|
||||||
|
path('filter-by-key/', views.filter_by_key, name='filter_by_key'),
|
||||||
|
path('keys-for-filter/', views.keys_for_filter_view, name='keys_for_filter'),
|
||||||
|
path('types-for-filter/', views.types_for_filter_view, name='types_for_filter'),
|
||||||
|
path('filter/', views.filter_view, name='filter'),
|
||||||
|
path('report/', views.report_view, name='report'),
|
||||||
|
path('report/csv/', views.report_csv_view, name='report_csv'),
|
||||||
|
path('export_achievements_csv/', views.export_achievements_csv, name='export_achievements_csv'),
|
||||||
|
|
||||||
# 用户管理
|
# 用户管理
|
||||||
path('users/', views.get_users, name='get_users'),
|
path('users/', views.get_users, name='get_users'),
|
||||||
@@ -32,6 +39,14 @@ urlpatterns = [
|
|||||||
# 管理页面
|
# 管理页面
|
||||||
path('manage/', views.manage_page, name='manage_page'),
|
path('manage/', views.manage_page, name='manage_page'),
|
||||||
path('user_manage/', views.user_manage, name='user_manage'),
|
path('user_manage/', views.user_manage, name='user_manage'),
|
||||||
|
path('registration-codes/manage/', views.registration_code_manage_page, name='registration_code_manage_page'),
|
||||||
|
path('registration-codes/keys/', views.get_keys_list_view, name='get_keys_list'),
|
||||||
|
path('registration-codes/keys/add/', views.add_key_view, name='add_key'),
|
||||||
|
path('registration-codes/keys/remove/', views.remove_key_view, name='remove_key'),
|
||||||
|
path('registration-codes/keys/unallow/', views.unallow_tutor_added_key_view, name='unallow_tutor_added_key'),
|
||||||
|
path('registration-codes/generate/', views.generate_registration_code_view, name='generate_registration_code'),
|
||||||
|
path('registration-codes/list/', views.list_registration_codes_view, name='list_registration_codes'),
|
||||||
|
path('registration-codes/revoke/', views.revoke_registration_code_view, name='revoke_registration_code'),
|
||||||
|
|
||||||
# 分析接口
|
# 分析接口
|
||||||
path('analytics/trend/', views.analytics_trend_view, name='analytics_trend'),
|
path('analytics/trend/', views.analytics_trend_view, name='analytics_trend'),
|
||||||
|
|||||||
1581
elastic/views.py
1581
elastic/views.py
File diff suppressed because it is too large
Load Diff
@@ -6,147 +6,58 @@
|
|||||||
<title>数据管理系统</title>
|
<title>数据管理系统</title>
|
||||||
<script src="{% static 'vendor/echarts.min.js' %}"></script>
|
<script src="{% static 'vendor/echarts.min.js' %}"></script>
|
||||||
<style>
|
<style>
|
||||||
body {
|
body {margin: 0;font-family: system-ui, -apple-system, Segoe UI, Roboto, sans-serif;background: #fafafa;}
|
||||||
margin: 0;
|
|
||||||
font-family: system-ui, -apple-system, Segoe UI, Roboto, sans-serif;
|
|
||||||
background: #fafafa;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* 导航栏样式 */
|
/* 导航栏样式 */
|
||||||
.sidebar {
|
.sidebar {position: fixed;top: 0;left: 0;width: 180px;height: 100vh;background: #1e1e2e;color: white;padding: 20px;box-shadow: 2px 0 5px rgba(0,0,0,0.1);z-index: 1000;display: flex;
|
||||||
position: fixed;
|
flex-direction: column;align-items: center;}
|
||||||
top: 0;
|
.user-id {text-align: center;margin-bottom: 0px;}
|
||||||
left: 0;
|
.sidebar h3 {margin-top: 0;font-size: 18px;color: #add8e6;text-align: center; margin-bottom: 20px;}
|
||||||
width: 180px;
|
.navigation-links {width: 100%;margin-top: 60px;}
|
||||||
height: 100vh;
|
|
||||||
background: #1e1e2e;
|
|
||||||
color: white;
|
|
||||||
padding: 20px;
|
|
||||||
box-shadow: 2px 0 5px rgba(0,0,0,0.1);
|
|
||||||
z-index: 1000;
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
align-items: center;
|
|
||||||
}
|
|
||||||
|
|
||||||
.user-id {
|
|
||||||
text-align: center;
|
|
||||||
margin-bottom: 0px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.sidebar h3 {
|
|
||||||
margin-top: 0;
|
|
||||||
font-size: 18px;
|
|
||||||
color: #add8e6;
|
|
||||||
text-align: center;
|
|
||||||
margin-bottom: 20px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.navigation-links {
|
|
||||||
width: 100%;
|
|
||||||
margin-top: 60px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.sidebar a,
|
.sidebar a,
|
||||||
.sidebar button {
|
.sidebar button {display: block;color: #8be9fd;text-decoration: none;margin: 10px 0;font-size: 16px;padding: 15px;border-radius: 4px;background: transparent;
|
||||||
display: block;
|
border: none;cursor: pointer; width: calc(100% - 40px);text-align: left;transition: all 0.2s ease;}
|
||||||
color: #8be9fd;
|
|
||||||
text-decoration: none;
|
|
||||||
margin: 10px 0;
|
|
||||||
font-size: 16px;
|
|
||||||
padding: 15px;
|
|
||||||
border-radius: 4px;
|
|
||||||
background: transparent;
|
|
||||||
border: none;
|
|
||||||
cursor: pointer;
|
|
||||||
width: calc(100% - 40px);
|
|
||||||
text-align: left;
|
|
||||||
transition: all 0.2s ease;
|
|
||||||
}
|
|
||||||
|
|
||||||
.sidebar a:hover,
|
.sidebar a:hover,
|
||||||
.sidebar button:hover {
|
.sidebar button:hover {color: #ff79c6;background-color: rgba(139, 233, 253, 0.2);}
|
||||||
color: #ff79c6;
|
|
||||||
background-color: rgba(139, 233, 253, 0.2);
|
|
||||||
}
|
|
||||||
|
|
||||||
/* 主内容区 */
|
/* 主内容区 */
|
||||||
.main-content {
|
.main-content {margin-left: 200px;padding: 20px;color: #333;}
|
||||||
margin-left: 200px;
|
.card {background: #fff;border-radius: 14px;box-shadow: 0 10px 24px rgba(31,35,40,0.08);padding: 20px;}
|
||||||
padding: 20px;
|
.grid {display: grid;grid-template-columns: repeat(2, 1fr);gap: 16px;}
|
||||||
color: #333;
|
.grid-3 {display: grid;grid-template-columns: repeat(3, 1fr);gap: 16px; }
|
||||||
}
|
.header {display: flex;align-items: center; justify-content: space-between; margin-bottom: 12px; }
|
||||||
|
.badge { background: #eef2ff; color: #3730a3; border-radius: 999px; padding: 4px 10px; font-size: 12px; }
|
||||||
.card {
|
.legend {display: flex;gap: 12px;align-items: center;}
|
||||||
background: #fff;
|
.legend .dot { width: 8px;height: 8px;border-radius: 50%;display: inline-block; }
|
||||||
border-radius: 14px;
|
.muted {color: #6b7280;font-size: 12px;}
|
||||||
box-shadow: 0 10px 24px rgba(31,35,40,0.08);
|
.btn {padding: 8px 12px;border: none; border-radius: 8px;cursor: pointer; }
|
||||||
padding: 20px;
|
.btn-primary {background: #4f46e5;color: #fff;}
|
||||||
}
|
|
||||||
.grid {
|
|
||||||
display: grid;
|
|
||||||
grid-template-columns: repeat(2, 1fr);
|
|
||||||
gap: 16px;
|
|
||||||
}
|
|
||||||
.grid-3 {
|
|
||||||
display: grid;
|
|
||||||
grid-template-columns: repeat(3, 1fr);
|
|
||||||
gap: 16px;
|
|
||||||
}
|
|
||||||
.header {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
justify-content: space-between;
|
|
||||||
margin-bottom: 12px;
|
|
||||||
}
|
|
||||||
.badge {
|
|
||||||
background: #eef2ff;
|
|
||||||
color: #3730a3;
|
|
||||||
border-radius: 999px;
|
|
||||||
padding: 4px 10px;
|
|
||||||
font-size: 12px;
|
|
||||||
}
|
|
||||||
.legend {
|
|
||||||
display: flex;
|
|
||||||
gap: 12px;
|
|
||||||
align-items: center;
|
|
||||||
}
|
|
||||||
.legend .dot {
|
|
||||||
width: 8px;
|
|
||||||
height: 8px;
|
|
||||||
border-radius: 50%;
|
|
||||||
display: inline-block;
|
|
||||||
}
|
|
||||||
.muted {
|
|
||||||
color: #6b7280;
|
|
||||||
font-size: 12px;
|
|
||||||
}
|
|
||||||
.btn {
|
|
||||||
padding: 8px 12px;
|
|
||||||
border: none;
|
|
||||||
border-radius: 8px;
|
|
||||||
cursor: pointer;
|
|
||||||
}
|
|
||||||
.btn-primary {
|
|
||||||
background: #4f46e5;
|
|
||||||
color: #fff;
|
|
||||||
}
|
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<!-- 左侧固定栏目 -->
|
<!-- 左侧固定栏目 -->
|
||||||
<div class="sidebar">
|
<div class="sidebar">
|
||||||
<div class="user-id">
|
<div class="user-id">
|
||||||
<h3>用户ID:{{ user_id }}</h3>
|
<h3>你好,{{ username|default:"访客" }}</h3>
|
||||||
</div>
|
</div>
|
||||||
<div class="navigation-links">
|
<div class="navigation-links">
|
||||||
<a href="{% url 'main:home' %}" onclick="return handleNavClick(this, '/');">主页</a>
|
<a href="{% url 'main:home' %}" onclick="return handleNavClick(this, '/');">主页</a>
|
||||||
<a href="{% url 'elastic:upload_page' %}" onclick="return handleNavClick(this, '/elastic/upload/');">图片上传与识别</a>
|
<a href="{% url 'elastic:upload_page' %}" onclick="return handleNavClick(this, '/elastic/upload/');">图片上传与识别</a>
|
||||||
|
{% if is_admin or has_manage_key %}
|
||||||
<a href="{% url 'elastic:manage_page' %}" onclick="return handleNavClick(this, '/elastic/manage/');">数据管理</a>
|
<a href="{% url 'elastic:manage_page' %}" onclick="return handleNavClick(this, '/elastic/manage/');">数据管理</a>
|
||||||
{% if is_admin %}
|
{% endif %}
|
||||||
|
{% if is_admin or has_manage_key %}
|
||||||
<a href="{% url 'elastic:user_manage' %}" onclick="return handleNavClick(this, '/elastic/user_manage/');">用户管理</a>
|
<a href="{% url 'elastic:user_manage' %}" onclick="return handleNavClick(this, '/elastic/user_manage/');">用户管理</a>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
<button id="logoutBtn">退出登录</button>
|
<a href="/accounts/profile/">个人中心</a>
|
||||||
|
{% if is_admin or has_manage_key or can_manage_registration_codes %}
|
||||||
|
<a href="{% url 'elastic:registration_code_manage_page' %}" onclick="return handleNavClick(this, '/elastic/registration-codes/manage/');">注册码管理</a>
|
||||||
|
{% endif %}
|
||||||
|
{% if is_admin %}
|
||||||
|
<a href="{% url 'accounts:registration_code_requests_page' %}">注册码申请管理</a>
|
||||||
|
{% endif %}
|
||||||
|
{% if not is_admin and not has_manage_key and not can_manage_registration_codes and not has_registration_code %}
|
||||||
|
<a id="applyRegBtn" href="javascript:void(0)">申请注册码管理</a>
|
||||||
|
{% endif %}
|
||||||
|
<a id="logoutBtn">退出登录</a>
|
||||||
<div id="logoutMsg"></div>
|
<div id="logoutMsg"></div>
|
||||||
{% csrf_token %}
|
{% csrf_token %}
|
||||||
</div>
|
</div>
|
||||||
@@ -156,7 +67,7 @@
|
|||||||
<div class="main-content">
|
<div class="main-content">
|
||||||
<div class="card">
|
<div class="card">
|
||||||
<div class="header">
|
<div class="header">
|
||||||
<h2>主页</h2>
|
<h2>师生共创系统</h2>
|
||||||
<span class="badge">用户:{{ user_id }}</span>
|
<span class="badge">用户:{{ user_id }}</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="muted">数据可视化概览:录入量变化、类型占比、类型变化、最近活动</div>
|
<div class="muted">数据可视化概览:录入量变化、类型占比、类型变化、最近活动</div>
|
||||||
@@ -167,7 +78,10 @@
|
|||||||
<div id="chartTrend" style="width:100%;height:320px;"></div>
|
<div id="chartTrend" style="width:100%;height:320px;"></div>
|
||||||
</div>
|
</div>
|
||||||
<div class="card">
|
<div class="card">
|
||||||
<div class="header"><h3>类型占比(近30天)</h3></div>
|
<div class="header">
|
||||||
|
<h3>类型占比(近30天)</h3>
|
||||||
|
<button id="toggleTypesChartBtn" class="btn btn-primary" style="font-size: 12px; padding: 4px 8px;">切换图表</button>
|
||||||
|
</div>
|
||||||
<div id="chartTypes" style="width:100%;height:320px;"></div>
|
<div id="chartTypes" style="width:100%;height:320px;"></div>
|
||||||
</div>
|
</div>
|
||||||
<div class="card">
|
<div class="card">
|
||||||
@@ -181,6 +95,24 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div id="applyRegModal" style="display:none; position:fixed; inset:0; background:rgba(0,0,0,0.45); z-index:3000; align-items:center; justify-content:center;">
|
||||||
|
<div class="card" style="width:min(560px, calc(100vw - 40px));">
|
||||||
|
<div class="header">
|
||||||
|
<h3 style="margin:0;">申请注册码管理权限</h3>
|
||||||
|
<button id="applyRegClose" class="btn" type="button" style="background:#e5e7eb;">关闭</button>
|
||||||
|
</div>
|
||||||
|
<div class="muted" style="margin-bottom:10px;">填写申请理由,管理员同意后可进入“注册码管理”页面。</div>
|
||||||
|
<div style="margin-top:10px;">
|
||||||
|
<label for="applyReason" style="display:block; margin-bottom:6px; font-weight:600;">申请理由</label>
|
||||||
|
<textarea id="applyReason" rows="5" style="width:100%; padding:10px 12px; border:1px solid #d1d5db; border-radius:10px; box-sizing:border-box; resize: vertical;"></textarea>
|
||||||
|
</div>
|
||||||
|
<div id="applyRegMsg" class="muted" style="margin-top:10px;"></div>
|
||||||
|
<div style="display:flex; gap:10px; justify-content:flex-end; margin-top:14px;">
|
||||||
|
<button id="applyRegSubmit" class="btn btn-primary" type="button">提交申请</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
// 获取CSRF令牌的函数
|
// 获取CSRF令牌的函数
|
||||||
function getCookie(name) {
|
function getCookie(name) {
|
||||||
@@ -247,6 +179,68 @@
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const applyRegBtn = document.getElementById('applyRegBtn');
|
||||||
|
const applyRegModal = document.getElementById('applyRegModal');
|
||||||
|
const applyRegClose = document.getElementById('applyRegClose');
|
||||||
|
const applyRegSubmit = document.getElementById('applyRegSubmit');
|
||||||
|
const applyRegMsg = document.getElementById('applyRegMsg');
|
||||||
|
const applyReason = document.getElementById('applyReason');
|
||||||
|
|
||||||
|
function openApplyRegModal() {
|
||||||
|
if (!applyRegModal) return;
|
||||||
|
applyRegMsg.textContent = '';
|
||||||
|
applyReason.value = '';
|
||||||
|
applyRegModal.style.display = 'flex';
|
||||||
|
}
|
||||||
|
function closeApplyRegModal() {
|
||||||
|
if (!applyRegModal) return;
|
||||||
|
applyRegModal.style.display = 'none';
|
||||||
|
}
|
||||||
|
if (applyRegBtn) applyRegBtn.addEventListener('click', openApplyRegModal);
|
||||||
|
if (applyRegClose) applyRegClose.addEventListener('click', closeApplyRegModal);
|
||||||
|
if (applyRegModal) {
|
||||||
|
applyRegModal.addEventListener('click', (e) => {
|
||||||
|
if (e.target === applyRegModal) closeApplyRegModal();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (applyRegSubmit) {
|
||||||
|
applyRegSubmit.addEventListener('click', async () => {
|
||||||
|
const reason = (applyReason.value || '').trim();
|
||||||
|
if (!reason) {
|
||||||
|
applyRegMsg.textContent = '请填写申请理由';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
applyRegMsg.textContent = '提交中...';
|
||||||
|
const csrftoken = getCookie('csrftoken');
|
||||||
|
try {
|
||||||
|
const resp = await fetch('/accounts/registration-code/request/submit/', {
|
||||||
|
method: 'POST',
|
||||||
|
credentials: 'same-origin',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'X-CSRFToken': csrftoken || ''
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ reason })
|
||||||
|
});
|
||||||
|
const data = await resp.json();
|
||||||
|
if (resp.ok && data.ok) {
|
||||||
|
applyRegMsg.textContent = '已提交申请,请等待管理员审核';
|
||||||
|
if (applyRegBtn) {
|
||||||
|
applyRegBtn.textContent = '已提交申请';
|
||||||
|
applyRegBtn.disabled = true;
|
||||||
|
applyRegBtn.style.opacity = '0.6';
|
||||||
|
applyRegBtn.style.cursor = 'not-allowed';
|
||||||
|
}
|
||||||
|
setTimeout(() => closeApplyRegModal(), 800);
|
||||||
|
} else {
|
||||||
|
applyRegMsg.textContent = (data && data.message) ? data.message : '提交失败';
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
applyRegMsg.textContent = '提交失败';
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
function fetchJSON(url){ return fetch(url, {credentials:'same-origin'}).then(r=>r.json()); }
|
function fetchJSON(url){ return fetch(url, {credentials:'same-origin'}).then(r=>r.json()); }
|
||||||
function qs(params){ const u = new URLSearchParams(params); return u.toString(); }
|
function qs(params){ const u = new URLSearchParams(params); return u.toString(); }
|
||||||
@@ -270,18 +264,73 @@
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let typesChartData = [];
|
||||||
|
let currentChartType = 'pie';
|
||||||
|
let typesChartInterval = null;
|
||||||
|
|
||||||
async function loadTypes(){
|
async function loadTypes(){
|
||||||
const url = '/elastic/analytics/types/?' + qs({ from:'now-30d', to:'now', size:10 });
|
const url = '/elastic/analytics/types/?' + qs({ from:'now-30d', to:'now', size:10 });
|
||||||
const res = await fetchJSON(url);
|
const res = await fetchJSON(url);
|
||||||
if(res.status!=='success') return;
|
if(res.status!=='success') return;
|
||||||
const buckets = res.data || [];
|
const buckets = res.data || [];
|
||||||
const data = buckets.map(b=>({ name: String(b.key||'未知'), value: b.doc_count||0 }));
|
typesChartData = buckets.map(b=>({ name: String(b.key||'未知'), value: b.doc_count||0 }));
|
||||||
|
renderTypesChart();
|
||||||
|
startTypesChartRotation();
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderTypesChart() {
|
||||||
|
if (currentChartType === 'pie') {
|
||||||
typesChart.setOption({
|
typesChart.setOption({
|
||||||
tooltip:{trigger:'item'},
|
tooltip:{trigger:'item'},
|
||||||
legend:{type:'scroll'},
|
legend:{type:'scroll', top:'bottom'},
|
||||||
series:[{ type:'pie', radius:['40%','70%'], data }]
|
grid: { top: 0, bottom: 0, left: 0, right: 0 },
|
||||||
});
|
xAxis: { show: false },
|
||||||
|
yAxis: { show: false },
|
||||||
|
series:[{
|
||||||
|
type:'pie',
|
||||||
|
radius:['40%','70%'],
|
||||||
|
center: ['50%', '50%'],
|
||||||
|
data: typesChartData,
|
||||||
|
label: { show: false },
|
||||||
|
itemStyle: { borderRadius: 10, borderColor: '#fff', borderWidth: 2 }
|
||||||
|
}]
|
||||||
|
}, true);
|
||||||
|
} else {
|
||||||
|
const names = typesChartData.map(d => d.name);
|
||||||
|
const values = typesChartData.map(d => d.value);
|
||||||
|
typesChart.setOption({
|
||||||
|
tooltip:{trigger:'axis', axisPointer:{type:'shadow'}},
|
||||||
|
legend:{show: false},
|
||||||
|
grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
|
||||||
|
xAxis: { type: 'category', data: names, show: true },
|
||||||
|
yAxis: { type: 'value', show: true },
|
||||||
|
series: [{
|
||||||
|
type: 'bar',
|
||||||
|
data: values,
|
||||||
|
itemStyle: { color: '#5470c6' },
|
||||||
|
barWidth: '60%'
|
||||||
|
}]
|
||||||
|
}, true);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggleChartType() {
|
||||||
|
currentChartType = currentChartType === 'pie' ? 'bar' : 'pie';
|
||||||
|
renderTypesChart();
|
||||||
|
}
|
||||||
|
|
||||||
|
function startTypesChartRotation() {
|
||||||
|
if (typesChartInterval) clearInterval(typesChartInterval);
|
||||||
|
typesChartInterval = setInterval(() => {
|
||||||
|
toggleChartType();
|
||||||
|
}, 5000);
|
||||||
|
}
|
||||||
|
|
||||||
|
document.getElementById('toggleTypesChartBtn').addEventListener('click', () => {
|
||||||
|
toggleChartType();
|
||||||
|
// Reset timer on manual interaction
|
||||||
|
startTypesChartRotation();
|
||||||
|
});
|
||||||
|
|
||||||
async function loadTypesTrend(){
|
async function loadTypesTrend(){
|
||||||
const url = '/elastic/analytics/types_trend/?' + qs({ from:'now-180d', to:'now', interval:'week', size:6 });
|
const url = '/elastic/analytics/types_trend/?' + qs({ from:'now-180d', to:'now', interval:'week', size:6 });
|
||||||
@@ -333,7 +382,8 @@
|
|||||||
const t = formatTime(it.time);
|
const t = formatTime(it.time);
|
||||||
const u = it.username || '';
|
const u = it.username || '';
|
||||||
const ty = it.type || '未知';
|
const ty = it.type || '未知';
|
||||||
li.textContent = `${t},${u},${ty}`;
|
const de = it.detail ? `,${it.detail}` : '';
|
||||||
|
li.textContent = `${t},${u},${ty}${de}`;
|
||||||
listEl.appendChild(li);
|
listEl.appendChild(li);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,12 +10,10 @@ def home(request):
|
|||||||
if session_user_id is None:
|
if session_user_id is None:
|
||||||
return redirect("/accounts/login/")
|
return redirect("/accounts/login/")
|
||||||
|
|
||||||
# Show user_id (prefer query param if present, but don't trust it)
|
uid = session_user_id
|
||||||
user_id_qs = request.GET.get("user_id")
|
|
||||||
uid = user_id_qs or session_user_id
|
|
||||||
perm = request.session.get("permission")
|
perm = request.session.get("permission")
|
||||||
|
u = get_user_by_id(uid) if uid is not None else None
|
||||||
if perm is None and uid is not None:
|
if perm is None and uid is not None:
|
||||||
u = get_user_by_id(uid)
|
|
||||||
try:
|
try:
|
||||||
perm = int((u or {}).get("permission", 1))
|
perm = int((u or {}).get("permission", 1))
|
||||||
except Exception:
|
except Exception:
|
||||||
@@ -26,8 +24,15 @@ def home(request):
|
|||||||
perm = int(perm)
|
perm = int(perm)
|
||||||
except Exception:
|
except Exception:
|
||||||
perm = 1
|
perm = 1
|
||||||
|
has_manage_key = bool((u or {}).get("manage_key") or [])
|
||||||
|
can_manage_registration_codes = bool(int((u or {}).get("can_manage_registration_codes") or 0) == 1)
|
||||||
|
has_registration_code = bool(str((u or {}).get("registration_code") or "").strip())
|
||||||
context = {
|
context = {
|
||||||
"user_id": uid,
|
"user_id": uid,
|
||||||
|
"username": (u or {}).get("username"),
|
||||||
"is_admin": (int(perm) == 0),
|
"is_admin": (int(perm) == 0),
|
||||||
|
"has_manage_key": has_manage_key,
|
||||||
|
"can_manage_registration_codes": can_manage_registration_codes,
|
||||||
|
"has_registration_code": has_registration_code,
|
||||||
}
|
}
|
||||||
return render(request, "main/home.html", context)
|
return render(request, "main/home.html", context)
|
||||||
1
minio_storage/__init__.py
Normal file
1
minio_storage/__init__.py
Normal file
@@ -0,0 +1 @@
|
|||||||
|
|
||||||
22
minio_storage/apps.py
Normal file
22
minio_storage/apps.py
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
from django.apps import AppConfig
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
|
||||||
|
class MinioStorageConfig(AppConfig):
|
||||||
|
default_auto_field = 'django.db.models.BigAutoField'
|
||||||
|
name = 'minio_storage'
|
||||||
|
|
||||||
|
def ready(self):
|
||||||
|
if os.path.basename(sys.argv[0]) == 'manage.py':
|
||||||
|
if os.environ.get('RUN_MAIN') != 'true':
|
||||||
|
return
|
||||||
|
if 'runserver' not in sys.argv:
|
||||||
|
return
|
||||||
|
|
||||||
|
from .minio_connect import ensure_bucket_exists
|
||||||
|
try:
|
||||||
|
ensure_bucket_exists()
|
||||||
|
except Exception as e:
|
||||||
|
print(f"❌ MinIO 初始化失败: {e}")
|
||||||
|
|
||||||
133
minio_storage/minio_connect.py
Normal file
133
minio_storage/minio_connect.py
Normal file
@@ -0,0 +1,133 @@
|
|||||||
|
import os
|
||||||
|
from datetime import timedelta
|
||||||
|
import mimetypes
|
||||||
|
from urllib.parse import urlparse
|
||||||
|
|
||||||
|
from minio import Minio
|
||||||
|
from minio.error import S3Error
|
||||||
|
|
||||||
|
|
||||||
|
def _env_bool(name: str, default: bool = False) -> bool:
|
||||||
|
v = os.environ.get(name)
|
||||||
|
if v is None:
|
||||||
|
return default
|
||||||
|
return str(v).strip().lower() in {'1', 'true', 'yes', 'y', 'on'}
|
||||||
|
|
||||||
|
|
||||||
|
def _normalize_endpoint(minio_url: str):
|
||||||
|
if not minio_url:
|
||||||
|
return None, None
|
||||||
|
|
||||||
|
u = str(minio_url).strip()
|
||||||
|
parsed = urlparse(u)
|
||||||
|
if parsed.scheme in {'http', 'https'}:
|
||||||
|
endpoint = parsed.netloc
|
||||||
|
secure = parsed.scheme == 'https'
|
||||||
|
else:
|
||||||
|
endpoint = u
|
||||||
|
secure = None
|
||||||
|
|
||||||
|
endpoint = endpoint.strip().rstrip('/')
|
||||||
|
return endpoint, secure
|
||||||
|
|
||||||
|
|
||||||
|
def _get_env(*names: str, default: str | None = None) -> str | None:
|
||||||
|
for n in names:
|
||||||
|
v = os.environ.get(n)
|
||||||
|
if v is not None and str(v).strip() != '':
|
||||||
|
return str(v).strip()
|
||||||
|
return default
|
||||||
|
|
||||||
|
|
||||||
|
def get_minio_client() -> Minio | None:
|
||||||
|
minio_url = _get_env('MINIO_URL', 'MINIO_ENDPOINT')
|
||||||
|
access_key = _get_env('MINIO_ACCESS_KEY')
|
||||||
|
secret_key = _get_env('MINIO_SECRET_KEY')
|
||||||
|
|
||||||
|
if not minio_url or not access_key or not secret_key:
|
||||||
|
return None
|
||||||
|
|
||||||
|
endpoint, secure_from_url = _normalize_endpoint(minio_url)
|
||||||
|
if not endpoint:
|
||||||
|
return None
|
||||||
|
|
||||||
|
secure = _env_bool('MINIO_SECURE', default=secure_from_url if secure_from_url is not None else False)
|
||||||
|
region = _get_env('MINIO_REGION', default=None)
|
||||||
|
|
||||||
|
return Minio(
|
||||||
|
endpoint=endpoint,
|
||||||
|
access_key=access_key,
|
||||||
|
secret_key=secret_key,
|
||||||
|
secure=secure,
|
||||||
|
region=region,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def is_minio_configured() -> bool:
|
||||||
|
return get_minio_client() is not None
|
||||||
|
|
||||||
|
|
||||||
|
def get_bucket_name() -> str:
|
||||||
|
return _get_env('MINIO_BUCKET', default='achievement') or 'achievement'
|
||||||
|
|
||||||
|
|
||||||
|
def ensure_bucket_exists() -> bool:
|
||||||
|
client = get_minio_client()
|
||||||
|
bucket = get_bucket_name()
|
||||||
|
if client is None:
|
||||||
|
print('ℹ️ MinIO 环境变量未配置,跳过桶检查')
|
||||||
|
return False
|
||||||
|
|
||||||
|
if not bucket:
|
||||||
|
print('ℹ️ MINIO_BUCKET 为空,跳过桶检查')
|
||||||
|
return False
|
||||||
|
|
||||||
|
try:
|
||||||
|
exists = client.bucket_exists(bucket)
|
||||||
|
except S3Error as e:
|
||||||
|
print(f'❌ MinIO 连接失败: {e}')
|
||||||
|
return False
|
||||||
|
|
||||||
|
if exists:
|
||||||
|
print(f'ℹ️ MinIO 桶已存在: {bucket}')
|
||||||
|
return True
|
||||||
|
|
||||||
|
try:
|
||||||
|
region = _get_env('MINIO_REGION', default=None)
|
||||||
|
if region:
|
||||||
|
client.make_bucket(bucket, location=region)
|
||||||
|
else:
|
||||||
|
client.make_bucket(bucket)
|
||||||
|
print(f'✅ MinIO 桶已创建: {bucket}')
|
||||||
|
return True
|
||||||
|
except S3Error as e:
|
||||||
|
print(f'❌ MinIO 创建桶失败: {e}')
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def upload_file(file_path: str, object_name: str, content_type: str | None = None) -> str:
|
||||||
|
client = get_minio_client()
|
||||||
|
if client is None:
|
||||||
|
raise RuntimeError('MinIO 未配置')
|
||||||
|
|
||||||
|
bucket = get_bucket_name()
|
||||||
|
ensure_bucket_exists()
|
||||||
|
|
||||||
|
ct = content_type
|
||||||
|
if not ct:
|
||||||
|
guessed, _ = mimetypes.guess_type(object_name)
|
||||||
|
ct = guessed or 'application/octet-stream'
|
||||||
|
|
||||||
|
client.fput_object(bucket, object_name, file_path, content_type=ct)
|
||||||
|
return object_name
|
||||||
|
|
||||||
|
|
||||||
|
def presigned_get_url(object_name: str, expires_seconds: int = 8 * 60 * 60) -> str:
|
||||||
|
client = get_minio_client()
|
||||||
|
if client is None:
|
||||||
|
raise RuntimeError('MinIO 未配置')
|
||||||
|
|
||||||
|
bucket = get_bucket_name()
|
||||||
|
ensure_bucket_exists()
|
||||||
|
exp = max(1, int(expires_seconds or 0))
|
||||||
|
return client.presigned_get_object(bucket, object_name, expires=timedelta(seconds=exp))
|
||||||
@@ -6,6 +6,12 @@ elasticsearch-dsl==7.4.1
|
|||||||
requests==2.32.3
|
requests==2.32.3
|
||||||
openai==1.52.2
|
openai==1.52.2
|
||||||
httpx==0.27.2
|
httpx==0.27.2
|
||||||
|
zai-sdk==0.2.2
|
||||||
Pillow==10.4.0
|
Pillow==10.4.0
|
||||||
|
minio>=7.2.0,<8
|
||||||
gunicorn==21.2.0
|
gunicorn==21.2.0
|
||||||
whitenoise==6.6.0
|
whitenoise==6.6.0
|
||||||
|
django-browser-reload==1.21.0
|
||||||
|
captcha==0.7.1
|
||||||
|
cryptography==46.0.3
|
||||||
|
pymupdf==1.25.3
|
||||||
|
|||||||
Reference in New Issue
Block a user