1 Commits

Author SHA1 Message Date
cnbugs 96023431fc feat: 新增超级管理员重置用户密码功能
- 用户列表页 /users/:支持按用户名/姓名/邮箱搜索、按状态筛选、分页
- 重置密码页 /users/<id>/password/:仅超级管理员可访问
- 复用 Django 密码校验器(一致性、长度、相似度、常见/纯数字密码)
- 管理员重置自身密码时保持登录会话不失效
- settings 补充 AUTH_PASSWORD_VALIDATORS 配置
2026-10-15 18:59:34 +08:00
8 changed files with 309 additions and 5 deletions
+18 -2
View File
@@ -11,6 +11,7 @@
- **Excel 导入导出** — 批量导入(分类不存在自动创建)、筛选导出、模板下载
- **多维度搜索** — 按编号/名称/部门/维护人/位置搜索,按分类/状态/位置筛选
- **质保提醒** — 已过保/即将过保状态标识
- **用户管理** — 超级管理员可查看用户列表、搜索筛选、为任意用户重置密码(密码强度校验,重置自身不掉登录)
- **用户认证** — 登录/退出,管理员权限控制
- **深色主题** — 护眼深色 UI,适合长时间使用
@@ -120,6 +121,16 @@ DATABASES = {
| DJANGO_DEBUG | False | 调试模式 |
| DJANGO_SECRET_KEY | your-secret-key... | Django 密钥 |
## 👥 用户管理
- 超级管理员登录后,导航栏可见 **用户管理** 入口(路径 `/users/`)
- 支持按用户名 / 姓名 / 邮箱搜索,按账号状态(正常/已禁用)筛选
- 点击"重置密码"可为任意用户设置新密码:
- 两次密码必须一致
- 应用 Django 密码强度校验(最少 8 位、不能与用户信息过于相似、不能是常见/纯数字密码)
- 管理员重置自己的密码后当前登录不会失效
- 该功能仅 **超级管理员(is_superuser)** 可访问,其他用户访问会被拒绝
## 📊 Excel 导入格式
| 资产编号 | 设备名称 | 分类 | 品牌 | 型号 | 资产面值 | 序列号 | 状态 | IP地址 | BMC地址 | 设备位置 | 负责人 | 使用部门 | 维护人 | 采购日期 | 质保到期 | 备注 |
@@ -137,7 +148,7 @@ asset-management/
├── assetapp/ # 主应用
│ ├── models.py # 数据模型
│ ├── views.py # 视图逻辑
│ ├── forms.py # 表单定义
│ ├── forms.py # 表单定义(含管理员重置密码表单)
│ ├── excel_utils.py # Excel 导入导出工具
│ ├── urls.py # URL 路由
│ ├── management/commands/ # 管理命令
@@ -147,7 +158,7 @@ asset-management/
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── templates/assetapp/ # HTML 模板
├── templates/assetapp/ # HTML 模板(含 user_list / user_password_reset)
├── static/css/ # 静态资源
├── docker-compose.yml # Docker 编排
├── Dockerfile # 容器构建
@@ -158,6 +169,11 @@ asset-management/
## 📝 版本历史
### v1.1.0
- 新增用户管理:超级管理员可查看用户列表、搜索筛选、重置任意用户密码
- 补充密码强度校验配置
### v1.0.0
- 资产增删改查
+37
View File
@@ -1,4 +1,5 @@
from django import forms
from django.contrib.auth.password_validation import password_validators_help_text_html, validate_password
from .models import Asset, Category
@@ -33,3 +34,39 @@ class CategoryForm(forms.ModelForm):
class Meta:
model = Category
fields = ['name', 'description']
class AdminPasswordResetForm(forms.Form):
"""管理员重置指定用户密码的表单"""
new_password1 = forms.CharField(
label='新密码',
widget=forms.PasswordInput(attrs={'class': 'form-control', 'autocomplete': 'new-password'}),
help_text=password_validators_help_text_html(),
)
new_password2 = forms.CharField(
label='确认新密码',
widget=forms.PasswordInput(attrs={'class': 'form-control', 'autocomplete': 'new-password'}),
)
def __init__(self, *args, target_user=None, **kwargs):
self.target_user = target_user
super().__init__(*args, **kwargs)
def clean(self):
cleaned_data = super().clean()
password1 = cleaned_data.get('new_password1')
password2 = cleaned_data.get('new_password2')
if password1 and password2 and password1 != password2:
raise forms.ValidationError('两次输入的密码不一致')
if password1 and self.target_user is not None:
validate_password(password1, self.target_user)
return cleaned_data
def save(self):
self.target_user.set_password(self.cleaned_data['new_password1'])
self.target_user.save(update_fields=['password'])
return self.target_user
+4
View File
@@ -29,4 +29,8 @@ urlpatterns = [
path('categories/create/', views.category_create, name='category_create'),
path('categories/<int:pk>/edit/', views.category_update, name='category_update'),
path('categories/<int:pk>/delete/', views.category_delete, name='category_delete'),
# 用户管理(仅超级管理员)
path('users/', views.user_list, name='user_list'),
path('users/<int:pk>/password/', views.admin_password_reset, name='admin_password_reset'),
]
+58 -3
View File
@@ -1,6 +1,7 @@
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required, user_passes_test
from django.contrib.auth import authenticate, login, logout, update_session_auth_hash
from django.contrib.auth.models import User
from django.contrib import messages
from django.http import HttpResponse, JsonResponse
from django.db.models import Count, Q
@@ -11,7 +12,7 @@ from io import BytesIO
from datetime import date, timedelta
from .models import Asset, Category, AssetChangeLog
from .forms import AssetForm, AssetImportForm, CategoryForm
from .forms import AssetForm, AssetImportForm, CategoryForm, AdminPasswordResetForm
from .excel_utils import (
export_assets_to_excel, generate_import_template,
import_assets_from_excel, STATUS_MAP,
@@ -437,3 +438,57 @@ def category_delete(request, pk):
return redirect('category_list')
return render(request, 'assetapp/category_confirm_delete.html', {'category': category})
# ─── 用户管理(仅超级管理员) ───────────────────────
superuser_required = user_passes_test(lambda u: u.is_authenticated and u.is_superuser)
@superuser_required
def user_list(request):
users = User.objects.order_by('id')
keyword = request.GET.get('search', '').strip()
if keyword:
users = users.filter(
Q(username__icontains=keyword) |
Q(first_name__icontains=keyword) |
Q(email__icontains=keyword)
)
is_active = request.GET.get('is_active')
if is_active in ('1', '0'):
users = users.filter(is_active=(is_active == '1'))
paginator = Paginator(users, 20)
page_obj = paginator.get_page(request.GET.get('page', 1))
context = {
'page_obj': page_obj,
'search': keyword,
'current_is_active': is_active,
}
return render(request, 'assetapp/user_list.html', context)
@superuser_required
def admin_password_reset(request, pk):
target_user = get_object_or_404(User, pk=pk)
if request.method == 'POST':
form = AdminPasswordResetForm(request.POST, target_user=target_user)
if form.is_valid():
form.save()
# 如果管理员重置的是自己的密码,保持当前登录会话不失效
if request.user.pk == target_user.pk:
update_session_auth_hash(request, target_user)
messages.success(request, f'用户 "{target_user.username}" 的密码已重置')
return redirect('user_list')
else:
form = AdminPasswordResetForm(target_user=target_user)
context = {'form': form, 'target_user': target_user}
return render(request, 'assetapp/user_password_reset.html', context)
+9
View File
@@ -76,6 +76,15 @@ LOGIN_URL = '/login/'
LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = '/login/'
# Password validation
AUTH_PASSWORD_VALIDATORS = [
{'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator'},
{'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
'OPTIONS': {'min_length': 8}},
{'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator'},
{'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator'},
]
# Static files
STATIC_URL = '/static/'
STATICFILES_DIRS = [BASE_DIR / 'static']
+7
View File
@@ -43,6 +43,13 @@
<i class="bi bi-clock-history me-1"></i>变更记录
</a>
</li>
{% if user.is_superuser %}
<li class="nav-item">
<a class="nav-link {% if request.resolver_match.url_name == 'user_list' %}active{% endif %}" href="{% url 'user_list' %}">
<i class="bi bi-people me-1"></i>用户管理
</a>
</li>
{% endif %}
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">
<i class="bi bi-file-earmark-spreadsheet me-1"></i>导入导出
+113
View File
@@ -0,0 +1,113 @@
{% extends "assetapp/base.html" %}
{% block title %}用户管理{% endblock %}
{% block content %}
<div class="d-flex justify-content-between align-items-center mb-4">
<h4 class="mb-0"><i class="bi bi-people me-2"></i>用户管理</h4>
</div>
<div class="card card-dark mb-3">
<div class="card-body py-3">
<form method="get" class="row g-2 align-items-center">
<div class="col-md-4">
<div class="input-group input-group-sm">
<span class="input-group-text"><i class="bi bi-search"></i></span>
<input type="text" name="search" value="{{ search }}" class="form-control"
placeholder="搜索用户名 / 姓名 / 邮箱">
</div>
</div>
<div class="col-md-3">
<select name="is_active" class="form-select form-select-sm">
<option value="">全部状态</option>
<option value="1" {% if current_is_active == '1' %}selected{% endif %}>正常</option>
<option value="0" {% if current_is_active == '0' %}selected{% endif %}>已禁用</option>
</select>
</div>
<div class="col-md-2">
<button type="submit" class="btn btn-primary btn-sm w-100">
<i class="bi bi-funnel me-1"></i>筛选
</button>
</div>
</form>
</div>
</div>
<div class="card card-dark">
<div class="card-body p-0">
<div class="table-responsive">
<table class="table table-dark table-hover mb-0 align-middle">
<thead>
<tr>
<th>ID</th>
<th>用户名</th>
<th>姓名</th>
<th>邮箱</th>
<th>角色</th>
<th>状态</th>
<th>最后登录</th>
<th>加入时间</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{% for u in page_obj %}
<tr>
<td>{{ u.id }}</td>
<td><strong>{{ u.username }}</strong></td>
<td>{{ u.first_name|default:"-" }}</td>
<td>{{ u.email|default:"-" }}</td>
<td>
{% if u.is_superuser %}
<span class="badge bg-danger">超级管理员</span>
{% elif u.is_staff %}
<span class="badge bg-info">管理员</span>
{% else %}
<span class="badge bg-secondary">普通用户</span>
{% endif %}
</td>
<td>
{% if u.is_active %}
<span class="badge bg-success">正常</span>
{% else %}
<span class="badge bg-secondary">已禁用</span>
{% endif %}
</td>
<td>{{ u.last_login|date:"Y-m-d H:i"|default:"-" }}</td>
<td>{{ u.date_joined|date:"Y-m-d" }}</td>
<td>
<a href="{% url 'admin_password_reset' u.pk %}"
class="btn btn-outline-warning btn-xs" title="重置密码">
<i class="bi bi-key"></i> 重置密码
</a>
</td>
</tr>
{% empty %}
<tr><td colspan="9" class="text-center text-muted py-4">暂无用户</td></tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
{% if page_obj.paginator.num_pages > 1 %}
<nav class="mt-3">
<ul class="pagination pagination-sm justify-content-center">
{% if page_obj.has_previous %}
<li class="page-item">
<a class="page-link" href="?page={{ page_obj.previous_page_number }}&search={{ search }}&is_active={{ current_is_active }}">上一页</a>
</li>
{% endif %}
<li class="page-item active">
<span class="page-link">{{ page_obj.number }} / {{ page_obj.paginator.num_pages }}</span>
</li>
{% if page_obj.has_next %}
<li class="page-item">
<a class="page-link" href="?page={{ page_obj.next_page_number }}&search={{ search }}&is_active={{ current_is_active }}">下一页</a>
</li>
{% endif %}
</ul>
</nav>
{% endif %}
{% endblock %}
@@ -0,0 +1,63 @@
{% extends "assetapp/base.html" %}
{% block title %}重置密码 - {{ target_user.username }}{% endblock %}
{% block content %}
<div class="d-flex align-items-center mb-4">
<a href="{% url 'user_list' %}" class="btn btn-outline-secondary btn-sm me-3">
<i class="bi bi-arrow-left"></i> 返回
</a>
<h4 class="mb-0">
<i class="bi bi-key me-2"></i>重置密码 - {{ target_user.username }}
</h4>
</div>
<div class="row justify-content-center">
<div class="col-md-6">
<div class="card card-dark">
<div class="card-body">
<div class="alert alert-warning py-2 small">
<i class="bi bi-exclamation-triangle me-1"></i>
您正在为用户 <strong>{{ target_user.username }}</strong> 设置新密码,设置后该用户需使用新密码登录。
</div>
<form method="post">
{% csrf_token %}
{% if form.non_field_errors %}
<div class="alert alert-danger py-2 small">{{ form.non_field_errors }}</div>
{% endif %}
<div class="mb-3">
<label class="form-label text-muted" for="{{ form.new_password1.id_for_label }}">
新密码 <span class="text-danger">*</span>
</label>
{{ form.new_password1 }}
{% if form.new_password1.help_text %}
<div class="form-text text-muted">{{ form.new_password1.help_text|safe }}</div>
{% endif %}
{% if form.new_password1.errors %}
<div class="text-danger small mt-1">{{ form.new_password1.errors }}</div>
{% endif %}
</div>
<div class="mb-3">
<label class="form-label text-muted" for="{{ form.new_password2.id_for_label }}">
确认新密码 <span class="text-danger">*</span>
</label>
{{ form.new_password2 }}
{% if form.new_password2.errors %}
<div class="text-danger small mt-1">{{ form.new_password2.errors }}</div>
{% endif %}
</div>
<button type="submit" class="btn btn-warning">
<i class="bi bi-check-circle me-1"></i>确认重置
</button>
<a href="{% url 'user_list' %}" class="btn btn-outline-secondary ms-2">取消</a>
</form>
</div>
</div>
</div>
</div>
{% endblock %}