mirror of
https://github.com/yangjian102621/geekai.git
synced 2025-09-17 08:46:38 +08:00
feat: add manager list page in console page
This commit is contained in:
parent
dece19cec6
commit
ec6186596d
@ -186,6 +186,9 @@ func authorizeMiddleware(s *AppServer, client *redis.Client) gin.HandlerFunc {
|
||||
}
|
||||
|
||||
key := fmt.Sprintf("users/%v", claims["user_id"])
|
||||
if isAdminApi {
|
||||
key = fmt.Sprintf("admin/%v", claims["user_id"])
|
||||
}
|
||||
if _, err := client.Get(context.Background(), key).Result(); err != nil && needLogin(c) {
|
||||
resp.NotAuth(c, "Token is not found in redis")
|
||||
c.Abort()
|
||||
|
@ -6,9 +6,11 @@ import (
|
||||
"chatplus/handler"
|
||||
logger2 "chatplus/logger"
|
||||
"chatplus/store/model"
|
||||
"chatplus/store/vo"
|
||||
"chatplus/utils"
|
||||
"chatplus/utils/resp"
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/go-redis/redis/v8"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/mojocn/base64Captcha"
|
||||
@ -28,6 +30,8 @@ type Manager struct {
|
||||
CaptchaId string `json:"captcha_id"` // 验证码id
|
||||
}
|
||||
|
||||
const SuperManagerID = 1
|
||||
|
||||
type ManagerHandler struct {
|
||||
handler.BaseHandler
|
||||
redis *redis.Client
|
||||
@ -64,14 +68,14 @@ func (h *ManagerHandler) Login(c *gin.Context) {
|
||||
}
|
||||
|
||||
// 超级管理员默认是ID:1
|
||||
if manager.Id != 1 && manager.Status == false {
|
||||
if manager.Id != SuperManagerID && manager.Status == false {
|
||||
resp.ERROR(c, "该用户已被禁止登录,请联系超级管理员")
|
||||
return
|
||||
}
|
||||
|
||||
// 创建 token
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
|
||||
"user_id": manager.Username,
|
||||
"user_id": manager.Id,
|
||||
"expired": time.Now().Add(time.Second * time.Duration(h.App.Config.Session.MaxAge)).Unix(),
|
||||
})
|
||||
tokenString, err := token.SignedString([]byte(h.App.Config.AdminSession.SecretKey))
|
||||
@ -80,7 +84,7 @@ func (h *ManagerHandler) Login(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
// 保存到 redis
|
||||
key := "users/" + manager.Username
|
||||
key := fmt.Sprintf("admin/%d", manager.Id)
|
||||
if _, err := h.redis.Set(context.Background(), key, tokenString, 0).Result(); err != nil {
|
||||
resp.ERROR(c, "error with save token: "+err.Error())
|
||||
return
|
||||
@ -89,7 +93,7 @@ func (h *ManagerHandler) Login(c *gin.Context) {
|
||||
// 更新最后登录时间和IP
|
||||
manager.LastLoginIp = c.ClientIP()
|
||||
manager.LastLoginAt = time.Now().Unix()
|
||||
h.DB.Model(&manager).Updates(manager)
|
||||
h.DB.Updates(&manager)
|
||||
|
||||
var result = struct {
|
||||
IsSuperAdmin bool `json:"is_super_admin"`
|
||||
@ -114,10 +118,155 @@ func (h *ManagerHandler) Logout(c *gin.Context) {
|
||||
|
||||
// Session 会话检测
|
||||
func (h *ManagerHandler) Session(c *gin.Context) {
|
||||
token := c.GetHeader(types.AdminAuthHeader)
|
||||
if token == "" {
|
||||
id := h.GetLoginUserId(c)
|
||||
key := fmt.Sprintf("admin/%d", id)
|
||||
if _, err := h.redis.Get(context.Background(), key).Result(); err != nil {
|
||||
resp.NotAuth(c)
|
||||
} else {
|
||||
resp.SUCCESS(c)
|
||||
return
|
||||
}
|
||||
var manager model.AdminUser
|
||||
res := h.DB.Where("id", id).First(&manager)
|
||||
if res.Error != nil {
|
||||
resp.NotAuth(c)
|
||||
return
|
||||
}
|
||||
|
||||
resp.SUCCESS(c, manager)
|
||||
}
|
||||
|
||||
// List 数据列表
|
||||
func (h *ManagerHandler) List(c *gin.Context) {
|
||||
var items []model.AdminUser
|
||||
res := h.DB.Find(&items)
|
||||
if res.Error != nil {
|
||||
resp.ERROR(c, res.Error.Error())
|
||||
return
|
||||
}
|
||||
|
||||
users := make([]vo.AdminUser, 0)
|
||||
for _, item := range items {
|
||||
var u vo.AdminUser
|
||||
err := utils.CopyObject(item, &u)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
u.Id = item.Id
|
||||
u.CreatedAt = item.CreatedAt.Unix()
|
||||
users = append(users, u)
|
||||
}
|
||||
|
||||
resp.SUCCESS(c, users)
|
||||
|
||||
}
|
||||
|
||||
func (h *ManagerHandler) Save(c *gin.Context) {
|
||||
var data struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
Status bool `json:"status"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&data); err != nil {
|
||||
resp.ERROR(c, types.InvalidArgs)
|
||||
return
|
||||
}
|
||||
|
||||
var user model.AdminUser
|
||||
res := h.DB.Where("username", data.Username).First(&user)
|
||||
if res.Error == nil {
|
||||
resp.ERROR(c, "用户名已存在")
|
||||
return
|
||||
}
|
||||
|
||||
// 生成密码
|
||||
salt := utils.RandString(8)
|
||||
password := utils.GenPassword(data.Password, salt)
|
||||
res = h.DB.Save(&model.AdminUser{
|
||||
Username: data.Username,
|
||||
Password: password,
|
||||
Salt: salt,
|
||||
Status: data.Status,
|
||||
})
|
||||
if res.Error != nil {
|
||||
resp.ERROR(c, "failed with update database")
|
||||
return
|
||||
}
|
||||
|
||||
resp.SUCCESS(c)
|
||||
}
|
||||
|
||||
// Remove 删除管理员
|
||||
func (h *ManagerHandler) Remove(c *gin.Context) {
|
||||
id := h.GetInt(c, "id", 0)
|
||||
if id <= 0 {
|
||||
resp.ERROR(c, types.InvalidArgs)
|
||||
return
|
||||
}
|
||||
|
||||
if id == SuperManagerID {
|
||||
resp.ERROR(c, "超级管理员不能删除")
|
||||
return
|
||||
}
|
||||
|
||||
res := h.DB.Where("id", id).Delete(&model.AdminUser{})
|
||||
if res.Error != nil {
|
||||
resp.ERROR(c, res.Error.Error())
|
||||
return
|
||||
}
|
||||
|
||||
resp.SUCCESS(c)
|
||||
}
|
||||
|
||||
// Enable 启用/禁用
|
||||
func (h *ManagerHandler) Enable(c *gin.Context) {
|
||||
var data struct {
|
||||
Id uint `json:"id"`
|
||||
Enabled bool `json:"enabled"`
|
||||
}
|
||||
|
||||
if err := c.ShouldBindJSON(&data); err != nil {
|
||||
resp.ERROR(c, types.InvalidArgs)
|
||||
return
|
||||
}
|
||||
|
||||
res := h.DB.Model(&model.AdminUser{}).Where("id", data.Id).UpdateColumn("status", data.Enabled)
|
||||
if res.Error != nil {
|
||||
resp.ERROR(c, res.Error.Error())
|
||||
return
|
||||
}
|
||||
resp.SUCCESS(c)
|
||||
}
|
||||
|
||||
// ResetPass 重置密码
|
||||
func (h *ManagerHandler) ResetPass(c *gin.Context) {
|
||||
id := h.GetLoginUserId(c)
|
||||
if id != SuperManagerID {
|
||||
resp.ERROR(c, "只有超级管理员能够进行该操作")
|
||||
return
|
||||
}
|
||||
|
||||
var data struct {
|
||||
Id int `json:"id"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&data); err != nil {
|
||||
resp.ERROR(c, types.InvalidArgs)
|
||||
return
|
||||
}
|
||||
|
||||
var user model.AdminUser
|
||||
res := h.DB.Where("id", data.Id).First(&user)
|
||||
if res.Error != nil {
|
||||
resp.ERROR(c, res.Error.Error())
|
||||
return
|
||||
}
|
||||
|
||||
password := utils.GenPassword(data.Password, user.Salt)
|
||||
user.Password = password
|
||||
res = h.DB.Updates(&user)
|
||||
if res.Error != nil {
|
||||
resp.ERROR(c, res.Error.Error())
|
||||
return
|
||||
}
|
||||
|
||||
resp.SUCCESS(c)
|
||||
}
|
||||
|
@ -108,7 +108,7 @@ func (h *ProductHandler) Enable(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
res := h.DB.Model(&model.Product{}).Where("id = ?", data.Id).Update("enabled", data.Enabled)
|
||||
res := h.DB.Model(&model.Product{}).Where("id", data.Id).UpdateColumn("enabled", data.Enabled)
|
||||
if res.Error != nil {
|
||||
resp.ERROR(c, "更新数据库失败!")
|
||||
return
|
||||
|
@ -274,6 +274,11 @@ func main() {
|
||||
group.POST("login", h.Login)
|
||||
group.GET("logout", h.Logout)
|
||||
group.GET("session", h.Session)
|
||||
group.GET("list", h.List)
|
||||
group.POST("save", h.Save)
|
||||
group.POST("enable", h.Enable)
|
||||
group.GET("remove", h.Remove)
|
||||
group.POST("resetPass", h.ResetPass)
|
||||
}),
|
||||
fx.Invoke(func(s *core.AppServer, h *admin.ApiKeyHandler) {
|
||||
group := s.Engine.Group("/api/admin/apikey/")
|
||||
|
@ -121,6 +121,11 @@ const items = [
|
||||
index: '/admin/chats',
|
||||
title: '对话管理',
|
||||
},
|
||||
{
|
||||
icon: 'role',
|
||||
index: '/admin/manger',
|
||||
title: '管理员',
|
||||
},
|
||||
{
|
||||
icon: 'config',
|
||||
index: '/admin/system',
|
||||
|
@ -168,6 +168,12 @@ const routes = [
|
||||
meta: {title: '算力日志'},
|
||||
component: () => import('@/views/admin/PowerLog.vue'),
|
||||
},
|
||||
{
|
||||
path: '/admin/manger',
|
||||
name: 'admin-manger',
|
||||
meta: {title: '管理员'},
|
||||
component: () => import('@/views/admin/Manager.vue'),
|
||||
},
|
||||
]
|
||||
},
|
||||
|
||||
|
@ -80,6 +80,8 @@ httpGet('/api/admin/dashboard/stats').then((res) => {
|
||||
|
||||
<style scoped lang="stylus">
|
||||
.dashboard {
|
||||
padding 20px
|
||||
|
||||
.grid-content {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
188
web/src/views/admin/Manager.vue
Normal file
188
web/src/views/admin/Manager.vue
Normal file
@ -0,0 +1,188 @@
|
||||
<template>
|
||||
<div class="container list" v-loading="loading">
|
||||
|
||||
<div class="handle-box">
|
||||
<el-button type="primary" :icon="Plus" @click="add">新增</el-button>
|
||||
</div>
|
||||
|
||||
<el-row>
|
||||
<el-table :data="items" :row-key="row => row.id" table-layout="auto">
|
||||
<el-table-column prop="username" label="用户名"/>
|
||||
<el-table-column prop="last_login_ip" label="最后登录IP"/>
|
||||
|
||||
<el-table-column label="最后登录时间">
|
||||
<template #default="scope">
|
||||
<span>{{ dateFormat(scope.row['last_login_at']) }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="enabled" label="启用状态">
|
||||
<template #default="scope">
|
||||
<el-switch v-model="scope.row['status']" @change="enable(scope.row)"/>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="创建时间">
|
||||
<template #default="scope">
|
||||
<span>{{ dateFormat(scope.row['created_at']) }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
|
||||
<el-table-column label="操作" width="180">
|
||||
<template #default="scope">
|
||||
<el-button size="small" type="primary" @click="resetPass(scope.row)">重置密码</el-button>
|
||||
<el-popconfirm title="确定要删除当前记录吗?" @confirm="remove(scope.row)" :width="200">
|
||||
<template #reference>
|
||||
<el-button size="small" type="danger">删除</el-button>
|
||||
</template>
|
||||
</el-popconfirm>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
</el-row>
|
||||
|
||||
<el-dialog
|
||||
v-model="showDialog"
|
||||
title="添加用户"
|
||||
:close-on-click-modal="false"
|
||||
>
|
||||
<el-form :model="item" label-width="120px" ref="formRef" :rules="rules">
|
||||
<el-form-item label="用户名:" prop="username">
|
||||
<el-input v-model="item.username" autocomplete="off"/>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="密码:" prop="password">
|
||||
<el-input v-model="item.password" type="password" autocomplete="off"/>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="重复密码:" prop="repass">
|
||||
<el-input v-model="item.repass" type="password" autocomplete="off"/>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
|
||||
<template #footer>
|
||||
<span class="dialog-footer">
|
||||
<el-button @click="showDialog = false">取消</el-button>
|
||||
<el-button type="primary" @click="save">提交</el-button>
|
||||
</span>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import {onMounted, reactive, ref} from "vue";
|
||||
import {httpGet, httpPost} from "@/utils/http";
|
||||
import {ElMessage, ElMessageBox} from "element-plus";
|
||||
import {dateFormat, removeArrayItem} from "@/utils/libs";
|
||||
import {Plus} from "@element-plus/icons-vue";
|
||||
import {Sortable} from "sortablejs";
|
||||
|
||||
// 变量定义
|
||||
const items = ref([])
|
||||
const item = ref({})
|
||||
const showDialog = ref(false)
|
||||
const title = ref("")
|
||||
const loading = ref(true)
|
||||
const formRef = ref(null)
|
||||
|
||||
const rules = reactive({
|
||||
username: [{required: true, message: '请输入用户名', trigger: 'change',}],
|
||||
password: [{required: true, message: '请输入密码', trigger: 'change',}],
|
||||
repass: [{required: true, message: '请再次输入密码', trigger: 'change',}],
|
||||
})
|
||||
|
||||
// 获取数据
|
||||
const fetchData = () => {
|
||||
httpGet('/api/admin/list').then((res) => {
|
||||
items.value = res.data
|
||||
loading.value = false
|
||||
}).catch(() => {
|
||||
ElMessage.error("获取数据失败");
|
||||
})
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
fetchData()
|
||||
})
|
||||
|
||||
const add = function () {
|
||||
showDialog.value = true
|
||||
item.value = {}
|
||||
}
|
||||
|
||||
// 重置密码
|
||||
const resetPass = function (row) {
|
||||
ElMessageBox.prompt('请输入新密码', '重置密码', {
|
||||
confirmButtonText: '确认',
|
||||
cancelButtonText: '取消',
|
||||
}).then(({value}) => {
|
||||
httpPost("/api/admin/resetPass", {
|
||||
id: row.id,
|
||||
password: value
|
||||
}).then(() => {
|
||||
ElMessage.success("操作成功")
|
||||
}).catch(e => {
|
||||
ElMessage.error("操作失败:" + e.message)
|
||||
})
|
||||
|
||||
}).catch(() => {
|
||||
})
|
||||
}
|
||||
|
||||
const save = function () {
|
||||
formRef.value.validate((valid) => {
|
||||
if (item.value.password !== item.value.repass) {
|
||||
return ElMessage.error("两次输入密码不一致!")
|
||||
}
|
||||
if (valid) {
|
||||
showDialog.value = false
|
||||
httpPost('/api/admin/save', item.value).then((res) => {
|
||||
ElMessage.success('操作成功!')
|
||||
fetchData()
|
||||
}).catch((e) => {
|
||||
ElMessage.error('操作失败,' + e.message)
|
||||
})
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const enable = (row) => {
|
||||
httpPost('/api/admin/enable', {id: row.id, enabled: row.status}).then(() => {
|
||||
ElMessage.success("操作成功!")
|
||||
}).catch(e => {
|
||||
ElMessage.error("操作失败:" + e.message)
|
||||
})
|
||||
}
|
||||
|
||||
const remove = function (row) {
|
||||
httpGet('/api/admin/remove?id=' + row.id).then(() => {
|
||||
ElMessage.success("删除成功!")
|
||||
items.value = removeArrayItem(items.value, row, (v1, v2) => {
|
||||
return v1.id === v2.id
|
||||
})
|
||||
}).catch((e) => {
|
||||
ElMessage.error("删除失败:" + e.message)
|
||||
})
|
||||
}
|
||||
</script>
|
||||
|
||||
<style lang="stylus" scoped>
|
||||
.list {
|
||||
|
||||
.opt-box {
|
||||
padding-bottom: 10px;
|
||||
display flex;
|
||||
justify-content flex-end
|
||||
|
||||
.el-icon {
|
||||
margin-right: 5px;
|
||||
}
|
||||
}
|
||||
|
||||
.el-select {
|
||||
width: 100%
|
||||
}
|
||||
|
||||
}
|
||||
</style>
|
@ -51,7 +51,6 @@
|
||||
v-model="showDialog"
|
||||
:title="title"
|
||||
:close-on-click-modal="false"
|
||||
style="width: 90%; max-width: 600px;"
|
||||
>
|
||||
<el-form :model="item" label-width="120px" ref="formRef" :rules="rules">
|
||||
<el-form-item label="产品名称:" prop="name">
|
||||
|
Loading…
Reference in New Issue
Block a user