mirror of
https://github.com/yangjian102621/geekai.git
synced 2025-09-18 01:06:39 +08:00
feat: API Key manage is ready
This commit is contained in:
parent
469844d97b
commit
e490e15bc4
@ -8,10 +8,9 @@ import (
|
||||
"chatplus/store/vo"
|
||||
"chatplus/utils"
|
||||
"chatplus/utils/resp"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
"time"
|
||||
)
|
||||
|
||||
type ApiKeyHandler struct {
|
||||
@ -25,38 +24,50 @@ func NewApiKeyHandler(app *core.AppServer, db *gorm.DB) *ApiKeyHandler {
|
||||
return &h
|
||||
}
|
||||
|
||||
func (h *ApiKeyHandler) Add(c *gin.Context) {
|
||||
func (h *ApiKeyHandler) Save(c *gin.Context) {
|
||||
var data struct {
|
||||
Key string
|
||||
Id uint `json:"id"`
|
||||
UserId uint `json:"user_id"`
|
||||
Value string `json:"value"`
|
||||
LastUsedAt string `json:"last_used_at"`
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&data); err != nil {
|
||||
resp.ERROR(c, types.InvalidArgs)
|
||||
return
|
||||
}
|
||||
// 获取当前登录用户
|
||||
var userId uint = 0
|
||||
user, err := utils.GetLoginUser(c, h.db)
|
||||
if err == nil {
|
||||
userId = user.Id
|
||||
|
||||
apiKey := model.ApiKey{Value: data.Value, UserId: data.UserId, LastUsedAt: utils.Str2stamp(data.LastUsedAt)}
|
||||
apiKey.Id = data.Id
|
||||
if apiKey.Id > 0 {
|
||||
apiKey.CreatedAt = time.Unix(data.CreatedAt, 0)
|
||||
}
|
||||
var key = model.ApiKey{Value: data.Key, UserId: userId}
|
||||
res := h.db.Create(&key)
|
||||
res := h.db.Save(&apiKey)
|
||||
if res.Error != nil {
|
||||
c.JSON(http.StatusOK, types.BizVo{Code: types.Failed, Message: "操作失败"})
|
||||
resp.ERROR(c, "更新数据库失败!")
|
||||
return
|
||||
}
|
||||
resp.SUCCESS(c, key)
|
||||
|
||||
var keyVo vo.ApiKey
|
||||
err := utils.CopyObject(apiKey, &keyVo)
|
||||
if err != nil {
|
||||
resp.ERROR(c, "数据拷贝失败!")
|
||||
return
|
||||
}
|
||||
keyVo.Id = apiKey.Id
|
||||
keyVo.CreatedAt = apiKey.CreatedAt.Unix()
|
||||
resp.SUCCESS(c, keyVo)
|
||||
}
|
||||
|
||||
func (h *ApiKeyHandler) List(c *gin.Context) {
|
||||
page := h.GetInt(c, "page", 1)
|
||||
pageSize := h.GetInt(c, "page_size", 20)
|
||||
offset := (page - 1) * pageSize
|
||||
userId := h.GetInt(c, "user_id", -1)
|
||||
query := h.db.Debug().Session(&gorm.Session{})
|
||||
if userId >= 0 {
|
||||
query = query.Where("user_id", userId)
|
||||
}
|
||||
var items []model.ApiKey
|
||||
var keys = make([]vo.ApiKey, 0)
|
||||
var total int64
|
||||
h.db.Model(&model.ApiKey{}).Count(&total)
|
||||
res := h.db.Offset(offset).Limit(pageSize).Find(&items)
|
||||
res := query.Find(&items)
|
||||
if res.Error == nil {
|
||||
for _, item := range items {
|
||||
var key vo.ApiKey
|
||||
@ -71,6 +82,18 @@ func (h *ApiKeyHandler) List(c *gin.Context) {
|
||||
}
|
||||
}
|
||||
}
|
||||
pageVo := vo.NewPage(total, page, pageSize, keys)
|
||||
resp.SUCCESS(c, pageVo)
|
||||
resp.SUCCESS(c, keys)
|
||||
}
|
||||
|
||||
func (h *ApiKeyHandler) Remove(c *gin.Context) {
|
||||
id := h.GetInt(c, "id", 0)
|
||||
|
||||
if id > 0 {
|
||||
res := h.db.Where("id = ?", id).Delete(&model.ApiKey{})
|
||||
if res.Error != nil {
|
||||
resp.ERROR(c, "更新数据库失败!")
|
||||
return
|
||||
}
|
||||
}
|
||||
resp.SUCCESS(c)
|
||||
}
|
||||
|
@ -24,8 +24,8 @@ func NewChatRoleHandler(app *core.AppServer, db *gorm.DB) *ChatRoleHandler {
|
||||
return &h
|
||||
}
|
||||
|
||||
// Update 更新某个聊天角色信息,这里只允许更改名称以及启用和禁用角色操作
|
||||
func (h *ChatRoleHandler) Update(c *gin.Context) {
|
||||
// Save 创建或者更新某个角色
|
||||
func (h *ChatRoleHandler) Save(c *gin.Context) {
|
||||
var data vo.ChatRole
|
||||
if err := c.ShouldBindJSON(&data); err != nil {
|
||||
resp.ERROR(c, types.InvalidArgs)
|
||||
|
@ -128,8 +128,9 @@ func main() {
|
||||
}),
|
||||
fx.Invoke(func(s *core.AppServer, h *admin.ApiKeyHandler) {
|
||||
group := s.Engine.Group("/api/admin/apikey/")
|
||||
group.POST("add", h.Add)
|
||||
group.POST("save", h.Save)
|
||||
group.GET("list", h.List)
|
||||
group.GET("remove", h.Remove)
|
||||
}),
|
||||
fx.Invoke(func(s *core.AppServer, h *admin.UserHandler) {
|
||||
group := s.Engine.Group("/api/admin/user/")
|
||||
@ -141,7 +142,7 @@ func main() {
|
||||
fx.Invoke(func(s *core.AppServer, h *admin.ChatRoleHandler) {
|
||||
group := s.Engine.Group("/api/admin/role/")
|
||||
group.GET("list", h.List)
|
||||
group.POST("update", h.Update)
|
||||
group.POST("save", h.Save)
|
||||
group.POST("sort", h.SetSort)
|
||||
group.GET("remove", h.Remove)
|
||||
}),
|
||||
|
@ -123,4 +123,8 @@ export function renderInputText(text) {
|
||||
// 拷贝对象
|
||||
export function copyObj(origin) {
|
||||
return JSON.parse(JSON.stringify(origin));
|
||||
}
|
||||
|
||||
export function disabledDate(time) {
|
||||
return time.getTime() < Date.now()
|
||||
}
|
@ -84,6 +84,9 @@
|
||||
<el-tab-pane label="角色管理" name="role" v-if="arrayContains(tabs, 'role')">
|
||||
<role-list v-if="curTab==='role'"/>
|
||||
</el-tab-pane>
|
||||
<el-tab-pane label="API KEY" name="apikey" v-if="arrayContains(tabs, 'apikey')">
|
||||
<api-key v-if="curTab==='apikey'"/>
|
||||
</el-tab-pane>
|
||||
</el-tabs>
|
||||
</div>
|
||||
</div>
|
||||
@ -104,6 +107,7 @@ import RoleList from "@/views/admin/RoleList.vue";
|
||||
import {httpGet} from "@/utils/http";
|
||||
import {ElMessage} from "element-plus";
|
||||
import {useRouter} from "vue-router";
|
||||
import ApiKey from "@/views/admin/ApiKey.vue";
|
||||
|
||||
const title = ref('Chat-Plus 控制台')
|
||||
const logo = ref('images/logo.png')
|
||||
@ -126,6 +130,12 @@ const navs = ref([
|
||||
title: '角色管理',
|
||||
tab: 'role',
|
||||
active: false,
|
||||
},
|
||||
{
|
||||
id: 4,
|
||||
title: 'API KEY',
|
||||
tab: 'apikey',
|
||||
active: false,
|
||||
}
|
||||
])
|
||||
const tabs = ref([])
|
||||
|
171
web/src/views/admin/ApiKey.vue
Normal file
171
web/src/views/admin/ApiKey.vue
Normal file
@ -0,0 +1,171 @@
|
||||
<template>
|
||||
<div class="list" v-loading="loading">
|
||||
<el-row class="opt-box">
|
||||
<el-button type="primary" @click="add">
|
||||
<el-icon>
|
||||
<Plus/>
|
||||
</el-icon>
|
||||
新增角色
|
||||
</el-button>
|
||||
</el-row>
|
||||
|
||||
<el-row>
|
||||
<el-table :data="items" :row-key="row => row.id">
|
||||
<el-table-column prop="value" label="API KEY"/>
|
||||
|
||||
<el-table-column label="创建时间">
|
||||
<template #default="scope">
|
||||
<span>{{ dateFormat(scope.row['created_at']) }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
|
||||
<el-table-column label="最后使用时间">
|
||||
<template #default="scope">
|
||||
<span v-if="scope.row['last_used_at']">{{ scope.row['last_used_at'] }}</span>
|
||||
<el-tag v-else>未使用</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
|
||||
<el-table-column label="操作" width="180">
|
||||
<template #default="scope">
|
||||
<el-button size="small" type="primary" @click="edit(scope.row)">编辑</el-button>
|
||||
<el-popconfirm title="确定要删除当前记录吗?" @confirm="remove(scope.row)">
|
||||
<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="编辑 API KEY"
|
||||
style="width: 90%; max-width: 600px;"
|
||||
>
|
||||
<el-form :model="item" label-width="120px" ref="formRef" :rules="rules">
|
||||
<el-form-item label="API KEY:" prop="nickname">
|
||||
<el-input v-model="item.value" autocomplete="off"/>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="最后使用时间:" prop="last_used_at">
|
||||
<el-date-picker
|
||||
v-model="item.last_used_at"
|
||||
type="datetime"
|
||||
placeholder="选择日期"
|
||||
format="YYYY-MM-DD HH:mm:ss"
|
||||
value-format="YYYY-MM-DD HH:mm:ss"
|
||||
:disabled-date="disabledDate"
|
||||
/>
|
||||
</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 {reactive, ref} from "vue";
|
||||
import {httpGet, httpPost} from "@/utils/http";
|
||||
import {ElMessage} from "element-plus";
|
||||
import {dateFormat, disabledDate, removeArrayItem} from "@/utils/libs";
|
||||
import {Plus} from "@element-plus/icons-vue";
|
||||
|
||||
// 变量定义
|
||||
const items = ref([])
|
||||
const item = ref({})
|
||||
const showDialog = ref(false)
|
||||
const rules = reactive({
|
||||
key: [{required: true, message: '请输入 API KEY', trigger: 'change',}]
|
||||
})
|
||||
const loading = ref(true)
|
||||
const formRef = ref(null)
|
||||
|
||||
// 获取数据
|
||||
httpGet('/api/admin/apikey/list?user_id=0').then((res) => {
|
||||
if (res.data) {
|
||||
// 初始化数据
|
||||
const arr = res.data;
|
||||
for (let i = 0; i < arr.length; i++) {
|
||||
arr[i].last_used_at = dateFormat(arr[i].last_used_at)
|
||||
}
|
||||
items.value = arr
|
||||
}
|
||||
loading.value = false
|
||||
}).catch(() => {
|
||||
ElMessage.error("获取数据失败");
|
||||
})
|
||||
|
||||
const add = function () {
|
||||
showDialog.value = true
|
||||
item.value = {}
|
||||
}
|
||||
|
||||
const edit = function (row) {
|
||||
showDialog.value = true
|
||||
item.value = row
|
||||
}
|
||||
|
||||
const save = function () {
|
||||
formRef.value.validate((valid) => {
|
||||
if (valid) {
|
||||
showDialog.value = false
|
||||
httpPost('/api/admin/apikey/save', item.value).then((res) => {
|
||||
ElMessage.success('操作成功!')
|
||||
if (!item.id) {
|
||||
const newItem = res.data
|
||||
newItem.last_used_at = dateFormat(newItem.last_used_at)
|
||||
items.value.push(newItem)
|
||||
}
|
||||
}).catch((e) => {
|
||||
ElMessage.error('操作失败,' + e.message)
|
||||
})
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const remove = function (row) {
|
||||
httpGet('/api/admin/apikey/remove?id=' + row.id).then(() => {
|
||||
ElMessage.success("删除成功!")
|
||||
item.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;
|
||||
|
||||
.el-icon {
|
||||
margin-right: 5px;
|
||||
}
|
||||
}
|
||||
|
||||
.pagination {
|
||||
padding-top 20px;
|
||||
display flex
|
||||
justify-content center
|
||||
width 100%
|
||||
}
|
||||
|
||||
.el-select {
|
||||
width: 100%
|
||||
}
|
||||
|
||||
}
|
||||
</style>
|
@ -140,7 +140,7 @@
|
||||
<template #footer>
|
||||
<span class="dialog-footer">
|
||||
<el-button @click="showDialog = false">取消</el-button>
|
||||
<el-button type="primary" @click="doUpdate">保存</el-button>
|
||||
<el-button type="primary" @click="save">保存</el-button>
|
||||
</span>
|
||||
</template>
|
||||
</el-dialog>
|
||||
@ -245,11 +245,11 @@ const addRole = function () {
|
||||
showDialog.value = true
|
||||
}
|
||||
|
||||
const doUpdate = function () {
|
||||
const save = function () {
|
||||
formRef.value.validate((valid) => {
|
||||
if (valid) {
|
||||
showDialog.value = false
|
||||
httpPost('/api/admin/role/update', role.value).then((res) => {
|
||||
httpPost('/api/admin/role/save', role.value).then((res) => {
|
||||
ElMessage.success('操作成功')
|
||||
// 更新当前数据行
|
||||
if (role.value.id) {
|
||||
|
@ -14,7 +14,7 @@
|
||||
</el-table-column>
|
||||
<el-table-column label="过期时间">
|
||||
<template #default="scope">
|
||||
<span v-if="scope.row['expired_time'] > 0">{{ dateFormat(scope.row['expired_time']) }}</span>
|
||||
<span v-if="scope.row['expired_time']">{{ scope.row['expired_time'] }}</span>
|
||||
<el-tag v-else>长期有效</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
@ -40,7 +40,7 @@
|
||||
v-model:current-page="users.page"
|
||||
v-model:page-size="users.page_size"
|
||||
@update:current-change="fetchUserList(users.page, users.page_size)"
|
||||
:page-count="users.total_page"/>
|
||||
:total="users.total"/>
|
||||
|
||||
</div>
|
||||
</el-row>
|
||||
@ -105,7 +105,7 @@
|
||||
import {nextTick, onMounted, reactive, ref} from "vue";
|
||||
import {httpGet, httpPost} from "@/utils/http";
|
||||
import {ElMessage, ElMessageBox} from "element-plus";
|
||||
import {dateFormat, removeArrayItem} from "@/utils/libs";
|
||||
import {dateFormat, disabledDate, removeArrayItem} from "@/utils/libs";
|
||||
|
||||
// 变量定义
|
||||
const users = ref({})
|
||||
@ -141,16 +141,19 @@ onMounted(() => {
|
||||
|
||||
const fetchUserList = function (page, pageSize) {
|
||||
httpGet('/api/admin/user/list', {page: page, page_size: pageSize}).then((res) => {
|
||||
users.value = res.data;
|
||||
if (res.data) {
|
||||
// 初始化数据
|
||||
const arr = res.data.items;
|
||||
for (let i = 0; i < arr.length; i++) {
|
||||
arr[i].expired_time = dateFormat(arr[i].expired_time)
|
||||
}
|
||||
users.value.items = arr
|
||||
}
|
||||
}).catch(() => {
|
||||
ElMessage.error('加载用户列表失败')
|
||||
})
|
||||
}
|
||||
|
||||
const disabledDate = (time) => {
|
||||
return time.getTime() < Date.now()
|
||||
}
|
||||
|
||||
// 删除用户
|
||||
const removeUser = function (user) {
|
||||
ElMessageBox.confirm(
|
||||
@ -179,7 +182,6 @@ const removeUser = function (user) {
|
||||
}
|
||||
|
||||
const userEdit = function (_user) {
|
||||
_user.expired_time = dateFormat(_user.expired_time)
|
||||
user.value = _user
|
||||
showUserEditDialog.value = true
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user