修改登录,添加超级管理员权限

This commit is contained in:
dxc
2026-02-25 11:02:06 +08:00
parent 948149cd44
commit 1c3f116c50
5 changed files with 180 additions and 109 deletions

View File

@ -2,19 +2,27 @@
from app.extensions import db
from werkzeug.security import generate_password_hash, check_password_hash
from datetime import datetime
from sqlalchemy.sql import func
class SysUser(db.Model):
"""
系统用户表
对应数据库: sys_user
"""
__tablename__ = 'sys_user'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(100), nullable=False)
# 注意:如果允许邮箱为空,建议去掉 unique=True 或者在数据库层面处理空字符串
email = db.Column(db.String(100), unique=True)
department = db.Column(db.String(100))
role = db.Column(db.String(50))
role = db.Column(db.String(50)) # 存储 UserRole 的值,如 'SUPER_ADMIN'
status = db.Column(db.String(20), default='active')
password_hash = db.Column(db.Text)
created_at = db.Column(db.DateTime, default=datetime.now) # 新增创建时间
# [关键] 对应数据库的 created_at 字段
# 如果数据库报错 column not found请务必执行 SQL: ALTER TABLE sys_user ADD COLUMN created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP;
created_at = db.Column(db.DateTime, server_default=func.now(), default=datetime.now)
def set_password(self, password):
"""生成加密密码"""
@ -36,6 +44,7 @@ class SysUser(db.Model):
'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else ''
}
class SysLog(db.Model):
"""
系统操作日志表

View File

@ -3,10 +3,11 @@ from app.models.system import SysUser
from app.extensions import db
from flask_jwt_extended import create_access_token
from app.utils.constants import UserRole
from datetime import timedelta # [修改点1] 引入 timedelta 用于设置过期时间
from datetime import timedelta
class AuthService:
# 硬编码的超级管理员凭证
# 硬编码的“初始”超级管理员凭证 (用于系统初始化或数据库被锁死时)
SUPER_ADMIN_USER = "IRIS"
SUPER_ADMIN_PASS = "licahk"
@ -19,20 +20,22 @@ class AuthService:
user_id = None
user_info = {}
# 1. 优先检查硬编码的超级管理员
# 1. 优先检查硬编码的超级管理员 (IRIS)
if username == AuthService.SUPER_ADMIN_USER:
if password == AuthService.SUPER_ADMIN_PASS:
# 显式指定角色为 SUPER_ADMIN
user_role = UserRole.SUPER_ADMIN
user_id = 0 # 虚拟ID
user_id = 0 # 虚拟ID区分于数据库ID
user_info = {
'username': username,
'role': user_role,
'department': 'System'
'department': 'System',
'status': 'active'
}
else:
raise ValueError("密码错误")
# 2. 如果不是 IRIS,检查数据库用户
# 2. 如果不是硬编码用户,检查数据库用户
else:
user = SysUser.query.filter_by(username=username).first()
@ -49,8 +52,7 @@ class AuthService:
user_id = user.id
user_info = user.to_dict()
# 3. 生成 Token
# [修改点2] 增加 expires_delta 参数,设置为 7 天(可根据需要修改为 days=1 或 days=30
# 3. 生成 Token (设置为7天过期)
access_token = create_access_token(
identity=user_id,
additional_claims={'role': user_role, 'username': username},
@ -65,18 +67,31 @@ class AuthService:
@staticmethod
def create_user(data, operator_role):
"""
创建新用户 (仅限管理员使用)
创建新用户
权限控制:只有超级管理员(SUPER_ADMIN) 或 主管(SUPERVISOR) 可以创建
"""
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('__')]
# 验证角色合法性
# [核心修复] 过滤掉 __开头的属性 和 ROLE_MAP 字典,只保留字符串类型的角色定义
valid_roles = [
v for k, v in UserRole.__dict__.items()
if not k.startswith('__') and isinstance(v, str)
]
if role not in valid_roles:
raise Exception(f"角色无效,可选角色: {valid_roles}")
raise Exception(f"角色无效")
# 如果操作者只是 SUPERVISOR (主管),不允许他创建 SUPER_ADMIN (超管)
if operator_role == UserRole.SUPERVISOR and role == UserRole.SUPER_ADMIN:
raise Exception("权限不足:主管无法创建超级管理员")
email = data.get('email', '')
if email and SysUser.query.filter_by(email=email).first():
@ -99,8 +114,9 @@ class AuthService:
@staticmethod
def update_user(user_id, data, operator_role):
"""
[新增] 更新用户信息
更新用户信息
"""
# 权限校验
if operator_role not in [UserRole.SUPER_ADMIN, UserRole.SUPERVISOR]:
raise Exception("权限不足:只有超级管理员或主管可以修改用户信息")
@ -108,18 +124,30 @@ class AuthService:
if not user:
raise Exception("用户不存在")
# 1. 更新基本信息
# 1. 更新角色 (Role)
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']
# [核心修复] 同样添加类型检查
valid_roles = [
v for k, v in UserRole.__dict__.items()
if not k.startswith('__') and isinstance(v, str)
]
new_role = data['role']
if new_role not in valid_roles:
raise Exception(f"角色无效")
# 防止主管把自己或其他用户提升为超管
if operator_role == UserRole.SUPERVISOR and new_role == UserRole.SUPER_ADMIN:
raise Exception("权限不足:主管无法分配超级管理员权限")
user.role = new_role
# 2. 更新部门
if 'department' in data:
user.department = data['department']
# 3. 更新邮箱
if 'email' in data:
# 如果修改了邮箱,且新邮箱已被其他人使用
email = data['email']
if email and email != user.email:
existing = SysUser.query.filter_by(email=email).first()
@ -127,7 +155,11 @@ class AuthService:
raise Exception("该邮箱已被其他用户使用")
user.email = email
# 2. 如果提供了密码,则重置密码;否则保持原密码
# 4. 更新状态 (Status) - 例如禁用用户
if 'status' in data:
user.status = data['status']
# 5. 更新密码
new_password = data.get('password')
if new_password and str(new_password).strip():
if len(new_password) < 6:
@ -140,14 +172,16 @@ class AuthService:
@staticmethod
def get_all_users():
"""获取所有系统用户"""
# 按照 ID 倒序排列
users = SysUser.query.order_by(SysUser.id.desc()).all()
return [user.to_dict() for user in users]
@staticmethod
def delete_user(user_id, operator_role):
"""删除用户"""
if operator_role not in [UserRole.SUPER_ADMIN, UserRole.SUPERVISOR]:
raise Exception("权限不足")
# 只有超级管理员可以执行物理删除
if operator_role != UserRole.SUPER_ADMIN:
raise Exception("权限不足:只有超级管理员可以删除用户,建议使用禁用功能")
user = SysUser.query.get(user_id)
if not user:

View File

@ -1,16 +1,20 @@
# app/utils/constants.py
class UserRole:
SUPER_ADMIN = 'super_admin' # 超级管理员 (IRIS)
SUPERVISOR = 'supervisor' # 主管
FINANCE = 'finance' # 财务
WAREHOUSE_MGR = 'warehouse_manager' # 库管
INBOUND = 'inbound' # 入库员
OUTBOUND = 'outbound' # 出库员
PURCHASER = 'purchaser' # 采购员
SALES = 'sales' # 销售
"""
用户角色定义
"""
SUPER_ADMIN = 'SUPER_ADMIN' # 超级管理员 (IRIS)
SUPERVISOR = 'SUPERVISOR' # 主管
FINANCE = 'FINANCE' # 财务
WAREHOUSE_MGR = 'WAREHOUSE_MGR' # 库管
INBOUND = 'INBOUND' # 入库员
OUTBOUND = 'OUTBOUND' # 出库员
PURCHASER = 'PURCHASER' # 采购员
SALES = 'SALES' # 销售
# 角色中文映射(用于前端展示或日志)
# 注意:这个字典在 auth_service 遍历时需要被过滤掉
ROLE_MAP = {
SUPER_ADMIN: '超级管理员',
SUPERVISOR: '主管',

View File

@ -4,6 +4,16 @@ import Layout from '@/layout/index.vue'
import { useUserStore } from '@/stores/user'
import BomManage from '@/views/bom/BomManage.vue'
// [新增] 扩展 RouteMeta 类型定义,防止 TS 报错
declare module 'vue-router' {
interface RouteMeta {
title?: string
icon?: string
hidden?: boolean
roles?: string[] // 允许的角色列表
}
}
const routes: Array<RouteRecordRaw> = [
// 1. 登录页
{
@ -169,17 +179,25 @@ const routes: Array<RouteRecordRaw> = [
{
path: '/system',
component: Layout,
// [修复] 添加 redirect点击父菜单时跳转到子页面
redirect: '/system/user-create',
meta: {
title: '系统管理',
icon: 'Setting',
roles: ['super_admin', 'supervisor']
// [修复] 使用大写角色名,匹配后端常量
roles: ['SUPER_ADMIN', 'SUPERVISOR']
},
children: [
{
path: 'user-create',
name: 'UserCreate',
component: () => import('@/views/system/UserCreate.vue'),
meta: { title: '账号开通', icon: 'User' }
meta: {
title: '账号开通',
icon: 'User',
// 子路由也建议加上权限限制
roles: ['SUPER_ADMIN', 'SUPERVISOR']
}
}
]
},
@ -204,7 +222,16 @@ router.beforeEach((to, from, next) => {
const userStore = useUserStore()
const token = userStore.token || localStorage.getItem('token')
const userRole = userStore.role || localStorage.getItem('role') || 'user'
// [修复] 优先从 user 对象获取,并统一转大写,防止大小写不一致导致权限失效
// 注意Store 中存储的可能是 user.role 或者直接是 role根据你之前的 store 结构适配
const rawRole = userStore.user?.role || userStore.role || localStorage.getItem('role') || 'user'
const userRole = String(rawRole).toUpperCase()
// 调试日志:如果跳转有问题,请按 F12 查看控制台输出
if (to.path.includes('/system')) {
console.log(`路由守卫检查: Path=${to.path}, UserRole=${userRole}, Required=${to.meta.roles}`)
}
if (to.path === '/login') {
if (token) {
@ -220,10 +247,13 @@ router.beforeEach((to, from, next) => {
return
}
// 权限检查逻辑
if (to.meta.roles && Array.isArray(to.meta.roles)) {
// [修复] to.meta.roles 里已经是大写了userRole 也转大写了,现在可以安全比对
if (to.meta.roles.includes(userRole)) {
next()
} else {
console.warn(`权限不足: 用户角色 ${userRole} 不在允许列表 ${to.meta.roles}`)
next('/dashboard')
}
} else {
@ -231,4 +261,4 @@ router.beforeEach((to, from, next) => {
}
})
export default router
export default router

View File

@ -17,42 +17,26 @@
style="width: 100%"
>
<el-table-column prop="username" label="用户名" width="150" />
<el-table-column prop="department" label="所属部门" width="150">
<template #default="scope">
<el-tag>{{ scope.row.department }}</el-tag>
</template>
</el-table-column>
<el-table-column prop="role" label="系统角色" width="180">
<template #default="scope">
{{ formatRole(scope.row.role) }}
</template>
</el-table-column>
<el-table-column prop="email" label="邮箱" min-width="200" />
<el-table-column prop="created_at" label="创建时间" width="180">
<template #default="scope">
{{ formatDate(scope.row.created_at) }}
</template>
</el-table-column>
<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)"
>
<el-button link type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
<el-popconfirm title="确定要删除该用户吗?" @confirm="handleDelete(scope.row)">
<template #reference>
<el-button link type="danger" size="small">删除</el-button>
</template>
@ -82,10 +66,7 @@
/>
</el-form-item>
<el-form-item
label="密码"
prop="password"
>
<el-form-item label="密码" prop="password">
<el-input
v-model="form.password"
type="password"
@ -103,24 +84,18 @@
allow-create
default-first-option
>
<el-option
v-for="item in departmentOptions"
:key="item"
:label="item"
:value="item"
/>
<el-option v-for="item in departmentOptions" :key="item" :label="item" :value="item" />
</el-select>
</el-form-item>
<el-form-item label="系统角色" prop="role">
<el-select v-model="form.role" placeholder="授予权限" style="width: 100%">
<el-option label="主管" value="supervisor" />
<el-option label="财务" value="finance" />
<el-option label="库管" value="warehouse_manager" />
<el-option label="入库员" value="inbound" />
<el-option label="出库员" value="outbound" />
<el-option label="采购员" value="purchaser" />
<el-option label="销售" value="sales" />
<el-option
v-for="option in roleOptions"
:key="option.value"
:label="option.label"
:value="option.value"
/>
</el-select>
</el-form-item>
@ -144,9 +119,11 @@
<script setup lang="ts">
import { reactive, ref, onMounted, computed } from 'vue'
import { createUser, updateUser, getUserList, deleteUser } from '@/api/auth'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
// --- 状态定义 ---
const userStore = useUserStore()
const tableLoading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
@ -154,7 +131,6 @@ const tableData = ref<any[]>([])
const departmentOptions = ref<string[]>([])
const formRef = ref()
// [新增] 区分编辑/创建模式
const isEdit = ref(false)
const currentId = ref<number | null>(null)
@ -166,20 +142,52 @@ const form = reactive({
email: ''
})
// [关键] 动态规则:编辑模式下密码不是必填项
// [核心逻辑] 角色选项列表 (保留了之前的强力判断逻辑,但去除了 debug 变量)
const roleOptions = computed(() => {
const options = [
{ label: '主管', value: 'SUPERVISOR' },
{ label: '财务', value: 'FINANCE' },
{ label: '库管', value: 'WAREHOUSE_MGR' },
{ label: '入库员', value: 'INBOUND' },
{ label: '出库员', value: 'OUTBOUND' },
{ label: '采购员', value: 'PURCHASER' },
{ label: '销售', value: 'SALES' }
]
// 1. 尝试从 Pinia Store 获取信息
let role = userStore.user?.role || userStore.role
let username = userStore.user?.username || userStore.name
// 2. 如果 Store 没数据,尝试从 LocalStorage 补救
if (!role) role = localStorage.getItem('role')
if (!username) username = localStorage.getItem('username')
// 3. 统一转大写
const safeRole = role ? String(role).toUpperCase() : ''
const safeUsername = username ? String(username).toUpperCase() : ''
// 4. [关键] 只要是 IRIS 或者 角色包含 ADMIN就开启上帝模式
const isSuperAdmin = (safeRole === 'SUPER_ADMIN') || (safeUsername === 'IRIS')
if (isSuperAdmin) {
options.unshift({ label: '超级管理员', value: 'SUPER_ADMIN' })
}
return options
})
// 验证规则
const rules = computed(() => {
const commonRules = {
const commonRules: any = {
username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
role: [{ required: true, message: '请选择角色', trigger: 'change' }],
department: [{ required: true, message: '请输入或选择部门', trigger: ['blur', 'change'] }],
// [新增] 邮箱必填校验规则
email: [
{ required: true, message: '请输入邮箱', trigger: 'blur' },
{ type: 'email', message: '请输入正确的邮箱格式', trigger: ['blur', 'change'] }
]
}
// 如果是创建模式,密码必填
if (!isEdit.value) {
return {
...commonRules,
@ -189,7 +197,6 @@ const rules = computed(() => {
]
}
} else {
// 如果是编辑模式,密码选填(只有输入了才校验长度)
return {
...commonRules,
password: [
@ -226,51 +233,47 @@ const extractDepartments = (data: any[]) => {
departmentOptions.value = Array.from(deptSet)
}
// 2. 打开新增弹窗
const handleCreate = () => {
isEdit.value = false
currentId.value = null
resetFormState() // 清空数据
form.username = ''
form.password = ''
form.department = ''
form.role = ''
form.email = ''
if (formRef.value) formRef.value.clearValidate()
dialogVisible.value = true
}
// [新增] 打开编辑弹窗
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 = '' // 编辑时不回显密码,留空表示不修改
form.password = ''
if (formRef.value) formRef.value.clearValidate()
dialogVisible.value = true
}
// 3. 提交 (兼容创建和修改)
const onSubmit = async () => {
if (!formRef.value) return
await formRef.value.validate(async (valid: boolean) => {
if (valid) {
submitLoading.value = true
try {
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) {
// 错误已处理
// request 拦截器会处理错误
} finally {
submitLoading.value = false
}
@ -278,14 +281,9 @@ const onSubmit = async () => {
})
}
// 4. 重置表单
const resetForm = () => {
if (!formRef.value) return
formRef.value.resetFields()
resetFormState()
}
const resetFormState = () => {
form.username = ''
form.password = ''
form.department = ''
@ -293,19 +291,15 @@ const resetFormState = () => {
form.email = ''
}
// 5. 删除用户
const handleDelete = async (row: any) => {
try {
await deleteUser(row.id)
ElMessage.success('删除成功')
getList()
} catch (error) {
// 错误处理
}
}
// --- 辅助显示方法 ---
const formatDate = (dateStr: string) => {
if (!dateStr) return '-'
return dateStr.replace('T', ' ').substring(0, 19)
@ -313,19 +307,19 @@ const formatDate = (dateStr: string) => {
const formatRole = (val: string) => {
const map: Record<string, string> = {
'supervisor': '主管',
'finance': '财务',
'warehouse_manager': '库管',
'inbound': '入库员',
'outbound': '库员',
'purchaser': '采购员',
'sales': '销售',
'super_admin': '超级管理员'
'SUPER_ADMIN': '超级管理员',
'SUPERVISOR': '主管',
'FINANCE': '财务',
'WAREHOUSE_MGR': '库管',
'INBOUND': '库员',
'OUTBOUND': '出库员',
'PURCHASER': '采购员',
'SALES': '销售'
}
return map[val] || val
const key = val ? val.toUpperCase() : ''
return map[key] || val
}
// --- 初始化 ---
onMounted(() => {
getList()
})