进入界面的调整
This commit is contained in:
@ -16,7 +16,6 @@ def login():
|
||||
if not data.get('username') or not data.get('password'):
|
||||
return jsonify({'msg': '请输入用户名和密码'}), 400
|
||||
|
||||
# 调用 Service 层逻辑
|
||||
result = AuthService.login(data)
|
||||
|
||||
response_data = {
|
||||
@ -24,15 +23,11 @@ def login():
|
||||
'access_token': result.get('access_token'),
|
||||
'user': result.get('user')
|
||||
}
|
||||
|
||||
return jsonify(response_data), 200
|
||||
|
||||
except ValueError as ve:
|
||||
# [修改] 捕获业务逻辑错误(如密码错误、用户不存在),返回 401 Unauthorized
|
||||
return jsonify({'msg': str(ve)}), 401
|
||||
|
||||
except Exception as e:
|
||||
# [修改] 捕获系统级错误(如数据库连接失败),返回 500 Internal Server Error
|
||||
current_app.logger.error(f"Login Failed Error: {str(e)}")
|
||||
return jsonify({'msg': f'服务器内部错误: {str(e)}'}), 500
|
||||
|
||||
@ -53,12 +48,27 @@ def create_user():
|
||||
return jsonify({'msg': str(e)}), 400
|
||||
|
||||
|
||||
# [新增] 获取用户列表
|
||||
# [新增] 更新用户
|
||||
@auth_bp.route('/user/<int:user_id>', methods=['PUT'])
|
||||
@jwt_required()
|
||||
def update_user(user_id):
|
||||
try:
|
||||
data = request.get_json()
|
||||
claims = get_jwt()
|
||||
operator_role = claims.get('role')
|
||||
|
||||
result = AuthService.update_user(user_id, data, operator_role)
|
||||
return jsonify({'msg': '用户更新成功', 'data': result}), 200
|
||||
|
||||
except Exception as e:
|
||||
current_app.logger.error(f"User Update Failed: {str(e)}")
|
||||
return jsonify({'msg': str(e)}), 400
|
||||
|
||||
|
||||
@auth_bp.route('/users', methods=['GET'])
|
||||
@jwt_required()
|
||||
def get_users():
|
||||
try:
|
||||
# 这里可以添加分页逻辑,目前先返回所有
|
||||
users = AuthService.get_all_users()
|
||||
return jsonify({'msg': '获取成功', 'data': users}), 200
|
||||
except Exception as e:
|
||||
@ -66,7 +76,6 @@ def get_users():
|
||||
return jsonify({'msg': '获取用户列表失败'}), 500
|
||||
|
||||
|
||||
# [新增] 删除用户
|
||||
@auth_bp.route('/user/<int:user_id>', methods=['DELETE'])
|
||||
@jwt_required()
|
||||
def delete_user(user_id):
|
||||
|
||||
@ -30,14 +30,12 @@ class AuthService:
|
||||
'department': 'System'
|
||||
}
|
||||
else:
|
||||
# [修改] 使用 ValueError 表示认证失败
|
||||
raise ValueError("密码错误")
|
||||
|
||||
# 2. 如果不是 IRIS,检查数据库用户
|
||||
else:
|
||||
user = SysUser.query.filter_by(username=username).first()
|
||||
|
||||
# [修改] 分开判断,逻辑更清晰,且使用 ValueError
|
||||
if not user:
|
||||
raise ValueError("用户不存在")
|
||||
|
||||
@ -67,21 +65,17 @@ class AuthService:
|
||||
"""
|
||||
创建新用户 (仅限管理员使用)
|
||||
"""
|
||||
# 简单权限控制:只有超级管理员或主管可以创建用户
|
||||
if operator_role not in [UserRole.SUPER_ADMIN, UserRole.SUPERVISOR]:
|
||||
raise Exception("权限不足:只有超级管理员或主管可以创建新用户")
|
||||
|
||||
# 检查重名
|
||||
if SysUser.query.filter_by(username=data.get('username')).first():
|
||||
raise Exception("用户名已存在")
|
||||
|
||||
# 默认角色处理
|
||||
role = data.get('role')
|
||||
valid_roles = [v for k, v in UserRole.__dict__.items() if not k.startswith('__')]
|
||||
if role not in valid_roles:
|
||||
raise Exception(f"角色无效,可选角色: {valid_roles}")
|
||||
|
||||
# 处理 Email 为空的情况
|
||||
email = data.get('email', '')
|
||||
if email and SysUser.query.filter_by(email=email).first():
|
||||
raise Exception("邮箱已被使用")
|
||||
@ -100,6 +94,47 @@ class AuthService:
|
||||
|
||||
return new_user.to_dict()
|
||||
|
||||
@staticmethod
|
||||
def update_user(user_id, data, operator_role):
|
||||
"""
|
||||
[新增] 更新用户信息
|
||||
"""
|
||||
if operator_role not in [UserRole.SUPER_ADMIN, UserRole.SUPERVISOR]:
|
||||
raise Exception("权限不足:只有超级管理员或主管可以修改用户信息")
|
||||
|
||||
user = SysUser.query.get(user_id)
|
||||
if not user:
|
||||
raise Exception("用户不存在")
|
||||
|
||||
# 1. 更新基本信息
|
||||
if 'role' in data:
|
||||
valid_roles = [v for k, v in UserRole.__dict__.items() if not k.startswith('__')]
|
||||
if data['role'] not in valid_roles:
|
||||
raise Exception(f"角色无效")
|
||||
user.role = data['role']
|
||||
|
||||
if 'department' in data:
|
||||
user.department = data['department']
|
||||
|
||||
if 'email' in data:
|
||||
# 如果修改了邮箱,且新邮箱已被其他人使用
|
||||
email = data['email']
|
||||
if email and email != user.email:
|
||||
existing = SysUser.query.filter_by(email=email).first()
|
||||
if existing:
|
||||
raise Exception("该邮箱已被其他用户使用")
|
||||
user.email = email
|
||||
|
||||
# 2. 如果提供了密码,则重置密码;否则保持原密码
|
||||
new_password = data.get('password')
|
||||
if new_password and str(new_password).strip():
|
||||
if len(new_password) < 6:
|
||||
raise Exception("密码长度至少6位")
|
||||
user.set_password(new_password)
|
||||
|
||||
db.session.commit()
|
||||
return user.to_dict()
|
||||
|
||||
@staticmethod
|
||||
def get_all_users():
|
||||
"""获取所有系统用户"""
|
||||
|
||||
@ -18,6 +18,15 @@ export function createUser(data: any) {
|
||||
})
|
||||
}
|
||||
|
||||
// [新增] 更新用户
|
||||
export function updateUser(id: number, data: any) {
|
||||
return request({
|
||||
url: `/v1/auth/user/${id}`,
|
||||
method: 'put',
|
||||
data
|
||||
})
|
||||
}
|
||||
|
||||
// 获取当前登录用户信息
|
||||
export function getUserInfo() {
|
||||
return request({
|
||||
@ -26,7 +35,7 @@ export function getUserInfo() {
|
||||
})
|
||||
}
|
||||
|
||||
// [新增] 获取所有用户列表
|
||||
// 获取所有用户列表
|
||||
export function getUserList() {
|
||||
return request({
|
||||
url: '/v1/auth/users',
|
||||
@ -34,7 +43,7 @@ export function getUserList() {
|
||||
})
|
||||
}
|
||||
|
||||
// [新增] 删除用户
|
||||
// 删除用户
|
||||
export function deleteUser(id: number) {
|
||||
return request({
|
||||
url: `/v1/auth/user/${id}`,
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
<el-card class="welcome-card">
|
||||
<template #header>
|
||||
<div class="card-header">
|
||||
<span class="title">👋 欢迎回来,Admin</span>
|
||||
<span class="title">👋 欢迎回来,{{ userStore.username }}</span>
|
||||
<el-tag type="success">系统运行正常</el-tag>
|
||||
</div>
|
||||
</template>
|
||||
@ -35,10 +35,14 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { useRouter } from 'vue-router'
|
||||
// 1. 引入 User Store
|
||||
import { useUserStore } from '@/stores/user'
|
||||
// 引入需要的图标
|
||||
import { Box, TrendCharts, ShoppingCart, Operation } from '@element-plus/icons-vue'
|
||||
|
||||
const router = useRouter()
|
||||
// 2. 实例化 store
|
||||
const userStore = useUserStore()
|
||||
|
||||
// 统一跳转函数
|
||||
const handleNav = (path: string) => {
|
||||
|
||||
@ -38,8 +38,17 @@
|
||||
</template>
|
||||
</el-table-column>
|
||||
|
||||
<el-table-column label="操作" width="150" fixed="right">
|
||||
<el-table-column label="操作" width="180" fixed="right">
|
||||
<template #default="scope">
|
||||
<el-button
|
||||
link
|
||||
type="primary"
|
||||
size="small"
|
||||
@click="handleEdit(scope.row)"
|
||||
>
|
||||
编辑
|
||||
</el-button>
|
||||
|
||||
<el-popconfirm
|
||||
title="确定要删除该用户吗?此操作无法撤销。"
|
||||
@confirm="handleDelete(scope.row)"
|
||||
@ -55,7 +64,7 @@
|
||||
|
||||
<el-dialog
|
||||
v-model="dialogVisible"
|
||||
title="新增员工账号"
|
||||
:title="isEdit ? '编辑员工账号' : '新增员工账号'"
|
||||
width="500px"
|
||||
@close="resetForm"
|
||||
>
|
||||
@ -66,15 +75,22 @@
|
||||
label-width="100px"
|
||||
>
|
||||
<el-form-item label="用户名" prop="username">
|
||||
<el-input v-model="form.username" placeholder="登录账号 (英文)" />
|
||||
<el-input
|
||||
v-model="form.username"
|
||||
placeholder="登录账号 (英文)"
|
||||
:disabled="isEdit"
|
||||
/>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="初始密码" prop="password">
|
||||
<el-form-item
|
||||
label="密码"
|
||||
prop="password"
|
||||
>
|
||||
<el-input
|
||||
v-model="form.password"
|
||||
type="password"
|
||||
show-password
|
||||
placeholder="设置初始密码"
|
||||
:placeholder="isEdit ? '不修改请留空' : '设置初始密码'"
|
||||
/>
|
||||
</el-form-item>
|
||||
|
||||
@ -117,7 +133,7 @@
|
||||
<div class="dialog-footer">
|
||||
<el-button @click="dialogVisible = false">取消</el-button>
|
||||
<el-button type="primary" @click="onSubmit" :loading="submitLoading">
|
||||
确认创建
|
||||
{{ isEdit ? '确认修改' : '确认创建' }}
|
||||
</el-button>
|
||||
</div>
|
||||
</template>
|
||||
@ -126,8 +142,8 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { reactive, ref, onMounted } from 'vue'
|
||||
import { createUser, getUserList, deleteUser } from '@/api/auth'
|
||||
import { reactive, ref, onMounted, computed } from 'vue'
|
||||
import { createUser, updateUser, getUserList, deleteUser } from '@/api/auth'
|
||||
import { ElMessage } from 'element-plus'
|
||||
|
||||
// --- 状态定义 ---
|
||||
@ -135,9 +151,13 @@ const tableLoading = ref(false)
|
||||
const submitLoading = ref(false)
|
||||
const dialogVisible = ref(false)
|
||||
const tableData = ref<any[]>([])
|
||||
const departmentOptions = ref<string[]>([]) // 部门下拉选项
|
||||
const departmentOptions = ref<string[]>([])
|
||||
const formRef = ref()
|
||||
|
||||
// [新增] 区分编辑/创建模式
|
||||
const isEdit = ref(false)
|
||||
const currentId = ref<number | null>(null)
|
||||
|
||||
const form = reactive({
|
||||
username: '',
|
||||
password: '',
|
||||
@ -146,28 +166,42 @@ const form = reactive({
|
||||
email: ''
|
||||
})
|
||||
|
||||
const rules = {
|
||||
username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
|
||||
password: [
|
||||
{ required: true, message: '请输入密码', trigger: 'blur' },
|
||||
{ min: 6, message: '密码至少6位', trigger: 'blur' }
|
||||
],
|
||||
role: [{ required: true, message: '请选择角色', trigger: 'change' }],
|
||||
department: [{ required: true, message: '请输入或选择部门', trigger: ['blur', 'change'] }]
|
||||
}
|
||||
// [关键] 动态规则:编辑模式下密码不是必填项
|
||||
const rules = computed(() => {
|
||||
const commonRules = {
|
||||
username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
|
||||
role: [{ required: true, message: '请选择角色', trigger: 'change' }],
|
||||
department: [{ required: true, message: '请输入或选择部门', trigger: ['blur', 'change'] }]
|
||||
}
|
||||
|
||||
// 如果是创建模式,密码必填
|
||||
if (!isEdit.value) {
|
||||
return {
|
||||
...commonRules,
|
||||
password: [
|
||||
{ required: true, message: '请输入密码', trigger: 'blur' },
|
||||
{ min: 6, message: '密码至少6位', trigger: 'blur' }
|
||||
]
|
||||
}
|
||||
} else {
|
||||
// 如果是编辑模式,密码选填(只有输入了才校验长度)
|
||||
return {
|
||||
...commonRules,
|
||||
password: [
|
||||
{ min: 6, message: '密码至少6位', trigger: 'blur' }
|
||||
]
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// --- 逻辑方法 ---
|
||||
|
||||
// 1. 获取用户列表
|
||||
const getList = async () => {
|
||||
tableLoading.value = true
|
||||
try {
|
||||
const res = await getUserList()
|
||||
tableData.value = res.data || []
|
||||
|
||||
// 获取数据后,提取已有的部门作为选项
|
||||
extractDepartments(tableData.value)
|
||||
|
||||
} catch (error) {
|
||||
console.error('Fetch users failed:', error)
|
||||
} finally {
|
||||
@ -175,31 +209,42 @@ const getList = async () => {
|
||||
}
|
||||
}
|
||||
|
||||
// 【关键修改】提取部门:没有任何预设值,完全依赖数据库
|
||||
const extractDepartments = (data: any[]) => {
|
||||
// 1. 创建一个空的 Set,不放任何默认值
|
||||
const deptSet = new Set<string>()
|
||||
|
||||
// 2. 遍历数据库返回的数据,收集已有的部门
|
||||
if (data && data.length > 0) {
|
||||
data.forEach(user => {
|
||||
// 只有当部门字段不为空时才添加
|
||||
if (user.department && user.department.trim() !== '') {
|
||||
deptSet.add(user.department)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// 3. 转为数组供下拉框使用
|
||||
departmentOptions.value = Array.from(deptSet)
|
||||
}
|
||||
|
||||
// 2. 打开新增弹窗
|
||||
const handleCreate = () => {
|
||||
isEdit.value = false
|
||||
currentId.value = null
|
||||
resetFormState() // 清空数据
|
||||
dialogVisible.value = true
|
||||
}
|
||||
|
||||
// 3. 提交创建
|
||||
// [新增] 打开编辑弹窗
|
||||
const handleEdit = (row: any) => {
|
||||
isEdit.value = true
|
||||
currentId.value = row.id
|
||||
|
||||
// 回填数据
|
||||
form.username = row.username
|
||||
form.department = row.department
|
||||
form.role = row.role
|
||||
form.email = row.email || ''
|
||||
form.password = '' // 编辑时不回显密码,留空表示不修改
|
||||
|
||||
dialogVisible.value = true
|
||||
}
|
||||
|
||||
// 3. 提交 (兼容创建和修改)
|
||||
const onSubmit = async () => {
|
||||
if (!formRef.value) return
|
||||
|
||||
@ -207,10 +252,18 @@ const onSubmit = async () => {
|
||||
if (valid) {
|
||||
submitLoading.value = true
|
||||
try {
|
||||
await createUser(form)
|
||||
ElMessage.success(`用户 ${form.username} 创建成功!`)
|
||||
dialogVisible.value = false // 关闭弹窗
|
||||
getList() // 刷新列表,如果你刚才输入了新部门,刷新后它就会出现在下拉框里
|
||||
if (isEdit.value && currentId.value) {
|
||||
// 编辑逻辑
|
||||
await updateUser(currentId.value, form)
|
||||
ElMessage.success(`用户 ${form.username} 修改成功!`)
|
||||
} else {
|
||||
// 创建逻辑
|
||||
await createUser(form)
|
||||
ElMessage.success(`用户 ${form.username} 创建成功!`)
|
||||
}
|
||||
|
||||
dialogVisible.value = false
|
||||
getList()
|
||||
} catch (error) {
|
||||
// 错误已处理
|
||||
} finally {
|
||||
@ -224,6 +277,15 @@ const onSubmit = async () => {
|
||||
const resetForm = () => {
|
||||
if (!formRef.value) return
|
||||
formRef.value.resetFields()
|
||||
resetFormState()
|
||||
}
|
||||
|
||||
const resetFormState = () => {
|
||||
form.username = ''
|
||||
form.password = ''
|
||||
form.department = ''
|
||||
form.role = ''
|
||||
form.email = ''
|
||||
}
|
||||
|
||||
// 5. 删除用户
|
||||
@ -244,7 +306,6 @@ const formatDate = (dateStr: string) => {
|
||||
return dateStr.replace('T', ' ').substring(0, 19)
|
||||
}
|
||||
|
||||
// 角色保留翻译(因为后端通常存英文代码 code)
|
||||
const formatRole = (val: string) => {
|
||||
const map: Record<string, string> = {
|
||||
'supervisor': '主管',
|
||||
|
||||
Reference in New Issue
Block a user