mirror of
https://github.com/go-admin-team/go-admin.git
synced 2026-09-25 11:31:47 +00:00
Compare commits
92
Commits
v1.2.0-beta
...
v1.2.2
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
07cb061ea5 | ||
|
|
5078403569 | ||
|
|
5e3e16025c | ||
|
|
4b5b0507e9 | ||
|
|
ccd76445f2 | ||
|
|
706c72b973 | ||
|
|
22fb2b5d0b | ||
|
|
16775cee45 | ||
|
|
2195c89099 | ||
|
|
199fc180b7 | ||
|
|
55112db749 | ||
|
|
da4637d285 | ||
|
|
a68e58f93b | ||
|
|
c814439f93 | ||
|
|
cc34268791 | ||
|
|
b94acb62ca | ||
|
|
c851e82762 | ||
|
|
870b144557 | ||
|
|
ac5b10e6c0 | ||
|
|
e1965be2ab | ||
|
|
b931925f75 | ||
|
|
e53cc4a9b5 | ||
|
|
b40d376e25 | ||
|
|
52f42616a2 | ||
|
|
01c519e894 | ||
|
|
93feb4779e | ||
|
|
61bf06c49b | ||
|
|
8ef816c2a9 | ||
|
|
8705ad0436 | ||
|
|
c350c8e32a | ||
|
|
f2703f16d5 | ||
|
|
7a0fff117b | ||
|
|
209db87d05 | ||
|
|
d12b1b7384 | ||
|
|
21603d5a4c | ||
|
|
bd658d9f0b | ||
|
|
9e640cf422 | ||
|
|
d1d545b29c | ||
|
|
1e8544f1ce | ||
|
|
2ecabd1202 | ||
|
|
4741137c9a | ||
|
|
f4c5aacf32 | ||
|
|
72a95babe5 | ||
|
|
3b5ce7ffaf | ||
|
|
7db918c495 | ||
|
|
faa8de7dc2 | ||
|
|
68c51fb480 | ||
|
|
4fe68183ba | ||
|
|
918e5c2ce1 | ||
|
|
ce656bf7a1 | ||
|
|
4be26aa5d2 | ||
|
|
dd09f52343 | ||
|
|
606aa821d5 | ||
|
|
99acf0086f | ||
|
|
c9b073908e | ||
|
|
000cd1d07d | ||
|
|
ca8d1e7e33 | ||
|
|
bc648c3f2f | ||
|
|
677cdb7821 | ||
|
|
7e2e40df56 | ||
|
|
2c23ef8c6d | ||
|
|
dab93f16b0 | ||
|
|
43dd214a7e | ||
|
|
c0ac9a6397 | ||
|
|
78bb246390 | ||
|
|
029783a685 | ||
|
|
8460b3f385 | ||
|
|
f3e0e4dbc6 | ||
|
|
72a876f37a | ||
|
|
7d8a267da7 | ||
|
|
2fe2c96e82 | ||
|
|
fdbb76086e | ||
|
|
a8d5846483 | ||
|
|
a06bd289b3 | ||
|
|
6bc3e6c00b | ||
|
|
91f2adb340 | ||
|
|
21d217c42a | ||
|
|
50464dc6e6 | ||
|
|
bb07d90407 | ||
|
|
3d5a2ea9f7 | ||
|
|
ca4ed89536 | ||
|
|
9cab65af6a | ||
|
|
7bba9b44b5 | ||
|
|
fd27170946 | ||
|
|
c6735c4b1a | ||
|
|
106ca70acc | ||
|
|
e0f5a9ede2 | ||
|
|
ab28eea2f3 | ||
|
|
6f09ecca32 | ||
|
|
0b80ac635d | ||
|
|
31544ff1ae | ||
|
|
c2f593de48 |
+4
-1
@@ -1,4 +1,5 @@
|
||||
.idea
|
||||
.vscode
|
||||
static/uploadfile
|
||||
main.exe
|
||||
go-admin
|
||||
@@ -8,8 +9,10 @@ vendor
|
||||
config/settings.dev.yml
|
||||
go-admin
|
||||
common/middleware/demo.go
|
||||
config/settings.dev.b.yml
|
||||
config/settings.dev.*.yml
|
||||
config/settings.dev.*.yml.log
|
||||
temp/logs
|
||||
config/settings.dev.yml.log
|
||||
config/settings.b.dev.yml
|
||||
cmd/migrate/migration/version-local/*
|
||||
!cmd/migrate/migration/version-local/doc.go
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
</p>
|
||||
|
||||
|
||||
[English](https://github.com/wenjianzhang/go-admin/blob/master/README.en.md) | 简体中文
|
||||
[English](https://github.com/go-admin-team/go-admin/blob/master/README.en.md) | 简体中文
|
||||
|
||||
|
||||
##### 基于Gin + Vue + Element UI的前后端分离权限管理系统
|
||||
@@ -27,7 +27,7 @@
|
||||
|
||||
[在线文档国内](http://mydearzwj.gitee.io/go-admin-site/)
|
||||
|
||||
[前端项目](https://github.com/wenjianzhang/go-admin-ui)
|
||||
[前端项目](https://github.com/go-admin-team/go-admin-ui)
|
||||
|
||||
[视频教程](https://space.bilibili.com/565616721/channel/detail?cid=125737)
|
||||
|
||||
@@ -128,10 +128,10 @@ cd goadmin
|
||||
|
||||
```bash
|
||||
# 获取后端代码
|
||||
git clone https://github.com/wenjianzhang/go-admin.git
|
||||
git clone https://github.com/go-admin-team/go-admin.git
|
||||
|
||||
# 获取前端代码
|
||||
git clone https://github.com/wenjianzhang/go-admin-ui.git
|
||||
git clone https://github.com/go-admin-team/go-admin-ui.git
|
||||
|
||||
```
|
||||
|
||||
@@ -159,11 +159,11 @@ vi ./config/setting.yml
|
||||
#### 初始化数据库,以及服务启动
|
||||
```
|
||||
# 首次配置需要初始化数据库资源信息
|
||||
./go-admin init -c config/settings.yml -m dev
|
||||
./go-admin migrate -c config/settings.yml
|
||||
|
||||
|
||||
# 启动项目,也可以用IDE进行调试
|
||||
./go-admin server -c config/settings.yml -p 8000 -m dev
|
||||
./go-admin server -c config/settings.yml -p 8000
|
||||
|
||||
```
|
||||
|
||||
@@ -258,7 +258,7 @@ zhuqiyun LLL狐 星星之火 cjj770 Sam 唐*i 晓聪 aLong *渊 海马 魏镇坪
|
||||
|
||||
## 🔑 License
|
||||
|
||||
[MIT](https://github.com/wenjianzhang/go-admin/blob/master/LICENSE.md)
|
||||
[MIT](https://github.com/go-admin-team/go-admin/blob/master/LICENSE.md)
|
||||
|
||||
Copyright (c) 2020 wenjianzhang
|
||||
|
||||
|
||||
@@ -1,134 +0,0 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
)
|
||||
|
||||
// @Summary 登录日志列表
|
||||
// @Description 获取JSON
|
||||
// @Tags 登录日志
|
||||
// @Param status query string false "status"
|
||||
// @Param dictCode query string false "dictCode"
|
||||
// @Param dictType query string false "dictType"
|
||||
// @Param pageSize query int false "页条数"
|
||||
// @Param pageIndex query int false "页码"
|
||||
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/loginloglist [get]
|
||||
// @Security Bearer
|
||||
func GetLoginLogList(c *gin.Context) {
|
||||
var data models.LoginLog
|
||||
var err error
|
||||
var pageSize = 10
|
||||
var pageIndex = 1
|
||||
|
||||
size := c.Request.FormValue("pageSize")
|
||||
if size != "" {
|
||||
pageSize = tools.StrToInt(err, size)
|
||||
}
|
||||
|
||||
index := c.Request.FormValue("pageIndex")
|
||||
if index != "" {
|
||||
pageIndex = tools.StrToInt(err, index)
|
||||
}
|
||||
|
||||
data.Username = c.Request.FormValue("username")
|
||||
data.Status = c.Request.FormValue("status")
|
||||
data.Ipaddr = c.Request.FormValue("ipaddr")
|
||||
result, count, err := data.GetPage(pageSize, pageIndex)
|
||||
tools.HasError(err, "", -1)
|
||||
|
||||
var mp = make(map[string]interface{}, 3)
|
||||
mp["list"] = result
|
||||
mp["count"] = count
|
||||
mp["pageIndex"] = pageIndex
|
||||
mp["pageSize"] = pageSize
|
||||
|
||||
var res app.Response
|
||||
res.Data = mp
|
||||
c.JSON(http.StatusOK, res.ReturnOK())
|
||||
}
|
||||
|
||||
// @Summary 通过编码获取登录日志
|
||||
// @Description 获取JSON
|
||||
// @Tags 登录日志
|
||||
// @Param infoId path int true "infoId"
|
||||
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/loginlog/{infoId} [get]
|
||||
// @Security Bearer
|
||||
func GetLoginLog(c *gin.Context) {
|
||||
var LoginLog models.LoginLog
|
||||
LoginLog.InfoId, _ = tools.StringToInt(c.Param("infoId"))
|
||||
result, err := LoginLog.Get()
|
||||
tools.HasError(err, "抱歉未找到相关信息", -1)
|
||||
|
||||
var res app.Response
|
||||
res.Data = result
|
||||
c.JSON(http.StatusOK, res.ReturnOK())
|
||||
}
|
||||
|
||||
// @Summary 添加登录日志
|
||||
// @Description 获取JSON
|
||||
// @Tags 登录日志
|
||||
// @Accept application/json
|
||||
// @Product application/json
|
||||
// @Param data body models.LoginLog true "data"
|
||||
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
|
||||
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
|
||||
// @Router /api/v1/loginlog [post]
|
||||
// @Security Bearer
|
||||
func InsertLoginLog(c *gin.Context) {
|
||||
var data models.LoginLog
|
||||
err := c.BindWith(&data, binding.JSON)
|
||||
tools.HasError(err, "", 500)
|
||||
result, err := data.Create()
|
||||
tools.HasError(err, "", -1)
|
||||
var res app.Response
|
||||
res.Data = result
|
||||
c.JSON(http.StatusOK, res.ReturnOK())
|
||||
}
|
||||
|
||||
// @Summary 修改登录日志
|
||||
// @Description 获取JSON
|
||||
// @Tags 登录日志
|
||||
// @Accept application/json
|
||||
// @Product application/json
|
||||
// @Param data body models.LoginLog true "body"
|
||||
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
|
||||
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
|
||||
// @Router /api/v1/loginlog [put]
|
||||
// @Security Bearer
|
||||
func UpdateLoginLog(c *gin.Context) {
|
||||
var data models.LoginLog
|
||||
err := c.BindWith(&data, binding.JSON)
|
||||
tools.HasError(err, "", -1)
|
||||
result, err := data.Update(data.InfoId)
|
||||
tools.HasError(err, "", -1)
|
||||
var res app.Response
|
||||
res.Data = result
|
||||
c.JSON(http.StatusOK, res.ReturnOK())
|
||||
}
|
||||
|
||||
// @Summary 批量删除登录日志
|
||||
// @Description 删除数据
|
||||
// @Tags 登录日志
|
||||
// @Param infoId path string true "以逗号(,)分割的infoId"
|
||||
// @Success 200 {string} string "{"code": 200, "message": "删除成功"}"
|
||||
// @Success 200 {string} string "{"code": -1, "message": "删除失败"}"
|
||||
// @Router /api/v1/loginlog/{infoId} [delete]
|
||||
func DeleteLoginLog(c *gin.Context) {
|
||||
var data models.LoginLog
|
||||
data.UpdateBy = tools.GetUserIdStr(c)
|
||||
IDS := tools.IdsStrToIdsIntGroup("infoId", c)
|
||||
_, err := data.BatchDelete(IDS)
|
||||
tools.HasError(err, "修改失败", 500)
|
||||
var res app.Response
|
||||
res.Msg = "删除成功"
|
||||
c.JSON(http.StatusOK, res.ReturnOK())
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
package log
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
)
|
||||
|
||||
// @Summary 登录日志列表
|
||||
// @Description 获取JSON
|
||||
// @Tags 登录日志
|
||||
// @Param status query string false "status"
|
||||
// @Param dictCode query string false "dictCode"
|
||||
// @Param dictType query string false "dictType"
|
||||
// @Param pageSize query int false "页条数"
|
||||
// @Param pageIndex query int false "页码"
|
||||
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/operloglist [get]
|
||||
// @Security Bearer
|
||||
func GetOperLogList(c *gin.Context) {
|
||||
var data models.SysOperLog
|
||||
var err error
|
||||
var pageSize = 10
|
||||
var pageIndex = 1
|
||||
|
||||
size := c.Request.FormValue("pageSize")
|
||||
if size != "" {
|
||||
pageSize = tools.StrToInt(err, size)
|
||||
}
|
||||
|
||||
index := c.Request.FormValue("pageIndex")
|
||||
if index != "" {
|
||||
pageIndex = tools.StrToInt(err, index)
|
||||
}
|
||||
|
||||
data.OperName = c.Request.FormValue("operName")
|
||||
data.Status = c.Request.FormValue("status")
|
||||
data.OperIp = c.Request.FormValue("operIp")
|
||||
result, count, err := data.GetPage(pageSize, pageIndex)
|
||||
tools.HasError(err, "", -1)
|
||||
|
||||
var mp = make(map[string]interface{}, 3)
|
||||
mp["list"] = result
|
||||
mp["count"] = count
|
||||
mp["pageIndex"] = pageIndex
|
||||
mp["pageSize"] = pageSize
|
||||
|
||||
var res app.Response
|
||||
res.Data = mp
|
||||
|
||||
c.JSON(http.StatusOK, res.ReturnOK())
|
||||
}
|
||||
|
||||
// @Summary 通过编码获取登录日志
|
||||
// @Description 获取JSON
|
||||
// @Tags 登录日志
|
||||
// @Param infoId path int true "infoId"
|
||||
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/operlog/{infoId} [get]
|
||||
// @Security Bearer
|
||||
func GetOperLog(c *gin.Context) {
|
||||
var OperLog models.SysOperLog
|
||||
OperLog.OperId, _ = tools.StringToInt(c.Param("operId"))
|
||||
result, err := OperLog.Get()
|
||||
tools.HasError(err, "抱歉未找到相关信息", -1)
|
||||
var res app.Response
|
||||
res.Data = result
|
||||
c.JSON(http.StatusOK, res.ReturnOK())
|
||||
}
|
||||
|
||||
// @Summary 添加操作日志
|
||||
// @Description 获取JSON
|
||||
// @Tags 操作日志
|
||||
// @Accept application/json
|
||||
// @Product application/json
|
||||
// @Param data body models.SysOperLog true "data"
|
||||
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
|
||||
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
|
||||
// @Router /api/v1/operlog [post]
|
||||
// @Security Bearer
|
||||
func InsertOperLog(c *gin.Context) {
|
||||
var data models.SysOperLog
|
||||
err := c.BindWith(&data, binding.JSON)
|
||||
tools.HasError(err, "", 500)
|
||||
result, err := data.Create()
|
||||
tools.HasError(err, "", -1)
|
||||
var res app.Response
|
||||
res.Data = result
|
||||
c.JSON(http.StatusOK, res.ReturnOK())
|
||||
}
|
||||
|
||||
// @Summary 批量删除操作日志
|
||||
// @Description 删除数据
|
||||
// @Tags 操作日志
|
||||
// @Param operId path string true "以逗号(,)分割的operId"
|
||||
// @Success 200 {string} string "{"code": 200, "message": "删除成功"}"
|
||||
// @Success 200 {string} string "{"code": -1, "message": "删除失败"}"
|
||||
// @Router /api/v1/operlog/{operId} [delete]
|
||||
func DeleteOperLog(c *gin.Context) {
|
||||
var data models.SysOperLog
|
||||
data.UpdateBy = tools.GetUserIdStr(c)
|
||||
IDS := tools.IdsStrToIdsIntGroup("operId", c)
|
||||
_, err := data.BatchDelete(IDS)
|
||||
tools.HasError(err, "删除失败", 500)
|
||||
var res app.Response
|
||||
res.Msg = "删除成功"
|
||||
c.JSON(http.StatusOK, res.ReturnOK())
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
package syscategory
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
"go-admin/tools/app/msg"
|
||||
)
|
||||
|
||||
func GetSysCategoryList(c *gin.Context) {
|
||||
var data models.SysCategory
|
||||
var err error
|
||||
var pageSize = 10
|
||||
var pageIndex = 1
|
||||
|
||||
if size := c.Request.FormValue("pageSize"); size != "" {
|
||||
pageSize = tools.StrToInt(err, size)
|
||||
}
|
||||
if index := c.Request.FormValue("pageIndex"); index != "" {
|
||||
pageIndex = tools.StrToInt(err, index)
|
||||
}
|
||||
|
||||
data.Name = c.Request.FormValue("name")
|
||||
data.Status = c.Request.FormValue("status")
|
||||
|
||||
data.DataScope = tools.GetUserIdStr(c)
|
||||
result, count, err := data.GetPage(pageSize, pageIndex)
|
||||
tools.HasError(err, "", -1)
|
||||
|
||||
app.PageOK(c, result, count, pageIndex, pageSize, "")
|
||||
}
|
||||
|
||||
func GetSysCategory(c *gin.Context) {
|
||||
var data models.SysCategory
|
||||
data.Id, _ = tools.StringToInt(c.Param("id"))
|
||||
result, err := data.Get()
|
||||
tools.HasError(err, "抱歉未找到相关信息", -1)
|
||||
|
||||
app.OK(c, result, "")
|
||||
}
|
||||
|
||||
// @Summary 添加分类
|
||||
// @Description 获取JSON
|
||||
// @Tags 分类
|
||||
// @Accept application/json
|
||||
// @Product application/json
|
||||
// @Param data body models.SysCategory true "data"
|
||||
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
|
||||
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
|
||||
// @Router /api/v1/syscategory [post]
|
||||
func InsertSysCategory(c *gin.Context) {
|
||||
var data models.SysCategory
|
||||
err := c.ShouldBindJSON(&data)
|
||||
data.CreateBy = tools.GetUserIdStr(c)
|
||||
tools.HasError(err, "", 500)
|
||||
result, err := data.Create()
|
||||
tools.HasError(err, "", -1)
|
||||
app.OK(c, result, "")
|
||||
}
|
||||
|
||||
func UpdateSysCategory(c *gin.Context) {
|
||||
var data models.SysCategory
|
||||
err := c.BindWith(&data, binding.JSON)
|
||||
tools.HasError(err, "数据解析失败", -1)
|
||||
data.UpdateBy = tools.GetUserIdStr(c)
|
||||
result, err := data.Update(data.Id)
|
||||
tools.HasError(err, "", -1)
|
||||
|
||||
app.OK(c, result, "")
|
||||
}
|
||||
|
||||
func DeleteSysCategory(c *gin.Context) {
|
||||
var data models.SysCategory
|
||||
data.UpdateBy = tools.GetUserIdStr(c)
|
||||
|
||||
IDS := tools.IdsStrToIdsIntGroup("id", c)
|
||||
_, err := data.BatchDelete(IDS)
|
||||
tools.HasError(err, msg.DeletedFail, 500)
|
||||
app.OK(c, nil, msg.DeletedSuccess)
|
||||
}
|
||||
@@ -17,10 +17,10 @@ func GetSysContentList(c *gin.Context) {
|
||||
var pageIndex = 1
|
||||
|
||||
if size := c.Request.FormValue("pageSize"); size != "" {
|
||||
pageSize = tools.StrToInt(err, size)
|
||||
pageSize, err = tools.StringToInt(size)
|
||||
}
|
||||
if index := c.Request.FormValue("pageIndex"); index != "" {
|
||||
pageIndex = tools.StrToInt(err, index)
|
||||
pageIndex, err = tools.StringToInt(index)
|
||||
}
|
||||
|
||||
data.CateId = c.Request.FormValue("cateId")
|
||||
|
||||
@@ -1,67 +1,70 @@
|
||||
package sysjob
|
||||
|
||||
import (
|
||||
"go-admin/common/dto"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/app/jobs"
|
||||
"go-admin/app/admin/service"
|
||||
"go-admin/common/apis"
|
||||
"go-admin/common/dto"
|
||||
"go-admin/common/log"
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
"go-admin/tools/app/msg"
|
||||
)
|
||||
|
||||
func RemoveJob(c *gin.Context) {
|
||||
var data models.SysJob
|
||||
type SysJob struct {
|
||||
apis.Api
|
||||
}
|
||||
|
||||
// RemoveJobForService 调用service实现
|
||||
func (e *SysJob) RemoveJobForService(c *gin.Context) {
|
||||
msgID := tools.GenerateMsgIDFromContext(c)
|
||||
db, err := e.GetOrm(c)
|
||||
if err != nil {
|
||||
log.Errorf("msgID[%s] error:%s", msgID, err)
|
||||
app.Error(c, 500, err, "")
|
||||
return
|
||||
}
|
||||
var v dto.GeneralDelDto
|
||||
err := c.BindUri(&v)
|
||||
tools.HasError(err, "", 500)
|
||||
data.JobId = v.Id
|
||||
err = data.Get(data.JobId)
|
||||
tools.HasError(err, "", 500)
|
||||
cn := jobs.Remove(data.EntryId)
|
||||
|
||||
select {
|
||||
case res := <-cn:
|
||||
if res {
|
||||
_, _ = data.RemoveEntryID(data.EntryId)
|
||||
app.OK(c, nil, msg.DeletedSuccess)
|
||||
}
|
||||
case <-time.After(time.Second * 1):
|
||||
app.OK(c, nil, msg.TimeOut)
|
||||
err = c.BindUri(&v)
|
||||
if err != nil {
|
||||
log.Errorf("msgID[%s] 参数验证错误, error:%s", msgID, err)
|
||||
app.Error(c, 422, err, "参数验证失败")
|
||||
return
|
||||
}
|
||||
|
||||
s := service.SysJob{}
|
||||
s.MsgID = msgID
|
||||
s.Orm = db
|
||||
err = s.RemoveJob(&v)
|
||||
if err != nil {
|
||||
app.Error(c, 500, err, "")
|
||||
return
|
||||
}
|
||||
app.OK(c, nil, s.Msg)
|
||||
}
|
||||
|
||||
func StartJob(c *gin.Context) {
|
||||
var data models.SysJob
|
||||
// StartJobForService 启动job service实现
|
||||
func (e *SysJob) StartJobForService(c *gin.Context) {
|
||||
msgID := tools.GenerateMsgIDFromContext(c)
|
||||
db, err := e.GetOrm(c)
|
||||
if err != nil {
|
||||
log.Errorf("msgID[%s] error:%s", msgID, err)
|
||||
app.Error(c, 500, err, "")
|
||||
return
|
||||
}
|
||||
var v dto.GeneralGetDto
|
||||
err := c.BindUri(&v)
|
||||
tools.HasError(err, "", 500)
|
||||
data.JobId = v.Id
|
||||
err = data.Get(data.JobId)
|
||||
tools.HasError(err, "", 500)
|
||||
if data.JobType == 1 {
|
||||
var j = &jobs.HttpJob{}
|
||||
j.InvokeTarget = data.InvokeTarget
|
||||
j.CronExpression = data.CronExpression
|
||||
j.JobId = data.JobId
|
||||
j.Name = data.JobName
|
||||
data.EntryId, err = jobs.AddJob(j)
|
||||
} else {
|
||||
var j = &jobs.ExecJob{}
|
||||
j.InvokeTarget = data.InvokeTarget
|
||||
j.CronExpression = data.CronExpression
|
||||
j.JobId = data.JobId
|
||||
j.Name = data.JobName
|
||||
j.Args = data.Args
|
||||
data.EntryId, err = jobs.AddJob(j)
|
||||
err = c.BindUri(&v)
|
||||
if err != nil {
|
||||
log.Errorf("msgID[%s] 参数验证错误, error:%s", msgID, err)
|
||||
app.Error(c, 422, err, "参数验证失败")
|
||||
return
|
||||
}
|
||||
|
||||
tools.HasError(err, "", 500)
|
||||
err = data.Update(data.JobId)
|
||||
tools.HasError(err, "", 500)
|
||||
app.OK(c, nil, msg.DeletedSuccess)
|
||||
s := service.SysJob{}
|
||||
s.Orm = db
|
||||
s.MsgID = msgID
|
||||
err = s.StartJob(&v)
|
||||
if err != nil {
|
||||
app.Error(c, 500, err, "")
|
||||
return
|
||||
}
|
||||
app.OK(c, nil, s.Msg)
|
||||
}
|
||||
|
||||
@@ -1,149 +0,0 @@
|
||||
package system
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gin-gonic/gin/binding"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
"go-admin/tools/app/msg"
|
||||
)
|
||||
|
||||
// @Summary 配置列表数据
|
||||
// @Description 获取JSON
|
||||
// @Tags 配置
|
||||
// @Param configKey query string false "configKey"
|
||||
// @Param configName query string false "configName"
|
||||
// @Param configType query string false "configType"
|
||||
// @Param pageSize query int false "页条数"
|
||||
// @Param pageIndex query int false "页码"
|
||||
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/configList [get]
|
||||
// @Security Bearer
|
||||
func GetConfigList(c *gin.Context) {
|
||||
var data models.SysConfig
|
||||
var err error
|
||||
var pageSize = 10
|
||||
var pageIndex = 1
|
||||
|
||||
if size := c.Request.FormValue("pageSize"); size != "" {
|
||||
pageSize = tools.StrToInt(err, size)
|
||||
}
|
||||
|
||||
if index := c.Request.FormValue("pageIndex"); index != "" {
|
||||
pageIndex = tools.StrToInt(err, index)
|
||||
}
|
||||
|
||||
data.ConfigKey = c.Request.FormValue("configKey")
|
||||
data.ConfigName = c.Request.FormValue("configName")
|
||||
data.ConfigType = c.Request.FormValue("configType")
|
||||
data.DataScope = tools.GetUserIdStr(c)
|
||||
result, count, err := data.GetPage(pageSize, pageIndex)
|
||||
tools.HasError(err, "", -1)
|
||||
|
||||
var mp = make(map[string]interface{}, 3)
|
||||
mp["list"] = result
|
||||
mp["count"] = count
|
||||
mp["pageIndex"] = pageIndex
|
||||
mp["pageSize"] = pageSize
|
||||
|
||||
var res app.Response
|
||||
res.Data = mp
|
||||
|
||||
c.JSON(http.StatusOK, res.ReturnOK())
|
||||
}
|
||||
|
||||
// @Summary 获取配置
|
||||
// @Description 获取JSON
|
||||
// @Tags 配置
|
||||
// @Param configId path int true "配置编码"
|
||||
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/config/{configId} [get]
|
||||
// @Security Bearer
|
||||
func GetConfig(c *gin.Context) {
|
||||
var Config models.SysConfig
|
||||
Config.ConfigId, _ = tools.StringToInt(c.Param("configId"))
|
||||
result, err := Config.Get()
|
||||
tools.HasError(err, "抱歉未找到相关信息", -1)
|
||||
|
||||
var res app.Response
|
||||
res.Data = result
|
||||
|
||||
c.JSON(http.StatusOK, res.ReturnOK())
|
||||
}
|
||||
|
||||
// @Summary 获取配置
|
||||
// @Description 获取JSON
|
||||
// @Tags 配置
|
||||
// @Param configKey path int true "configKey"
|
||||
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
|
||||
// @Router /api/v1/configKey/{configKey} [get]
|
||||
// @Security Bearer
|
||||
func GetConfigByConfigKey(c *gin.Context) {
|
||||
var Config models.SysConfig
|
||||
Config.ConfigKey = c.Param("configKey")
|
||||
result, err := Config.Get()
|
||||
tools.HasError(err, "抱歉未找到相关信息", -1)
|
||||
|
||||
app.OK(c, result, result.ConfigValue)
|
||||
}
|
||||
|
||||
// @Summary 添加配置
|
||||
// @Description 获取JSON
|
||||
// @Tags 配置
|
||||
// @Accept application/json
|
||||
// @Product application/json
|
||||
// @Param data body models.SysConfig true "data"
|
||||
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
|
||||
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
|
||||
// @Router /api/v1/dict/data [post]
|
||||
// @Security Bearer
|
||||
func InsertConfig(c *gin.Context) {
|
||||
var data models.SysConfig
|
||||
err := c.BindWith(&data, binding.JSON)
|
||||
data.CreateBy = tools.GetUserIdStr(c)
|
||||
tools.HasError(err, "", 500)
|
||||
result, err := data.Create()
|
||||
tools.HasError(err, "", -1)
|
||||
|
||||
app.OK(c, result, "")
|
||||
}
|
||||
|
||||
// @Summary 修改配置
|
||||
// @Description 获取JSON
|
||||
// @Tags 配置
|
||||
// @Accept application/json
|
||||
// @Product application/json
|
||||
// @Param data body models.SysConfig true "body"
|
||||
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
|
||||
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
|
||||
// @Router /api/v1/config [put]
|
||||
// @Security Bearer
|
||||
func UpdateConfig(c *gin.Context) {
|
||||
var data models.SysConfig
|
||||
err := c.BindWith(&data, binding.JSON)
|
||||
tools.HasError(err, "数据解析失败", -1)
|
||||
data.UpdateBy = tools.GetUserIdStr(c)
|
||||
result, err := data.Update(data.ConfigId)
|
||||
tools.HasError(err, "", -1)
|
||||
app.OK(c, result, "")
|
||||
}
|
||||
|
||||
// @Summary 删除配置
|
||||
// @Description 删除数据
|
||||
// @Tags 配置
|
||||
// @Param configId path int true "configId"
|
||||
// @Success 200 {string} string "{"code": 200, "message": "删除成功"}"
|
||||
// @Success 200 {string} string "{"code": -1, "message": "删除失败"}"
|
||||
// @Router /api/v1/config/{configId} [delete]
|
||||
func DeleteConfig(c *gin.Context) {
|
||||
var data models.SysConfig
|
||||
data.UpdateBy = tools.GetUserIdStr(c)
|
||||
IDS := tools.IdsStrToIdsIntGroup("configId", c)
|
||||
result, err := data.BatchDelete(IDS)
|
||||
tools.HasError(err, "修改失败", 500)
|
||||
app.OK(c, result, msg.DeletedSuccess)
|
||||
}
|
||||
@@ -29,11 +29,11 @@ func GetDictDataList(c *gin.Context) {
|
||||
var pageIndex = 1
|
||||
|
||||
if size := c.Request.FormValue("pageSize"); size != "" {
|
||||
pageSize = tools.StrToInt(err, size)
|
||||
pageSize, err = tools.StringToInt(size)
|
||||
}
|
||||
|
||||
if index := c.Request.FormValue("pageIndex"); index != "" {
|
||||
pageIndex = tools.StrToInt(err, index)
|
||||
pageIndex, err = tools.StringToInt(index)
|
||||
}
|
||||
|
||||
data.DictLabel = c.Request.FormValue("dictLabel")
|
||||
|
||||
@@ -29,11 +29,11 @@ func GetDictTypeList(c *gin.Context) {
|
||||
var pageIndex = 1
|
||||
|
||||
if size := c.Request.FormValue("pageSize"); size != "" {
|
||||
pageSize = tools.StrToInt(err, size)
|
||||
pageSize, err = tools.StringToInt(size)
|
||||
}
|
||||
|
||||
if index := c.Request.FormValue("pageIndex"); index != "" {
|
||||
pageIndex = tools.StrToInt(err, index)
|
||||
pageIndex, err = tools.StringToInt(index)
|
||||
}
|
||||
|
||||
data.DictName = c.Request.FormValue("dictName")
|
||||
|
||||
@@ -46,17 +46,22 @@ func GetMenu(c *gin.Context) {
|
||||
app.OK(c, result, "")
|
||||
}
|
||||
|
||||
// GetMenuTreeRoleselect 角色修改中的菜单列表
|
||||
func GetMenuTreeRoleselect(c *gin.Context) {
|
||||
var Menu models.Menu
|
||||
var SysRole models.SysRole
|
||||
|
||||
id, err := tools.StringToInt(c.Param("roleId"))
|
||||
SysRole.RoleId = id
|
||||
result, err := Menu.SetMenuLable()
|
||||
tools.HasError(err, "抱歉未找到相关信息", -1)
|
||||
var result *[]models.MenuLable
|
||||
menuIds := make([]int, 0)
|
||||
if id != 0 {
|
||||
menuIds, err = SysRole.GetRoleMeunId()
|
||||
if tools.GetRoleName(c) != "admin" {
|
||||
result, err = Menu.SetMenuLable()
|
||||
tools.HasError(err, "抱歉未找到相关信息", -1)
|
||||
if id != 0 {
|
||||
menuIds, err = SysRole.GetRoleMeunId()
|
||||
tools.HasError(err, "抱歉未找到相关信息", -1)
|
||||
}
|
||||
}
|
||||
app.Custum(c, gin.H{
|
||||
"code": 200,
|
||||
|
||||
@@ -25,11 +25,11 @@ func GetPostList(c *gin.Context) {
|
||||
var pageIndex = 1
|
||||
|
||||
if size := c.Request.FormValue("pageSize"); size != "" {
|
||||
pageSize = tools.StrToInt(err, size)
|
||||
pageSize, err = tools.StringToInt(size)
|
||||
}
|
||||
|
||||
if index := c.Request.FormValue("pageIndex"); index != "" {
|
||||
pageIndex = tools.StrToInt(err, index)
|
||||
pageIndex, err = tools.StringToInt(index)
|
||||
}
|
||||
|
||||
id := c.Request.FormValue("postId")
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/common/global"
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
)
|
||||
@@ -26,11 +27,11 @@ func GetRoleList(c *gin.Context) {
|
||||
var pageIndex = 1
|
||||
|
||||
if size := c.Request.FormValue("pageSize"); size != "" {
|
||||
pageSize = tools.StrToInt(err, size)
|
||||
pageSize, err = tools.StringToInt(size)
|
||||
}
|
||||
|
||||
if index := c.Request.FormValue("pageIndex"); index != "" {
|
||||
pageIndex = tools.StrToInt(err, index)
|
||||
pageIndex, err = tools.StringToInt(index)
|
||||
}
|
||||
|
||||
data.RoleKey = c.Request.FormValue("roleKey")
|
||||
@@ -86,6 +87,10 @@ func InsertRole(c *gin.Context) {
|
||||
_, err = t.Insert(id, data.MenuIds)
|
||||
tools.HasError(err, "", -1)
|
||||
}
|
||||
|
||||
_, err = global.LoadPolicy()
|
||||
tools.HasError(err, "", -1)
|
||||
|
||||
app.OK(c, data, "添加成功")
|
||||
}
|
||||
|
||||
@@ -112,6 +117,10 @@ func UpdateRole(c *gin.Context) {
|
||||
_, err2 := t.Insert(data.RoleId, data.MenuIds)
|
||||
tools.HasError(err2, "修改失败(insert)", -1)
|
||||
}
|
||||
|
||||
_, err = global.LoadPolicy()
|
||||
tools.HasError(err, "", -1)
|
||||
|
||||
app.OK(c, result, "修改成功")
|
||||
}
|
||||
|
||||
@@ -146,5 +155,9 @@ func DeleteRole(c *gin.Context) {
|
||||
IDS := tools.IdsStrToIdsIntGroup("roleId", c)
|
||||
_, err := Role.BatchDelete(IDS)
|
||||
tools.HasError(err, "删除失败", -1)
|
||||
|
||||
_, err = global.LoadPolicy()
|
||||
tools.HasError(err, "", -1)
|
||||
|
||||
app.OK(c, "", "删除成功")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
package sys_config
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"go-admin/app/admin/service"
|
||||
"go-admin/app/admin/service/dto"
|
||||
"go-admin/common/apis"
|
||||
"go-admin/common/log"
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
)
|
||||
|
||||
type SysConfig struct {
|
||||
apis.Api
|
||||
}
|
||||
|
||||
// GetSysConfigByKEYForService 根据Key获取SysConfig的Service
|
||||
func (e *SysConfig) GetSysConfigByKEYForService(c *gin.Context) {
|
||||
msgID := tools.GenerateMsgIDFromContext(c)
|
||||
db, err := e.GetOrm(c)
|
||||
if err != nil {
|
||||
log.Errorf("msgID[%s] error:%s", msgID, err)
|
||||
app.Error(c, 500, err, "")
|
||||
return
|
||||
}
|
||||
var v dto.SysConfigControl
|
||||
err = c.Bind(&v)
|
||||
if err != nil {
|
||||
log.Errorf("msgID[%s] 参数验证错误, error:%s", msgID, err)
|
||||
app.Error(c, 422, err, "参数验证失败")
|
||||
return
|
||||
}
|
||||
s := service.SysConfig{}
|
||||
s.MsgID = msgID
|
||||
s.Orm = db
|
||||
err = s.GetSysConfigByKEY(&v)
|
||||
if err != nil {
|
||||
app.Error(c, 500, err, "")
|
||||
return
|
||||
}
|
||||
app.OK(c, v, s.Msg)
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
package sys_login_log
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"go-admin/app/admin/models/system"
|
||||
|
||||
"go-admin/app/admin/service"
|
||||
"go-admin/app/admin/service/dto"
|
||||
"go-admin/common/apis"
|
||||
"go-admin/common/log"
|
||||
common "go-admin/common/models"
|
||||
"go-admin/tools"
|
||||
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type SysLoginLog struct {
|
||||
apis.Api
|
||||
}
|
||||
|
||||
func (e *SysLoginLog) GetSysLoginLogList(c *gin.Context) {
|
||||
msgID := tools.GenerateMsgIDFromContext(c)
|
||||
d := new(dto.SysLoginLogSearch)
|
||||
db, err := tools.GetOrm(c)
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
req := d.Generate()
|
||||
|
||||
//查询列表
|
||||
err = req.Bind(c)
|
||||
if err != nil {
|
||||
e.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
|
||||
return
|
||||
}
|
||||
|
||||
list := make([]system.SysLoginLog, 0)
|
||||
var count int64
|
||||
serviceStudent := service.SysLoginLog{}
|
||||
serviceStudent.MsgID = msgID
|
||||
serviceStudent.Orm = db
|
||||
err = serviceStudent.GetSysLoginLogPage(req, &list, &count)
|
||||
if err != nil {
|
||||
e.Error(c, http.StatusUnprocessableEntity, err, "查询失败")
|
||||
return
|
||||
}
|
||||
|
||||
e.PageOK(c, list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
|
||||
}
|
||||
|
||||
func (e *SysLoginLog) GetSysLoginLog(c *gin.Context) {
|
||||
control := new(dto.SysLoginLogById)
|
||||
db, err := tools.GetOrm(c)
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
msgID := tools.GenerateMsgIDFromContext(c)
|
||||
//查看详情
|
||||
req := control.Generate()
|
||||
err = req.Bind(c)
|
||||
if err != nil {
|
||||
e.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
|
||||
return
|
||||
}
|
||||
var object system.SysLoginLog
|
||||
|
||||
serviceSysLoginLog := service.SysLoginLog{}
|
||||
serviceSysLoginLog.MsgID = msgID
|
||||
serviceSysLoginLog.Orm = db
|
||||
err = serviceSysLoginLog.GetSysLoginLog(req, &object)
|
||||
if err != nil {
|
||||
e.Error(c, http.StatusUnprocessableEntity, err, "查询失败")
|
||||
return
|
||||
}
|
||||
|
||||
e.OK(c, object, "查看成功")
|
||||
}
|
||||
|
||||
func (e *SysLoginLog) InsertSysLoginLog(c *gin.Context) {
|
||||
control := new(dto.SysLoginLogControl)
|
||||
db, err := tools.GetOrm(c)
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
msgID := tools.GenerateMsgIDFromContext(c)
|
||||
//新增操作
|
||||
req := control.Generate()
|
||||
err = req.Bind(c)
|
||||
if err != nil {
|
||||
e.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
|
||||
return
|
||||
}
|
||||
var object common.ActiveRecord
|
||||
object, err = req.GenerateM()
|
||||
if err != nil {
|
||||
e.Error(c, http.StatusInternalServerError, err, "模型生成失败")
|
||||
return
|
||||
}
|
||||
// 设置创建人
|
||||
object.SetCreateBy(tools.GetUserIdUint(c))
|
||||
|
||||
serviceSysLoginLog := service.SysLoginLog{}
|
||||
serviceSysLoginLog.Orm = db
|
||||
serviceSysLoginLog.MsgID = msgID
|
||||
err = serviceSysLoginLog.InsertSysLoginLog(object)
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
e.Error(c, http.StatusInternalServerError, err, "创建失败")
|
||||
return
|
||||
}
|
||||
|
||||
e.OK(c, object.GetId(), "创建成功")
|
||||
}
|
||||
|
||||
func (e *SysLoginLog) UpdateSysLoginLog(c *gin.Context) {
|
||||
control := new(dto.SysLoginLogControl)
|
||||
db, err := tools.GetOrm(c)
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
msgID := tools.GenerateMsgIDFromContext(c)
|
||||
req := control.Generate()
|
||||
//更新操作
|
||||
err = req.Bind(c)
|
||||
if err != nil {
|
||||
e.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
|
||||
return
|
||||
}
|
||||
var object common.ActiveRecord
|
||||
object, err = req.GenerateM()
|
||||
if err != nil {
|
||||
e.Error(c, http.StatusInternalServerError, err, "模型生成失败")
|
||||
return
|
||||
}
|
||||
object.SetUpdateBy(tools.GetUserIdUint(c))
|
||||
|
||||
serviceSysLoginLog := service.SysLoginLog{}
|
||||
serviceSysLoginLog.Orm = db
|
||||
serviceSysLoginLog.MsgID = msgID
|
||||
err = serviceSysLoginLog.UpdateSysLoginLog(object)
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
return
|
||||
}
|
||||
e.OK(c, object.GetId(), "更新成功")
|
||||
}
|
||||
|
||||
func (e *SysLoginLog) DeleteSysLoginLog(c *gin.Context) {
|
||||
control := new(dto.SysLoginLogById)
|
||||
db, err := tools.GetOrm(c)
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
msgID := tools.GenerateMsgIDFromContext(c)
|
||||
//删除操作
|
||||
req := control.Generate()
|
||||
err = req.Bind(c)
|
||||
if err != nil {
|
||||
log.Errorf("MsgID[%s] Bind error: %s", msgID, err)
|
||||
e.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
|
||||
return
|
||||
}
|
||||
var object common.ActiveRecord
|
||||
object, err = req.GenerateM()
|
||||
if err != nil {
|
||||
e.Error(c, http.StatusInternalServerError, err, "模型生成失败")
|
||||
return
|
||||
}
|
||||
|
||||
// 设置编辑人
|
||||
object.SetUpdateBy(tools.GetUserIdUint(c))
|
||||
|
||||
serviceSysLoginLog := service.SysLoginLog{}
|
||||
serviceSysLoginLog.Orm = db
|
||||
serviceSysLoginLog.MsgID = msgID
|
||||
err = serviceSysLoginLog.RemoveSysLoginLog(req, object)
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
return
|
||||
}
|
||||
e.OK(c, object.GetId(), "删除成功")
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
package sys_opera_log
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"go-admin/app/admin/models/system"
|
||||
"go-admin/app/admin/service"
|
||||
"go-admin/app/admin/service/dto"
|
||||
"go-admin/common/apis"
|
||||
"go-admin/common/log"
|
||||
common "go-admin/common/models"
|
||||
"go-admin/tools"
|
||||
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type SysOperaLog struct {
|
||||
apis.Api
|
||||
}
|
||||
|
||||
func (e *SysOperaLog) GetSysOperaLogList(c *gin.Context) {
|
||||
msgID := tools.GenerateMsgIDFromContext(c)
|
||||
d := new(dto.SysOperaLogSearch)
|
||||
db, err := tools.GetOrm(c)
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
req := d.Generate()
|
||||
|
||||
//查询列表
|
||||
err = req.Bind(c)
|
||||
if err != nil {
|
||||
e.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
|
||||
return
|
||||
}
|
||||
|
||||
list := make([]system.SysOperaLog, 0)
|
||||
var count int64
|
||||
serviceStudent := service.SysOperaLog{}
|
||||
serviceStudent.MsgID = msgID
|
||||
serviceStudent.Orm = db
|
||||
err = serviceStudent.GetSysOperaLogPage(req, &list, &count)
|
||||
if err != nil {
|
||||
e.Error(c, http.StatusUnprocessableEntity, err, "查询失败")
|
||||
return
|
||||
}
|
||||
|
||||
e.PageOK(c, list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
|
||||
}
|
||||
|
||||
func (e *SysOperaLog) GetSysOperaLog(c *gin.Context) {
|
||||
control := new(dto.SysOperaLogById)
|
||||
db, err := tools.GetOrm(c)
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
msgID := tools.GenerateMsgIDFromContext(c)
|
||||
//查看详情
|
||||
req := control.Generate()
|
||||
err = req.Bind(c)
|
||||
if err != nil {
|
||||
e.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
|
||||
return
|
||||
}
|
||||
var object system.SysOperaLog
|
||||
|
||||
serviceSysOperlog := service.SysOperaLog{}
|
||||
serviceSysOperlog.MsgID = msgID
|
||||
serviceSysOperlog.Orm = db
|
||||
err = serviceSysOperlog.GetSysOperaLog(req, &object)
|
||||
if err != nil {
|
||||
e.Error(c, http.StatusUnprocessableEntity, err, "查询失败")
|
||||
return
|
||||
}
|
||||
|
||||
e.OK(c, object, "查看成功")
|
||||
}
|
||||
|
||||
func (e *SysOperaLog) InsertSysOperaLog(c *gin.Context) {
|
||||
control := new(dto.SysOperaLogControl)
|
||||
db, err := tools.GetOrm(c)
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
msgID := tools.GenerateMsgIDFromContext(c)
|
||||
//新增操作
|
||||
req := control.Generate()
|
||||
err = req.Bind(c)
|
||||
if err != nil {
|
||||
e.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
|
||||
return
|
||||
}
|
||||
var object common.ActiveRecord
|
||||
object, err = req.GenerateM()
|
||||
if err != nil {
|
||||
e.Error(c, http.StatusInternalServerError, err, "模型生成失败")
|
||||
return
|
||||
}
|
||||
// 设置创建人
|
||||
object.SetCreateBy(tools.GetUserIdUint(c))
|
||||
|
||||
serviceSysOperaLog := service.SysOperaLog{}
|
||||
serviceSysOperaLog.Orm = db
|
||||
serviceSysOperaLog.MsgID = msgID
|
||||
err = serviceSysOperaLog.InsertSysOperaLog(object)
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
e.Error(c, http.StatusInternalServerError, err, "创建失败")
|
||||
return
|
||||
}
|
||||
|
||||
e.OK(c, object.GetId(), "创建成功")
|
||||
}
|
||||
|
||||
func (e *SysOperaLog) UpdateSysOperaLog(c *gin.Context) {
|
||||
control := new(dto.SysOperaLogControl)
|
||||
db, err := tools.GetOrm(c)
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
msgID := tools.GenerateMsgIDFromContext(c)
|
||||
req := control.Generate()
|
||||
//更新操作
|
||||
err = req.Bind(c)
|
||||
if err != nil {
|
||||
e.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
|
||||
return
|
||||
}
|
||||
var object common.ActiveRecord
|
||||
object, err = req.GenerateM()
|
||||
if err != nil {
|
||||
e.Error(c, http.StatusInternalServerError, err, "模型生成失败")
|
||||
return
|
||||
}
|
||||
object.SetUpdateBy(tools.GetUserIdUint(c))
|
||||
|
||||
serviceSysOperaLog := service.SysOperaLog{}
|
||||
serviceSysOperaLog.Orm = db
|
||||
serviceSysOperaLog.MsgID = msgID
|
||||
err = serviceSysOperaLog.UpdateSysOperaLog(object)
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
return
|
||||
}
|
||||
e.OK(c, object.GetId(), "更新成功")
|
||||
}
|
||||
|
||||
func (e *SysOperaLog) DeleteSysOperaLog(c *gin.Context) {
|
||||
control := new(dto.SysOperaLogById)
|
||||
db, err := tools.GetOrm(c)
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
msgID := tools.GenerateMsgIDFromContext(c)
|
||||
//删除操作
|
||||
req := control.Generate()
|
||||
err = req.Bind(c)
|
||||
if err != nil {
|
||||
log.Errorf("MsgID[%s] Bind error: %s", msgID, err)
|
||||
e.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
|
||||
return
|
||||
}
|
||||
var object common.ActiveRecord
|
||||
object, err = req.GenerateM()
|
||||
if err != nil {
|
||||
e.Error(c, http.StatusInternalServerError, err, "模型生成失败")
|
||||
return
|
||||
}
|
||||
|
||||
// 设置编辑人
|
||||
object.SetUpdateBy(tools.GetUserIdUint(c))
|
||||
|
||||
serviceSysOperaLog := service.SysOperaLog{}
|
||||
serviceSysOperaLog.Orm = db
|
||||
serviceSysOperaLog.MsgID = msgID
|
||||
err = serviceSysOperaLog.RemoveSysOperaLog(req, object)
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
return
|
||||
}
|
||||
e.OK(c, object.GetId(), "删除成功")
|
||||
}
|
||||
@@ -27,12 +27,12 @@ func GetSysUserList(c *gin.Context) {
|
||||
|
||||
size := c.Request.FormValue("pageSize")
|
||||
if size != "" {
|
||||
pageSize = tools.StrToInt(err, size)
|
||||
pageSize, err = tools.StringToInt(size)
|
||||
}
|
||||
|
||||
index := c.Request.FormValue("pageIndex")
|
||||
if index != "" {
|
||||
pageIndex = tools.StrToInt(err, index)
|
||||
pageIndex, err = tools.StringToInt(index)
|
||||
}
|
||||
|
||||
data.Username = c.Request.FormValue("username")
|
||||
|
||||
@@ -25,11 +25,11 @@ func GetDBColumnList(c *gin.Context) {
|
||||
var pageIndex = 1
|
||||
|
||||
if size := c.Request.FormValue("pageSize"); size != "" {
|
||||
pageSize = tools2.StrToInt(err, size)
|
||||
pageSize, err = tools2.StringToInt(size)
|
||||
}
|
||||
|
||||
if index := c.Request.FormValue("pageIndex"); index != "" {
|
||||
pageIndex = tools2.StrToInt(err, index)
|
||||
pageIndex, err = tools2.StringToInt(index)
|
||||
}
|
||||
|
||||
data.TableName = c.Request.FormValue("tableName")
|
||||
|
||||
@@ -32,11 +32,11 @@ func GetDBTableList(c *gin.Context) {
|
||||
}
|
||||
|
||||
if size := c.Request.FormValue("pageSize"); size != "" {
|
||||
pageSize = tools2.StrToInt(err, size)
|
||||
pageSize, err = tools2.StringToInt(size)
|
||||
}
|
||||
|
||||
if index := c.Request.FormValue("pageIndex"); index != "" {
|
||||
pageIndex = tools2.StrToInt(err, index)
|
||||
pageIndex, err = tools2.StringToInt(index)
|
||||
}
|
||||
|
||||
data.TableName = c.Request.FormValue("tableName")
|
||||
|
||||
+34
-108
@@ -9,7 +9,6 @@ import (
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/app/admin/models/tools"
|
||||
"go-admin/common/global"
|
||||
tools2 "go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
"go-admin/tools/config"
|
||||
@@ -20,17 +19,17 @@ func Preview(c *gin.Context) {
|
||||
id, err := tools2.StringToInt(c.Param("tableId"))
|
||||
tools2.HasError(err, "", -1)
|
||||
table.TableId = id
|
||||
t1, err := template.ParseFiles("template/model.go.template")
|
||||
t1, err := template.ParseFiles("template/v3/model.go.template")
|
||||
tools2.HasError(err, "", -1)
|
||||
t2, err := template.ParseFiles("template/api.go.template")
|
||||
t2, err := template.ParseFiles("template/v3/no_actions/apis.go.template")
|
||||
tools2.HasError(err, "", -1)
|
||||
t3, err := template.ParseFiles("template/js.go.template")
|
||||
t3, err := template.ParseFiles("template/v3/js.go.template")
|
||||
tools2.HasError(err, "", -1)
|
||||
t4, err := template.ParseFiles("template/vue.go.template")
|
||||
t4, err := template.ParseFiles("template/v3/vue.go.template")
|
||||
tools2.HasError(err, "", -1)
|
||||
t5, err := template.ParseFiles("template/router.go.template")
|
||||
t5, err := template.ParseFiles("template/v3/no_actions/router_check_role.go.template")
|
||||
tools2.HasError(err, "", -1)
|
||||
t6, err := template.ParseFiles("template/v2/dto.go.template")
|
||||
t6, err := template.ParseFiles("template/v3/dto.go.template")
|
||||
tools2.HasError(err, "", -1)
|
||||
tab, _ := table.Get()
|
||||
var b1 bytes.Buffer
|
||||
@@ -59,83 +58,7 @@ func Preview(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, res.ReturnOK())
|
||||
}
|
||||
|
||||
func GenCode(c *gin.Context) {
|
||||
table := tools.SysTables{}
|
||||
id, err := tools2.StringToInt(c.Param("tableId"))
|
||||
tools2.HasError(err, "", -1)
|
||||
table.TableId = id
|
||||
tab, _ := table.Get()
|
||||
|
||||
routerfile := "template/routercheckrole.go.template"
|
||||
|
||||
oldTest := "// {{认证路由自动补充在此处请勿删除}}"
|
||||
newText := "// {{认证路由自动补充在此处请勿删除}} \r\n register" + tab.ClassName + "Router(v1,authMiddleware)"
|
||||
|
||||
if tab.IsAuth == 2 {
|
||||
oldTest = "// {{无需认证路由自动补充在此处请勿删除}}"
|
||||
newText = "// {{无需认证路由自动补充在此处请勿删除}} \r\n register" + tab.ClassName + "Router(v1)"
|
||||
routerfile = "template/routernocheckrole.go.template"
|
||||
}
|
||||
|
||||
t1, err := template.ParseFiles("template/model.go.template")
|
||||
tools2.HasError(err, "", -1)
|
||||
t2, err := template.ParseFiles("template/api.go.template")
|
||||
tools2.HasError(err, "", -1)
|
||||
t3, err := template.ParseFiles(routerfile)
|
||||
tools2.HasError(err, "", -1)
|
||||
t4, err := template.ParseFiles("template/js.go.template")
|
||||
tools2.HasError(err, "", -1)
|
||||
t5, err := template.ParseFiles("template/vue.go.template")
|
||||
tools2.HasError(err, "", -1)
|
||||
t6, err := template.ParseFiles("template/v2/dto.go.template")
|
||||
tools2.HasError(err, "", -1)
|
||||
|
||||
_ = tools2.PathCreate("./apis/" + tab.ModuleName + "/")
|
||||
_ = tools2.PathCreate("./models/")
|
||||
_ = tools2.PathCreate("./router/")
|
||||
_ = tools2.PathCreate("./dto/")
|
||||
_ = tools2.PathCreate(config.GenConfig.FrontPath + "/api/")
|
||||
_ = tools2.PathCreate(config.GenConfig.FrontPath + "/views/" + tab.PackageName)
|
||||
|
||||
var b1 bytes.Buffer
|
||||
err = t1.Execute(&b1, tab)
|
||||
var b2 bytes.Buffer
|
||||
err = t2.Execute(&b2, tab)
|
||||
var b3 bytes.Buffer
|
||||
err = t3.Execute(&b3, tab)
|
||||
var b4 bytes.Buffer
|
||||
err = t4.Execute(&b4, tab)
|
||||
var b5 bytes.Buffer
|
||||
err = t5.Execute(&b5, tab)
|
||||
var b6 bytes.Buffer
|
||||
err = t6.Execute(&b6, tab)
|
||||
tools2.FileCreate(b1, "./models/"+tab.PackageName+".go")
|
||||
tools2.FileCreate(b2, "./apis/"+tab.ModuleName+"/"+tab.PackageName+".go")
|
||||
tools2.FileCreate(b3, "./router/"+tab.PackageName+".go")
|
||||
tools2.FileCreate(b4, config.GenConfig.FrontPath+"/api/"+tab.PackageName+".js")
|
||||
tools2.FileCreate(b5, config.GenConfig.FrontPath+"/views/"+tab.PackageName+"/index.vue")
|
||||
tools2.FileCreate(b6, "./dto/"+tab.PackageName+".go")
|
||||
|
||||
helper := tools2.ReplaceHelper{
|
||||
Root: "./router/router.go",
|
||||
OldText: oldTest,
|
||||
NewText: newText,
|
||||
}
|
||||
if helper.OldText == helper.NewText {
|
||||
global.Logger.Println("error !! the NewText isEqual the OldText")
|
||||
return
|
||||
}
|
||||
if err := helper.DoWrok(); err != nil {
|
||||
global.Logger.Print("error:", err.Error())
|
||||
|
||||
} else {
|
||||
global.Logger.Print("done!")
|
||||
}
|
||||
|
||||
app.OK(c, "", "Code generated successfully!")
|
||||
}
|
||||
|
||||
func GenCodeV2(c *gin.Context) {
|
||||
func GenCodeV3(c *gin.Context) {
|
||||
table := tools.SysTables{}
|
||||
id, err := tools2.StringToInt(c.Param("tableId"))
|
||||
tools2.HasError(err, "", -1)
|
||||
@@ -143,32 +66,36 @@ func GenCodeV2(c *gin.Context) {
|
||||
tab, _ := table.Get()
|
||||
|
||||
if tab.IsActions == 1 {
|
||||
ActionsGen(tab)
|
||||
ActionsGenV3(tab)
|
||||
} else {
|
||||
NOActionsGen(tab)
|
||||
NOActionsGenV3(tab)
|
||||
}
|
||||
|
||||
app.OK(c, "", "Code generated successfully!")
|
||||
}
|
||||
|
||||
func NOActionsGen(tab tools.SysTables) {
|
||||
routerfile := "template/routercheckrole.go.template"
|
||||
func NOActionsGenV3(tab tools.SysTables) {
|
||||
|
||||
basePath := "template/v3/"
|
||||
routerFile := basePath + "no_actions/router_check_role.go.template"
|
||||
|
||||
if tab.IsAuth == 2 {
|
||||
routerfile = "template/routernocheckrole.go.template"
|
||||
routerFile = basePath + "no_actions/router_no_check_role.go.template"
|
||||
}
|
||||
|
||||
t1, err := template.ParseFiles("template/model.go.template")
|
||||
t1, err := template.ParseFiles(basePath + "model.go.template")
|
||||
tools2.HasError(err, "", -1)
|
||||
t2, err := template.ParseFiles("template/api.go.template")
|
||||
t2, err := template.ParseFiles(basePath + "no_actions/apis.go.template")
|
||||
tools2.HasError(err, "", -1)
|
||||
t3, err := template.ParseFiles(routerfile)
|
||||
t3, err := template.ParseFiles(routerFile)
|
||||
tools2.HasError(err, "", -1)
|
||||
t4, err := template.ParseFiles("template/js.go.template")
|
||||
t4, err := template.ParseFiles(basePath + "js.go.template")
|
||||
tools2.HasError(err, "", -1)
|
||||
t5, err := template.ParseFiles("template/vue.go.template")
|
||||
t5, err := template.ParseFiles(basePath + "vue.go.template")
|
||||
tools2.HasError(err, "", -1)
|
||||
t6, err := template.ParseFiles("template/v2/dto.go.template")
|
||||
t6, err := template.ParseFiles(basePath + "dto.go.template")
|
||||
tools2.HasError(err, "", -1)
|
||||
t7, err := template.ParseFiles(basePath + "no_actions/service.go.template")
|
||||
tools2.HasError(err, "", -1)
|
||||
|
||||
_ = tools2.PathCreate("./app/" + tab.PackageName + "/apis/" + tab.ModuleName)
|
||||
@@ -190,33 +117,35 @@ func NOActionsGen(tab tools.SysTables) {
|
||||
err = t5.Execute(&b5, tab)
|
||||
var b6 bytes.Buffer
|
||||
err = t6.Execute(&b6, tab)
|
||||
var b7 bytes.Buffer
|
||||
err = t7.Execute(&b7, tab)
|
||||
tools2.FileCreate(b1, "./app/"+tab.PackageName+"/models/"+tab.BusinessName+".go")
|
||||
tools2.FileCreate(b2, "./app/"+tab.PackageName+"/apis/"+tab.ModuleName+"/"+tab.BusinessName+".go")
|
||||
tools2.FileCreate(b3, "./app/"+tab.PackageName+"/router/"+tab.BusinessName+".go")
|
||||
tools2.FileCreate(b4, config.GenConfig.FrontPath+"/api/"+tab.BusinessName+".js")
|
||||
tools2.FileCreate(b5, config.GenConfig.FrontPath+"/views/"+tab.BusinessName+"/index.vue")
|
||||
tools2.FileCreate(b6, "./app/"+tab.PackageName+"/service/dto/"+tab.BusinessName+".go")
|
||||
tools2.FileCreate(b7, "./app/"+tab.PackageName+"/service/"+tab.BusinessName+".go")
|
||||
|
||||
}
|
||||
|
||||
func ActionsGen(tab tools.SysTables) {
|
||||
routerfile := "template/v2/routercheckrole.go.template"
|
||||
func ActionsGenV3(tab tools.SysTables) {
|
||||
basePath := "template/v3/"
|
||||
routerFile := basePath + "actions/router_check_role.go.template"
|
||||
|
||||
if tab.IsAuth == 2 {
|
||||
routerfile = "template/v2/routernocheckrole.go.template"
|
||||
routerFile = basePath + "actions/router_no_check_role.go.template"
|
||||
}
|
||||
|
||||
t1, err := template.ParseFiles("template/v2/model.go.template")
|
||||
t1, err := template.ParseFiles(basePath + "model.go.template")
|
||||
tools2.HasError(err, "", -1)
|
||||
//t2, err := template.ParseFiles("template/v2/router.go.template")
|
||||
//tools2.HasError(err, "", -1)
|
||||
t3, err := template.ParseFiles(routerfile)
|
||||
t3, err := template.ParseFiles(routerFile)
|
||||
tools2.HasError(err, "", -1)
|
||||
t4, err := template.ParseFiles("template/js.go.template")
|
||||
t4, err := template.ParseFiles(basePath + "js.go.template")
|
||||
tools2.HasError(err, "", -1)
|
||||
t5, err := template.ParseFiles("template/vue.go.template")
|
||||
t5, err := template.ParseFiles(basePath + "vue.go.template")
|
||||
tools2.HasError(err, "", -1)
|
||||
t6, err := template.ParseFiles("template/v2/dto.go.template")
|
||||
t6, err := template.ParseFiles(basePath + "dto.go.template")
|
||||
tools2.HasError(err, "", -1)
|
||||
|
||||
_ = tools2.PathCreate("./app/" + tab.PackageName + "/models/")
|
||||
@@ -227,8 +156,6 @@ func ActionsGen(tab tools.SysTables) {
|
||||
|
||||
var b1 bytes.Buffer
|
||||
err = t1.Execute(&b1, tab)
|
||||
//var b2 bytes.Buffer
|
||||
//err = t2.Execute(&b2, tab)
|
||||
var b3 bytes.Buffer
|
||||
err = t3.Execute(&b3, tab)
|
||||
var b4 bytes.Buffer
|
||||
@@ -239,7 +166,6 @@ func ActionsGen(tab tools.SysTables) {
|
||||
err = t6.Execute(&b6, tab)
|
||||
|
||||
tools2.FileCreate(b1, "./app/"+tab.PackageName+"/models/"+tab.BusinessName+".go")
|
||||
//tools2.FileCreate(b2, "./app/"+tab.PackageName+"/router/"+tab.BusinessName+".go")
|
||||
tools2.FileCreate(b3, "./app/"+tab.PackageName+"/router/"+tab.BusinessName+".go")
|
||||
tools2.FileCreate(b4, config.GenConfig.FrontPath+"/api/"+tab.BusinessName+".js")
|
||||
tools2.FileCreate(b5, config.GenConfig.FrontPath+"/views/"+tab.BusinessName+"/index.vue")
|
||||
|
||||
@@ -141,9 +141,10 @@ func genTableInit(tablesList []string, i int, c *gin.Context) (tools.SysTables,
|
||||
strStart := string([]byte(tablenamelist[i])[:1])
|
||||
strend := string([]byte(tablenamelist[i])[1:])
|
||||
data.ClassName += strings.ToUpper(strStart) + strend
|
||||
data.PackageName += strings.ToLower(strStart) + strings.ToLower(strend)
|
||||
//data.PackageName += strings.ToLower(strStart) + strings.ToLower(strend)
|
||||
data.ModuleName += strings.ToLower(strStart) + strings.ToLower(strend)
|
||||
}
|
||||
data.PackageName = "admin"
|
||||
data.TplCategory = "crud"
|
||||
data.Crud = true
|
||||
|
||||
@@ -159,6 +160,9 @@ func genTableInit(tablesList []string, i int, c *gin.Context) (tools.SysTables,
|
||||
data.IsLogicalDelete = "1"
|
||||
data.LogicalDelete = true
|
||||
data.LogicalDeleteColumn = "is_del"
|
||||
data.IsActions = 1
|
||||
data.IsDataScope = 1
|
||||
data.IsAuth = 1
|
||||
|
||||
data.FunctionAuthor = "wenjianzhang"
|
||||
for i := 0; i < len(dbcolumn); i++ {
|
||||
@@ -187,6 +191,8 @@ func genTableInit(tablesList []string, i int, c *gin.Context) (tools.SysTables,
|
||||
column.IsPk = "1"
|
||||
column.Pk = true
|
||||
data.PkColumn = dbcolumn[i].ColumnName
|
||||
column.GoField = strings.ToUpper(column.GoField)
|
||||
column.JsonField = strings.ToUpper(column.JsonField)
|
||||
data.PkGoField = column.GoField
|
||||
data.PkJsonField = column.JsonField
|
||||
}
|
||||
@@ -198,7 +204,9 @@ func genTableInit(tablesList []string, i int, c *gin.Context) (tools.SysTables,
|
||||
|
||||
if strings.Contains(dbcolumn[i].ColumnType, "int") {
|
||||
if strings.Contains(dbcolumn[i].ColumnKey, "PR") {
|
||||
column.GoType = "int"
|
||||
column.GoType = "uint"
|
||||
} else if strings.Contains(dbcolumn[i].ColumnType, "unsigned") {
|
||||
column.GoType = "uint"
|
||||
} else {
|
||||
column.GoType = "string"
|
||||
}
|
||||
@@ -206,6 +214,9 @@ func genTableInit(tablesList []string, i int, c *gin.Context) (tools.SysTables,
|
||||
} else if strings.Contains(dbcolumn[i].ColumnType, "timestamp") {
|
||||
column.GoType = "time.Time"
|
||||
column.HtmlType = "datetime"
|
||||
} else if strings.Contains(dbcolumn[i].ColumnType, "datetime") {
|
||||
column.GoType = "time.Time"
|
||||
column.HtmlType = "datetime"
|
||||
} else {
|
||||
column.GoType = "string"
|
||||
column.HtmlType = "input"
|
||||
|
||||
@@ -8,11 +8,20 @@ import (
|
||||
"go-admin/tools/config"
|
||||
)
|
||||
|
||||
// AuthInit jwt验证new
|
||||
func AuthInit() (*jwt.GinJWTMiddleware, error) {
|
||||
timeout := time.Hour
|
||||
if config.ApplicationConfig.Mode == "dev" {
|
||||
timeout = time.Duration(876010) * time.Hour
|
||||
} else {
|
||||
if config.JwtConfig.Timeout != 0 {
|
||||
timeout = time.Duration(config.JwtConfig.Timeout) * time.Second
|
||||
}
|
||||
}
|
||||
return jwt.New(&jwt.GinJWTMiddleware{
|
||||
Realm: "test zone",
|
||||
Key: []byte(config.ApplicationConfig.JwtSecret),
|
||||
Timeout: time.Hour,
|
||||
Timeout: timeout,
|
||||
MaxRefresh: time.Hour,
|
||||
PayloadFunc: handler.PayloadFunc,
|
||||
IdentityHandler: handler.IdentityHandler,
|
||||
|
||||
@@ -3,16 +3,17 @@ package middleware
|
||||
import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"go-admin/common/config"
|
||||
"go-admin/common/global"
|
||||
"go-admin/tools"
|
||||
"gorm.io/gorm/schema"
|
||||
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/schema"
|
||||
|
||||
"go-admin/common/config"
|
||||
"go-admin/common/global"
|
||||
"go-admin/common/middleware"
|
||||
"go-admin/tools"
|
||||
)
|
||||
|
||||
var WithContextDb = middleware.WithContextDb
|
||||
@@ -23,6 +24,8 @@ func getGormFromDb(driver string, db *sql.DB, config *gorm.Config) (*gorm.DB, er
|
||||
return gorm.Open(mysql.New(mysql.Config{Conn: db}), config)
|
||||
case "postgres":
|
||||
return gorm.Open(postgres.New(postgres.Config{Conn: db}), config)
|
||||
case "sqlite3":
|
||||
return gorm.Open(sqlite.Open(global.Source), config)
|
||||
default:
|
||||
return nil, errors.New("not support this db driver")
|
||||
}
|
||||
|
||||
@@ -8,7 +8,10 @@ import (
|
||||
"github.com/mssola/user_agent"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/app/admin/models/system"
|
||||
"go-admin/app/admin/service"
|
||||
"go-admin/common/global"
|
||||
"go-admin/common/log"
|
||||
jwt "go-admin/pkg/jwtauth"
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/config"
|
||||
@@ -90,29 +93,36 @@ func Authenticator(c *gin.Context) (interface{}, error) {
|
||||
msg = "登录失败"
|
||||
status = "1"
|
||||
LoginLogToDB(c, status, msg, username)
|
||||
global.RequestLogger.Println(e.Error())
|
||||
global.RequestLogger.Error(e)
|
||||
}
|
||||
return nil, jwt.ErrFailedAuthentication
|
||||
}
|
||||
|
||||
// Write log to database
|
||||
// LoginLogToDB Write log to database
|
||||
func LoginLogToDB(c *gin.Context, status string, msg string, username string) {
|
||||
if config.LoggerConfig.EnabledDB {
|
||||
var loginlog models.LoginLog
|
||||
var loginLog system.SysLoginLog
|
||||
msgID := tools.GenerateMsgIDFromContext(c)
|
||||
db, err := tools.GetOrm(c)
|
||||
if err != nil {
|
||||
log.Errorf("msgID[%s] 获取Orm失败, error:%s", msgID, err)
|
||||
}
|
||||
ua := user_agent.New(c.Request.UserAgent())
|
||||
loginlog.Ipaddr = c.ClientIP()
|
||||
loginlog.Username = username
|
||||
loginLog.Ipaddr = c.ClientIP()
|
||||
loginLog.Username = username
|
||||
location := tools.GetLocation(c.ClientIP())
|
||||
loginlog.LoginLocation = location
|
||||
loginlog.LoginTime = tools.GetCurrentTime()
|
||||
loginlog.Status = status
|
||||
loginlog.Remark = c.Request.UserAgent()
|
||||
loginLog.LoginLocation = location
|
||||
loginLog.LoginTime = tools.GetCurrentTime()
|
||||
loginLog.Status = status
|
||||
loginLog.Remark = c.Request.UserAgent()
|
||||
browserName, browserVersion := ua.Browser()
|
||||
loginlog.Browser = browserName + " " + browserVersion
|
||||
loginlog.Os = ua.OS()
|
||||
loginlog.Msg = msg
|
||||
loginlog.Platform = ua.Platform()
|
||||
_, _ = loginlog.Create()
|
||||
loginLog.Browser = browserName + " " + browserVersion
|
||||
loginLog.Os = ua.OS()
|
||||
loginLog.Msg = msg
|
||||
loginLog.Platform = ua.Platform()
|
||||
serviceLoginLog := service.SysLoginLog{}
|
||||
serviceLoginLog.Orm = db
|
||||
_ = serviceLoginLog.InsertSysLoginLog(loginLog.Generate())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -126,21 +136,28 @@ func LoginLogToDB(c *gin.Context, status string, msg string, username string) {
|
||||
// @Router /logout [post]
|
||||
// @Security Bearer
|
||||
func LogOut(c *gin.Context) {
|
||||
var loginlog models.LoginLog
|
||||
var loginLog system.SysLoginLog
|
||||
ua := user_agent.New(c.Request.UserAgent())
|
||||
loginlog.Ipaddr = c.ClientIP()
|
||||
loginLog.Ipaddr = c.ClientIP()
|
||||
location := tools.GetLocation(c.ClientIP())
|
||||
loginlog.LoginLocation = location
|
||||
loginlog.LoginTime = tools.GetCurrentTime()
|
||||
loginlog.Status = "0"
|
||||
loginlog.Remark = c.Request.UserAgent()
|
||||
loginLog.LoginLocation = location
|
||||
loginLog.LoginTime = tools.GetCurrentTime()
|
||||
loginLog.Status = "0"
|
||||
loginLog.Remark = c.Request.UserAgent()
|
||||
browserName, browserVersion := ua.Browser()
|
||||
loginlog.Browser = browserName + " " + browserVersion
|
||||
loginlog.Os = ua.OS()
|
||||
loginlog.Platform = ua.Platform()
|
||||
loginlog.Username = tools.GetUserName(c)
|
||||
loginlog.Msg = "退出成功"
|
||||
loginlog.Create()
|
||||
loginLog.Browser = browserName + " " + browserVersion
|
||||
loginLog.Os = ua.OS()
|
||||
loginLog.Platform = ua.Platform()
|
||||
loginLog.Username = tools.GetUserName(c)
|
||||
loginLog.Msg = "退出成功"
|
||||
msgID := tools.GenerateMsgIDFromContext(c)
|
||||
db, err := tools.GetOrm(c)
|
||||
if err != nil {
|
||||
log.Errorf("msgID[%s] 获取Orm失败, error:%s", msgID, err)
|
||||
}
|
||||
serviceLoginLog := service.SysLoginLog{}
|
||||
serviceLoginLog.Orm = db
|
||||
_ = serviceLoginLog.InsertSysLoginLog(loginLog.Generate())
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"code": 200,
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
jwt "go-admin/pkg/jwtauth"
|
||||
)
|
||||
|
||||
func NoFound(c *gin.Context) {
|
||||
claims := jwt.ExtractClaims(c)
|
||||
log.Printf("NoRoute claims: %#v\n", claims)
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"code": "404",
|
||||
"message": "not found",
|
||||
})
|
||||
}
|
||||
@@ -1,166 +0,0 @@
|
||||
package sd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"runtime"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/shirou/gopsutil/cpu"
|
||||
"github.com/shirou/gopsutil/disk"
|
||||
"github.com/shirou/gopsutil/load"
|
||||
"github.com/shirou/gopsutil/mem"
|
||||
|
||||
"go-admin/tools/app"
|
||||
)
|
||||
|
||||
const (
|
||||
B = 1
|
||||
KB = 1024 * B
|
||||
MB = 1024 * KB
|
||||
GB = 1024 * MB
|
||||
)
|
||||
|
||||
// 健康状况
|
||||
// @Summary 健康状况 HealthCheck shows OK as the ping-pong result.
|
||||
// @Description 健康状况
|
||||
// @Accept text/html
|
||||
// @Produce text/html
|
||||
// @Success 200 {string} string "OK"
|
||||
// @Router /sd/health [get]
|
||||
// @BasePath
|
||||
func HealthCheck(c *gin.Context) {
|
||||
app.OK(c, "", "OK")
|
||||
}
|
||||
|
||||
// @Summary 服务器硬盘使用量
|
||||
// @Description 服务器硬盘使用量 DiskCheck checks the disk usage.
|
||||
// @Accept text/html
|
||||
// @Produce text/html
|
||||
// @Success 200 {string} string "OK - Free space: 16321MB (15GB) / 51200MB (50GB) | Used: 31%"
|
||||
// @Failure 500 {string} string "CRITICAL"
|
||||
// @Failure 429 {string} string "WARNING"
|
||||
// @Router /sd/disk [get]
|
||||
// @BasePath
|
||||
func DiskCheck(c *gin.Context) {
|
||||
u, _ := disk.Usage("/")
|
||||
|
||||
usedMB := int(u.Used) / MB
|
||||
usedGB := int(u.Used) / GB
|
||||
totalMB := int(u.Total) / MB
|
||||
totalGB := int(u.Total) / GB
|
||||
usedPercent := int(u.UsedPercent)
|
||||
|
||||
status := http.StatusOK
|
||||
text := "OK"
|
||||
|
||||
if usedPercent >= 95 {
|
||||
status = http.StatusOK
|
||||
text = "CRITICAL"
|
||||
} else if usedPercent >= 90 {
|
||||
status = http.StatusTooManyRequests
|
||||
text = "WARNING"
|
||||
}
|
||||
|
||||
message := fmt.Sprintf("%s - Free space: %dMB (%dGB) / %dMB (%dGB) | Used: %d%%", text, usedMB, usedGB, totalMB, totalGB, usedPercent)
|
||||
c.String(status, "\n"+message)
|
||||
}
|
||||
|
||||
// @Summary OS
|
||||
// @Description Os
|
||||
// @Accept text/html
|
||||
// @Produce text/html
|
||||
// @Success 200 {string} string ""
|
||||
// @Router /sd/os [get]
|
||||
// @BasePath
|
||||
func OSCheck(c *gin.Context) {
|
||||
status := http.StatusOK
|
||||
app.Custum(c, gin.H{
|
||||
"code": 200,
|
||||
"status": status,
|
||||
"goOs": runtime.GOOS,
|
||||
"compiler": runtime.Compiler,
|
||||
"numCpu": runtime.NumCPU(),
|
||||
"version": runtime.Version(),
|
||||
"numGoroutine": runtime.NumGoroutine(),
|
||||
})
|
||||
}
|
||||
|
||||
// @Summary CPU 使用量
|
||||
// @Description CPU 使用量 DiskCheck checks the disk usage.
|
||||
// @Accept text/html
|
||||
// @Produce text/html
|
||||
// @Success 200 {string} string ""
|
||||
// @Router /sd/cpu [get]
|
||||
// @BasePath
|
||||
func CPUCheck(c *gin.Context) {
|
||||
cores, _ := cpu.Counts(false)
|
||||
|
||||
cpus, err := cpu.Percent(time.Duration(200)*time.Millisecond, true)
|
||||
if err == nil {
|
||||
for i, c := range cpus {
|
||||
fmt.Printf("cpu%d : %f%%\n", i, c)
|
||||
}
|
||||
}
|
||||
|
||||
a, _ := load.Avg()
|
||||
l1 := a.Load1
|
||||
l5 := a.Load5
|
||||
l15 := a.Load15
|
||||
|
||||
status := http.StatusOK
|
||||
text := "OK"
|
||||
|
||||
if l5 >= float64(cores-1) {
|
||||
status = http.StatusInternalServerError
|
||||
text = "CRITICAL"
|
||||
} else if l5 >= float64(cores-2) {
|
||||
status = http.StatusTooManyRequests
|
||||
text = "WARNING"
|
||||
}
|
||||
app.Custum(c, gin.H{
|
||||
"code": 200,
|
||||
"msg": text,
|
||||
"status": status,
|
||||
"cores": cores,
|
||||
"load1": l1,
|
||||
"load5": l5,
|
||||
"load15": l15,
|
||||
})
|
||||
}
|
||||
|
||||
// @Summary 内存使用量
|
||||
// @Description 内存使用量 RAMCheck checks the disk usage.
|
||||
// @Accept text/html
|
||||
// @Produce text/html
|
||||
// @Success 200 {string} string ""
|
||||
// @Router /sd/ram [get]
|
||||
// @BasePath
|
||||
func RAMCheck(c *gin.Context) {
|
||||
u, _ := mem.VirtualMemory()
|
||||
|
||||
usedMB := int(u.Used) / MB
|
||||
totalMB := int(u.Total) / MB
|
||||
usedPercent := int(u.UsedPercent)
|
||||
|
||||
status := http.StatusOK
|
||||
text := "OK"
|
||||
|
||||
if usedPercent >= 95 {
|
||||
status = http.StatusInternalServerError
|
||||
text = "CRITICAL"
|
||||
} else if usedPercent >= 90 {
|
||||
status = http.StatusTooManyRequests
|
||||
text = "WARNING"
|
||||
}
|
||||
|
||||
app.Custum(c, gin.H{
|
||||
"code": 200,
|
||||
"msg": text,
|
||||
"status": status,
|
||||
"used": usedMB,
|
||||
"total": totalMB,
|
||||
"usedPercent": usedPercent,
|
||||
})
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package middleware
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"go-admin/common/middleware"
|
||||
)
|
||||
|
||||
func InitMiddleware(r *gin.Engine) {
|
||||
@@ -15,6 +16,6 @@ func InitMiddleware(r *gin.Engine) {
|
||||
r.Use(Options)
|
||||
// Secure is a middleware function that appends security
|
||||
r.Use(Secure)
|
||||
// Set X-Request-Id header
|
||||
r.Use(RequestId())
|
||||
// 链路追踪
|
||||
r.Use(middleware.Trace())
|
||||
}
|
||||
|
||||
@@ -1,19 +1,21 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/app/admin/models/system"
|
||||
"go-admin/app/admin/service"
|
||||
"go-admin/common/global"
|
||||
"go-admin/common/log"
|
||||
"go-admin/tools"
|
||||
config2 "go-admin/tools/config"
|
||||
"go-admin/tools/config"
|
||||
)
|
||||
|
||||
// 日志记录到文件
|
||||
// LoggerToFile 日志记录到文件
|
||||
func LoggerToFile() gin.HandlerFunc {
|
||||
|
||||
return func(c *gin.Context) {
|
||||
@@ -42,69 +44,74 @@ func LoggerToFile() gin.HandlerFunc {
|
||||
clientIP := c.ClientIP()
|
||||
|
||||
// 日志格式
|
||||
fmt.Printf("%s [INFO] %s %s %3d %13v %15s \r\n",
|
||||
startTime.Format("2006-01-02 15:04:05"),
|
||||
reqMethod,
|
||||
reqUri,
|
||||
statusCode,
|
||||
latencyTime,
|
||||
clientIP,
|
||||
)
|
||||
logData := map[string]interface{}{
|
||||
"statusCode": statusCode,
|
||||
"latencyTime": latencyTime,
|
||||
"clientIP": clientIP,
|
||||
"method": reqMethod,
|
||||
"uri": reqUri,
|
||||
}
|
||||
log.Info(logData)
|
||||
global.RequestLogger.Info(logData)
|
||||
|
||||
global.RequestLogger.Info(statusCode, latencyTime, clientIP, reqMethod, reqUri)
|
||||
|
||||
if c.Request.Method != "GET" && c.Request.Method != "OPTIONS" && config2.LoggerConfig.EnabledDB {
|
||||
if c.Request.Method != "GET" && c.Request.Method != "OPTIONS" && config.LoggerConfig.EnabledDB {
|
||||
SetDBOperLog(c, clientIP, statusCode, reqUri, reqMethod, latencyTime)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 写入操作日志表
|
||||
// 该方法后续即将弃用
|
||||
// SetDBOperLog 写入操作日志表 fixme 该方法后续即将弃用
|
||||
func SetDBOperLog(c *gin.Context, clientIP string, statusCode int, reqUri string, reqMethod string, latencyTime time.Duration) {
|
||||
menu := models.Menu{}
|
||||
menu.Path = reqUri
|
||||
menu.Action = reqMethod
|
||||
menuList, _ := menu.Get()
|
||||
sysOperLog := models.SysOperLog{}
|
||||
sysOperLog.OperIp = clientIP
|
||||
sysOperLog.OperLocation = tools.GetLocation(clientIP)
|
||||
sysOperLog.Status = tools.IntToString(statusCode)
|
||||
sysOperLog.OperName = tools.GetUserName(c)
|
||||
sysOperLog.RequestMethod = c.Request.Method
|
||||
sysOperLog.OperUrl = reqUri
|
||||
sysOperaLog := system.SysOperaLog{}
|
||||
sysOperaLog.OperIp = clientIP
|
||||
sysOperaLog.OperLocation = tools.GetLocation(clientIP)
|
||||
sysOperaLog.Status = tools.IntToString(statusCode)
|
||||
sysOperaLog.OperName = tools.GetUserName(c)
|
||||
sysOperaLog.RequestMethod = c.Request.Method
|
||||
sysOperaLog.OperUrl = reqUri
|
||||
if reqUri == "/login" {
|
||||
sysOperLog.BusinessType = "10"
|
||||
sysOperLog.Title = "用户登录"
|
||||
sysOperLog.OperName = "-"
|
||||
sysOperaLog.BusinessType = "10"
|
||||
sysOperaLog.Title = "用户登录"
|
||||
sysOperaLog.OperName = "-"
|
||||
} else if strings.Contains(reqUri, "/api/v1/logout") {
|
||||
sysOperLog.BusinessType = "11"
|
||||
sysOperaLog.BusinessType = "11"
|
||||
} else if strings.Contains(reqUri, "/api/v1/getCaptcha") {
|
||||
sysOperLog.BusinessType = "12"
|
||||
sysOperLog.Title = "验证码"
|
||||
sysOperaLog.BusinessType = "12"
|
||||
sysOperaLog.Title = "验证码"
|
||||
} else {
|
||||
if reqMethod == "POST" {
|
||||
sysOperLog.BusinessType = "1"
|
||||
sysOperaLog.BusinessType = "1"
|
||||
} else if reqMethod == "PUT" {
|
||||
sysOperLog.BusinessType = "2"
|
||||
sysOperaLog.BusinessType = "2"
|
||||
} else if reqMethod == "DELETE" {
|
||||
sysOperLog.BusinessType = "3"
|
||||
sysOperaLog.BusinessType = "3"
|
||||
}
|
||||
}
|
||||
sysOperLog.Method = reqMethod
|
||||
sysOperaLog.Method = reqMethod
|
||||
if len(menuList) > 0 {
|
||||
sysOperLog.Title = menuList[0].Title
|
||||
sysOperaLog.Title = menuList[0].Title
|
||||
}
|
||||
b, _ := c.Get("body")
|
||||
sysOperLog.OperParam, _ = tools.StructToJsonStr(b)
|
||||
sysOperLog.CreateBy = tools.GetUserName(c)
|
||||
sysOperLog.OperTime = tools.GetCurrentTime()
|
||||
sysOperLog.LatencyTime = (latencyTime).String()
|
||||
sysOperLog.UserAgent = c.Request.UserAgent()
|
||||
sysOperaLog.OperParam, _ = tools.StructToJsonStr(b)
|
||||
sysOperaLog.CreateBy = tools.GetUserIdUint(c)
|
||||
sysOperaLog.OperTime = tools.GetCurrentTime()
|
||||
sysOperaLog.LatencyTime = (latencyTime).String()
|
||||
sysOperaLog.UserAgent = c.Request.UserAgent()
|
||||
if c.Err() == nil {
|
||||
sysOperLog.Status = "0"
|
||||
sysOperaLog.Status = "0"
|
||||
} else {
|
||||
sysOperLog.Status = "1"
|
||||
sysOperaLog.Status = "1"
|
||||
}
|
||||
_, _ = sysOperLog.Create()
|
||||
msgID := tools.GenerateMsgIDFromContext(c)
|
||||
db, err := tools.GetOrm(c)
|
||||
if err != nil {
|
||||
log.Errorf("msgID[%s] 获取Orm失败, error:%s", msgID, err)
|
||||
}
|
||||
serviceOperaLog := service.SysOperaLog{}
|
||||
serviceOperaLog.Orm = db
|
||||
_ = serviceOperaLog.InsertSysOperaLog(sysOperaLog.Generate())
|
||||
}
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
mycasbin "go-admin/pkg/casbin"
|
||||
"go-admin/common/global"
|
||||
"go-admin/common/log"
|
||||
"go-admin/pkg/jwtauth"
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
)
|
||||
|
||||
//权限检查中间件
|
||||
@@ -16,18 +17,21 @@ func AuthCheckRole() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
data, _ := c.Get(jwtauth.JwtPayloadKey)
|
||||
v := data.(jwtauth.MapClaims)
|
||||
e, err := mycasbin.Casbin()
|
||||
tools.HasError(err, "", 500)
|
||||
e := global.CasbinEnforcer
|
||||
var res bool
|
||||
var err error
|
||||
msgID := tools.GenerateMsgIDFromContext(c)
|
||||
//检查权限
|
||||
res, err := e.Enforce(v["rolekey"], c.Request.URL.Path, c.Request.Method)
|
||||
tools.HasError(err, "", 500)
|
||||
|
||||
fmt.Printf("%s [INFO] %s %s %s \r\n",
|
||||
tools.GetCurrentTimeStr(),
|
||||
c.Request.Method,
|
||||
c.Request.URL.Path,
|
||||
v["rolekey"],
|
||||
)
|
||||
if v["rolekey"] == "admin" {
|
||||
res = true
|
||||
log.Infof("msgID[%s] info:%s method:%s path:%s", msgID, v["rolekey"], c.Request.Method, c.Request.URL.Path)
|
||||
} else {
|
||||
res, err = e.Enforce(v["rolekey"], c.Request.URL.Path, c.Request.Method)
|
||||
if err != nil {
|
||||
log.Errorf("msgID[%s] error:%s method:%s path:%s", msgID, err, c.Request.Method, c.Request.URL.Path)
|
||||
app.Error(c, 500, err, "")
|
||||
}
|
||||
}
|
||||
|
||||
if res {
|
||||
c.Next()
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/satori/go.uuid"
|
||||
)
|
||||
|
||||
func RequestId() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
// Check for incoming header, use it if exists
|
||||
requestId := c.Request.Header.Get("X-Request-Id")
|
||||
|
||||
// Create request id with UUID4
|
||||
if requestId == "" {
|
||||
u4 := uuid.NewV4()
|
||||
requestId = u4.String()
|
||||
}
|
||||
|
||||
// Expose it for use in the application
|
||||
c.Set("X-Request-Id", requestId)
|
||||
|
||||
// Set X-Request-Id header
|
||||
c.Writer.Header().Set("X-Request-Id", requestId)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
package models
|
||||
|
||||
//casbin_rule
|
||||
//sys_casbin_rule
|
||||
type CasbinRule struct {
|
||||
PType string `json:"p_type" gorm:"size:100;"`
|
||||
V0 string `json:"v0" gorm:"size:100;"`
|
||||
|
||||
@@ -1,139 +0,0 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"errors"
|
||||
_ "time"
|
||||
|
||||
orm "go-admin/common/global"
|
||||
"go-admin/tools"
|
||||
)
|
||||
|
||||
type SysConfig struct {
|
||||
ConfigId int `json:"configId" gorm:"primary_key;auto_increment;"` //编码
|
||||
ConfigName string `json:"configName" gorm:"size:128;"` //参数名称
|
||||
ConfigKey string `json:"configKey" gorm:"size:128;"` //参数键名
|
||||
ConfigValue string `json:"configValue" gorm:"size:255;"` //参数键值
|
||||
ConfigType string `json:"configType" gorm:"size:64;"` //是否系统内置
|
||||
Remark string `json:"remark" gorm:"size:128;"` //备注
|
||||
CreateBy string `json:"createBy" gorm:"size:128;"`
|
||||
UpdateBy string `json:"updateBy" gorm:"size:128;"`
|
||||
DataScope string `json:"dataScope" gorm:"-"`
|
||||
Params string `json:"params" gorm:"-"`
|
||||
BaseModel
|
||||
}
|
||||
|
||||
func DataInit() {
|
||||
//config1:=SysConfig{1, "主框架页-默认皮肤样式名称", "sys_index_skinName", "skin-blue", "Y", "蓝色 skin-blue、绿色 skin-green、紫色 skin-purple、红色 skin-red、黄色 skin-yellow", "1", "1", "","",BaseModel{time.Now(), time.Now(), nil}}
|
||||
//
|
||||
//orm.Eloquent.Create(&config1)
|
||||
}
|
||||
|
||||
func (SysConfig) TableName() string {
|
||||
return "sys_config"
|
||||
}
|
||||
|
||||
// Config 创建
|
||||
func (e *SysConfig) Create() (SysConfig, error) {
|
||||
var doc SysConfig
|
||||
var i int64
|
||||
orm.Eloquent.Table(e.TableName()).Where("config_name=? or config_key = ?", e.ConfigName, e.ConfigKey).Count(&i)
|
||||
if i > 0 {
|
||||
return doc, errors.New("参数名称或者参数键名已经存在!")
|
||||
}
|
||||
|
||||
result := orm.Eloquent.Table(e.TableName()).Create(&e)
|
||||
if result.Error != nil {
|
||||
err := result.Error
|
||||
return doc, err
|
||||
}
|
||||
doc = *e
|
||||
return doc, nil
|
||||
}
|
||||
|
||||
// 获取 Config
|
||||
func (e *SysConfig) Get() (SysConfig, error) {
|
||||
var doc SysConfig
|
||||
|
||||
table := orm.Eloquent.Table(e.TableName())
|
||||
if e.ConfigId != 0 {
|
||||
table = table.Where("config_id = ?", e.ConfigId)
|
||||
}
|
||||
|
||||
if e.ConfigKey != "" {
|
||||
table = table.Where("config_key = ?", e.ConfigKey)
|
||||
}
|
||||
|
||||
if err := table.First(&doc).Error; err != nil {
|
||||
return doc, err
|
||||
}
|
||||
return doc, nil
|
||||
}
|
||||
|
||||
func (e *SysConfig) GetPage(pageSize int, pageIndex int) ([]SysConfig, int, error) {
|
||||
var doc []SysConfig
|
||||
|
||||
table := orm.Eloquent.Table(e.TableName())
|
||||
|
||||
if e.ConfigName != "" {
|
||||
table = table.Where("config_name = ?", e.ConfigName)
|
||||
}
|
||||
if e.ConfigKey != "" {
|
||||
table = table.Where("config_key = ?", e.ConfigKey)
|
||||
}
|
||||
if e.ConfigType != "" {
|
||||
table = table.Where("config_type = ?", e.ConfigType)
|
||||
}
|
||||
|
||||
// 数据权限控制
|
||||
dataPermission := new(DataPermission)
|
||||
dataPermission.UserId, _ = tools.StringToInt(e.DataScope)
|
||||
table, err := dataPermission.GetDataScope("sys_config", table)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
var count int64
|
||||
|
||||
if err := table.Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Offset(-1).Limit(-1).Count(&count).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
//table.Where("`deleted_at` IS NULL").Count(&count)
|
||||
return doc, int(count), nil
|
||||
}
|
||||
|
||||
func (e *SysConfig) Update(id int) (update SysConfig, err error) {
|
||||
if err = orm.Eloquent.Table(e.TableName()).Where("config_id = ?", id).First(&update).Error; err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if e.ConfigName != "" && e.ConfigName != update.ConfigName {
|
||||
return update, errors.New("参数名称不允许修改!")
|
||||
}
|
||||
|
||||
if e.ConfigKey != "" && e.ConfigKey != update.ConfigKey {
|
||||
return update, errors.New("参数键名不允许修改!")
|
||||
}
|
||||
|
||||
//参数1:是要修改的数据
|
||||
//参数2:是修改的数据
|
||||
if err = orm.Eloquent.Table(e.TableName()).Model(&update).Updates(&e).Error; err != nil {
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (e *SysConfig) Delete() (success bool, err error) {
|
||||
if err = orm.Eloquent.Table(e.TableName()).Where("config_id = ?", e.ConfigId).Delete(&SysConfig{}).Error; err != nil {
|
||||
success = false
|
||||
return
|
||||
}
|
||||
success = true
|
||||
return
|
||||
}
|
||||
|
||||
func (e *SysConfig) BatchDelete(id []int) (Result bool, err error) {
|
||||
if err = orm.Eloquent.Table(e.TableName()).Where("config_id in (?)", id).Delete(&SysConfig{}).Error; err != nil {
|
||||
return
|
||||
}
|
||||
Result = true
|
||||
return
|
||||
}
|
||||
+11
-10
@@ -9,21 +9,22 @@ import (
|
||||
)
|
||||
|
||||
type SysDept struct {
|
||||
DeptId int `json:"deptId" gorm:"primary_key;AUTO_INCREMENT"` //部门编码
|
||||
ParentId int `json:"parentId" gorm:""` //上级部门
|
||||
DeptPath string `json:"deptPath" gorm:"size:255;"` //
|
||||
DeptName string `json:"deptName" gorm:"size:128;"` //部门名称
|
||||
Sort int `json:"sort" gorm:""` //排序
|
||||
Leader string `json:"leader" gorm:"size:128;"` //负责人
|
||||
Phone string `json:"phone" gorm:"size:11;"` //手机
|
||||
Email string `json:"email" gorm:"size:64;"` //邮箱
|
||||
Status string `json:"status" gorm:"size:4;"` //状态
|
||||
DeptId int `json:"deptId" gorm:"primary_key;auto_increment;"` //部门编码
|
||||
ParentId int `json:"parentId" gorm:""` //上级部门
|
||||
DeptPath string `json:"deptPath" gorm:"size:255;"` //
|
||||
DeptName string `json:"deptName" gorm:"size:128;"` //部门名称
|
||||
Sort int `json:"sort" gorm:""` //排序
|
||||
Leader string `json:"leader" gorm:"size:128;"` //负责人
|
||||
Phone string `json:"phone" gorm:"size:11;"` //手机
|
||||
Email string `json:"email" gorm:"size:64;"` //邮箱
|
||||
Status string `json:"status" gorm:"size:4;"` //状态
|
||||
CreateBy string `json:"createBy" gorm:"size:64;"`
|
||||
UpdateBy string `json:"updateBy" gorm:"size:64;"`
|
||||
BaseModel
|
||||
|
||||
DataScope string `json:"dataScope" gorm:"-"`
|
||||
Params string `json:"params" gorm:"-"`
|
||||
Children []SysDept `json:"children" gorm:"-"`
|
||||
BaseModel
|
||||
}
|
||||
|
||||
func (SysDept) TableName() string {
|
||||
|
||||
@@ -8,22 +8,23 @@ import (
|
||||
)
|
||||
|
||||
type DictData struct {
|
||||
DictCode int `gorm:"primary_key;AUTO_INCREMENT" json:"dictCode" example:"1"` //字典编码
|
||||
DictSort int `gorm:"" json:"dictSort"` //显示顺序
|
||||
DictLabel string `gorm:"size:128;" json:"dictLabel"` //数据标签
|
||||
DictValue string `gorm:"size:255;" json:"dictValue"` //数据键值
|
||||
DictType string `gorm:"size:64;" json:"dictType"` //字典类型
|
||||
CssClass string `gorm:"size:128;" json:"cssClass"` //
|
||||
ListClass string `gorm:"size:128;" json:"listClass"` //
|
||||
IsDefault string `gorm:"size:8;" json:"isDefault"` //
|
||||
Status string `gorm:"size:4;" json:"status"` //状态
|
||||
Default string `gorm:"size:8;" json:"default"` //
|
||||
CreateBy string `gorm:"size:64;" json:"createBy"` //
|
||||
UpdateBy string `gorm:"size:64;" json:"updateBy"` //
|
||||
Remark string `gorm:"size:255;" json:"remark"` //备注
|
||||
DictCode int `gorm:"primary_key;auto_increment;" json:"dictCode" example:"1"` //字典编码
|
||||
DictSort int `gorm:"" json:"dictSort"` //显示顺序
|
||||
DictLabel string `gorm:"size:128;" json:"dictLabel"` //数据标签
|
||||
DictValue string `gorm:"size:255;" json:"dictValue"` //数据键值
|
||||
DictType string `gorm:"size:64;" json:"dictType"` //字典类型
|
||||
CssClass string `gorm:"size:128;" json:"cssClass"` //
|
||||
ListClass string `gorm:"size:128;" json:"listClass"` //
|
||||
IsDefault string `gorm:"size:8;" json:"isDefault"` //
|
||||
Status string `gorm:"size:4;" json:"status"` //状态
|
||||
Default string `gorm:"size:8;" json:"default"` //
|
||||
CreateBy string `gorm:"size:64;" json:"createBy"` //
|
||||
UpdateBy string `gorm:"size:64;" json:"updateBy"` //
|
||||
Remark string `gorm:"size:255;" json:"remark"` //备注
|
||||
BaseModel
|
||||
|
||||
Params string `gorm:"-" json:"params"`
|
||||
DataScope string `gorm:"-" json:"dataScope"`
|
||||
BaseModel
|
||||
}
|
||||
|
||||
func (DictData) TableName() string {
|
||||
@@ -34,7 +35,10 @@ func (e *DictData) Create() (DictData, error) {
|
||||
var doc DictData
|
||||
|
||||
var i int64
|
||||
if err := orm.Eloquent.Table(e.TableName()).Where("dict_label=? or (dict_label=? and dict_value = ?)", e.DictLabel, e.DictLabel, e.DictValue).Count(&i).Error; err != nil {
|
||||
if err := orm.Eloquent.Table(e.TableName()).
|
||||
Where("dict_type = ?", e.DictType).
|
||||
Where("dict_label=? or (dict_label=? and dict_value = ?)", e.DictLabel, e.DictLabel, e.DictValue).
|
||||
Count(&i).Error; err != nil {
|
||||
return doc, err
|
||||
}
|
||||
if i > 0 {
|
||||
|
||||
@@ -10,16 +10,17 @@ import (
|
||||
)
|
||||
|
||||
type DictType struct {
|
||||
DictId int `gorm:"primary_key;AUTO_INCREMENT" json:"dictId"`
|
||||
DictId int `gorm:"primary_key;auto_increment;" json:"dictId"`
|
||||
DictName string `gorm:"size:128;" json:"dictName"` //字典名称
|
||||
DictType string `gorm:"size:128;" json:"dictType"` //字典类型
|
||||
Status string `gorm:"size:4;" json:"status"` //状态
|
||||
DataScope string `gorm:"-" json:"dataScope"` //
|
||||
Params string `gorm:"-" json:"params"` //
|
||||
CreateBy string `gorm:"size:11;" json:"createBy"` //创建者
|
||||
UpdateBy string `gorm:"size:11;" json:"updateBy"` //更新者
|
||||
Remark string `gorm:"size:255;" json:"remark"` //备注
|
||||
BaseModel
|
||||
|
||||
DataScope string `gorm:"-" json:"dataScope"` //
|
||||
Params string `gorm:"-" json:"params"` //
|
||||
}
|
||||
|
||||
func (DictType) TableName() string {
|
||||
|
||||
@@ -3,21 +3,20 @@ package models
|
||||
import (
|
||||
orm "go-admin/common/global"
|
||||
"go-admin/tools"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type SysFileDir struct {
|
||||
gorm.Model
|
||||
Id int `json:"id" gorm:"type:int(11);primary_key;AUTO_INCREMENT"` //
|
||||
Label string `json:"label" gorm:"type:varchar(255);"` // 名称
|
||||
PId int `json:"pId" gorm:"type:int(11);"` // 父id
|
||||
Sort int `json:"sort" gorm:""` //排序
|
||||
Path string `json:"path" gorm:"size:255;"` //
|
||||
CreateBy string `json:"createBy" gorm:"type:varchar(128);"` // 创建人
|
||||
UpdateBy string `json:"updateBy" gorm:"type:varchar(128);"` // 编辑人
|
||||
Id int `json:"id"`
|
||||
Label string `json:"label" gorm:"type:varchar(255);"` // 名称
|
||||
PId int `json:"pId" gorm:"type:int(11);"` // 父id
|
||||
Sort int `json:"sort" gorm:""` //排序
|
||||
Path string `json:"path" gorm:"size:255;"` //
|
||||
CreateBy string `json:"createBy" gorm:"type:varchar(128);"` // 创建人
|
||||
UpdateBy string `json:"updateBy" gorm:"type:varchar(128);"` // 编辑人
|
||||
Children []SysFileDir `json:"children" gorm:"-"`
|
||||
DataScope string `json:"dataScope" gorm:"-"`
|
||||
Params string `json:"params" gorm:"-"`
|
||||
BaseModel
|
||||
}
|
||||
|
||||
func (SysFileDir) TableName() string {
|
||||
|
||||
@@ -84,5 +84,5 @@ func InitData(db *gorm.DB) {
|
||||
{"p", "admin", "/api/v1/syssetting/:id", "DELETE", "", "", ""},
|
||||
}
|
||||
|
||||
db.Table("casbin_rule").Create(list)
|
||||
db.Table("sys_casbin_rule").Create(list)
|
||||
}
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
package gorm
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/app/admin/models/tools"
|
||||
)
|
||||
|
||||
func AutoMigrate(db *gorm.DB) (err error) {
|
||||
err = db.Migrator().AutoMigrate(new(models.CasbinRule),
|
||||
new(models.SysDept),
|
||||
new(models.SysConfig),
|
||||
new(tools.SysTables),
|
||||
new(tools.SysColumns),
|
||||
new(models.Menu),
|
||||
new(models.LoginLog),
|
||||
new(models.SysOperLog),
|
||||
new(models.RoleMenu),
|
||||
new(models.SysRoleDept),
|
||||
new(models.SysUser),
|
||||
new(models.SysRole),
|
||||
new(models.Post),
|
||||
new(models.DictData),
|
||||
new(models.DictType),
|
||||
new(models.SysJob),
|
||||
new(models.SysConfig),
|
||||
new(models.SysSetting),
|
||||
new(models.SysFileDir),
|
||||
new(models.SysCategory),
|
||||
new(models.SysContent))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
models.DataInit()
|
||||
return err
|
||||
}
|
||||
|
||||
func CustomMigrate(db *gorm.DB, table interface{}) error {
|
||||
return db.AutoMigrate(&table)
|
||||
}
|
||||
@@ -12,15 +12,15 @@ import (
|
||||
|
||||
func InitDb(db *gorm.DB) (err error) {
|
||||
filePath := "config/db.sql"
|
||||
err = ExecSql(db,filePath)
|
||||
err = ExecSql(db, filePath)
|
||||
if global.Driver == "postgres" {
|
||||
filePath = "config/pg.sql"
|
||||
err = ExecSql(db,filePath)
|
||||
err = ExecSql(db, filePath)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func ExecSql(db *gorm.DB,filePath string) error {
|
||||
func ExecSql(db *gorm.DB, filePath string) error {
|
||||
sql, err := Ioutil(filePath)
|
||||
if err != nil {
|
||||
fmt.Println("数据库基础数据初始化脚本读取失败!原因:", err.Error())
|
||||
|
||||
@@ -1,105 +0,0 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
orm "go-admin/common/global"
|
||||
)
|
||||
|
||||
type LoginLog struct {
|
||||
InfoId int `json:"infoId" gorm:"primary_key;AUTO_INCREMENT"` //主键
|
||||
Username string `json:"username" gorm:"size:128;"` //用户名
|
||||
Status string `json:"status" gorm:"size:4;"` //状态
|
||||
Ipaddr string `json:"ipaddr" gorm:"size:255;"` //ip地址
|
||||
LoginLocation string `json:"loginLocation" gorm:"size:255;"` //归属地
|
||||
Browser string `json:"browser" gorm:"size:255;"` //浏览器
|
||||
Os string `json:"os" gorm:"size:255;"` //系统
|
||||
Platform string `json:"platform" gorm:"size:255;"` // 固件
|
||||
LoginTime time.Time `json:"loginTime" gorm:"type:timestamp;"` //登录时间
|
||||
CreateBy string `json:"createBy" gorm:"size:128;"` //创建人
|
||||
UpdateBy string `json:"updateBy" gorm:"size:128;"` //更新者
|
||||
DataScope string `json:"dataScope" gorm:"-"` //数据
|
||||
Params string `json:"params" gorm:"-"` //
|
||||
Remark string `json:"remark" gorm:"size:255;"` //备注
|
||||
Msg string `json:"msg" gorm:"size:255;"`
|
||||
BaseModel
|
||||
}
|
||||
|
||||
func (LoginLog) TableName() string {
|
||||
return "sys_loginlog"
|
||||
}
|
||||
|
||||
func (e *LoginLog) Get() (LoginLog, error) {
|
||||
var doc LoginLog
|
||||
|
||||
table := orm.Eloquent.Table(e.TableName())
|
||||
if e.Ipaddr != "" {
|
||||
table = table.Where("ipaddr = ?", e.Ipaddr)
|
||||
}
|
||||
if e.InfoId != 0 {
|
||||
table = table.Where("info_id = ?", e.InfoId)
|
||||
}
|
||||
|
||||
if err := table.First(&doc).Error; err != nil {
|
||||
return doc, err
|
||||
}
|
||||
return doc, nil
|
||||
}
|
||||
|
||||
func (e *LoginLog) GetPage(pageSize int, pageIndex int) ([]LoginLog, int, error) {
|
||||
var doc []LoginLog
|
||||
|
||||
table := orm.Eloquent.Table(e.TableName())
|
||||
if e.Ipaddr != "" {
|
||||
table = table.Where("ipaddr = ?", e.Ipaddr)
|
||||
}
|
||||
if e.Status != "" {
|
||||
table = table.Where("status = ?", e.Status)
|
||||
}
|
||||
if e.Username != "" {
|
||||
table = table.Where("userName = ?", e.Username)
|
||||
}
|
||||
|
||||
var count int64
|
||||
|
||||
if err := table.Order("info_id desc").Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Offset(-1).Limit(-1).Count(&count).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
//table.Where("`deleted_at` IS NULL").Count(&count)
|
||||
return doc, int(count), nil
|
||||
}
|
||||
|
||||
func (e *LoginLog) Create() (LoginLog, error) {
|
||||
var doc LoginLog
|
||||
e.CreateBy = "0"
|
||||
e.UpdateBy = "0"
|
||||
result := orm.Eloquent.Table(e.TableName()).Create(&e)
|
||||
if result.Error != nil {
|
||||
err := result.Error
|
||||
return doc, err
|
||||
}
|
||||
doc = *e
|
||||
return doc, nil
|
||||
}
|
||||
|
||||
func (e *LoginLog) Update(id int) (update LoginLog, err error) {
|
||||
|
||||
if err = orm.Eloquent.Table(e.TableName()).First(&update, id).Error; err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
//参数1:是要修改的数据
|
||||
//参数2:是修改的数据
|
||||
if err = orm.Eloquent.Table(e.TableName()).Model(&update).Updates(&e).Error; err != nil {
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (e *LoginLog) BatchDelete(id []int) (Result bool, err error) {
|
||||
if err = orm.Eloquent.Table(e.TableName()).Where("info_id in (?)", id).Delete(&LoginLog{}).Error; err != nil {
|
||||
return
|
||||
}
|
||||
Result = true
|
||||
return
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package models
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"gorm.io/gorm"
|
||||
|
||||
orm "go-admin/common/global"
|
||||
"go-admin/tools"
|
||||
@@ -45,7 +46,7 @@ type MenuLable struct {
|
||||
}
|
||||
|
||||
type Menus struct {
|
||||
MenuId int `json:"menuId" gorm:"column:menu_id;primary_key"`
|
||||
MenuId int `json:"menuId" gorm:"column:menu_id;primary_key;"`
|
||||
MenuName string `json:"menuName" gorm:"column:menu_name"`
|
||||
Title string `json:"title" gorm:"column:title"`
|
||||
Icon string `json:"icon" gorm:"column:icon"`
|
||||
@@ -145,10 +146,10 @@ func DiguiMenu(menulist *[]Menu, menu Menu) Menu {
|
||||
return menu
|
||||
}
|
||||
|
||||
func (e *Menu) SetMenuLable() (m []MenuLable, err error) {
|
||||
func (e *Menu) SetMenuLable() (m *[]MenuLable, err error) {
|
||||
menulist, err := e.Get()
|
||||
|
||||
m = make([]MenuLable, 0)
|
||||
ml := make([]MenuLable, 0)
|
||||
for i := 0; i < len(menulist); i++ {
|
||||
if menulist[i].ParentId != 0 {
|
||||
continue
|
||||
@@ -158,9 +159,9 @@ func (e *Menu) SetMenuLable() (m []MenuLable, err error) {
|
||||
e.Label = menulist[i].Title
|
||||
menusInfo := DiguiMenuLable(&menulist, e)
|
||||
|
||||
m = append(m, menusInfo)
|
||||
ml = append(ml, menusInfo)
|
||||
}
|
||||
return
|
||||
return &ml, err
|
||||
}
|
||||
|
||||
func DiguiMenuLable(menulist *[]Menu, menu MenuLable) MenuLable {
|
||||
@@ -216,8 +217,14 @@ func (e *MenuRole) Get() (Menus []MenuRole, err error) {
|
||||
}
|
||||
|
||||
func (e *Menu) GetByRoleName(rolename string) (Menus []Menu, err error) {
|
||||
table := orm.Eloquent.Table(e.TableName()).Select("sys_menu.*").Joins("left join sys_role_menu on sys_role_menu.menu_id=sys_menu.menu_id")
|
||||
table = table.Where("sys_role_menu.role_name=? and menu_type in ('M','C')", rolename)
|
||||
var table *gorm.DB
|
||||
if rolename == "admin" {
|
||||
table = orm.Eloquent.Table(e.TableName()).Select("sys_menu.*")
|
||||
table = table.Where(" menu_type in ('M','C')")
|
||||
} else {
|
||||
table = orm.Eloquent.Table(e.TableName()).Select("sys_menu.*").Joins("left join sys_role_menu on sys_role_menu.menu_id=sys_menu.menu_id")
|
||||
table = table.Where("sys_role_menu.role_name=? and menu_type in ('M','C')", rolename)
|
||||
}
|
||||
if err = table.Order("sort").Find(&Menus).Error; err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -1,116 +0,0 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
orm "go-admin/common/global"
|
||||
)
|
||||
|
||||
//sys_operlog
|
||||
type SysOperLog struct {
|
||||
OperId int `json:"operId" gorm:"primary_key;AUTO_INCREMENT"` //日志编码
|
||||
Title string `json:"title" gorm:"size:255;"` //操作模块
|
||||
BusinessType string `json:"businessType" gorm:"size:128;"` //操作类型
|
||||
BusinessTypes string `json:"businessTypes" gorm:"size:128;"`
|
||||
Method string `json:"method" gorm:"size:128;"` //函数
|
||||
RequestMethod string `json:"requestMethod" gorm:"size:128;"` //请求方式
|
||||
OperatorType string `json:"operatorType" gorm:"size:128;"` //操作类型
|
||||
OperName string `json:"operName" gorm:"size:128;"` //操作者
|
||||
DeptName string `json:"deptName" gorm:"size:128;"` //部门名称
|
||||
OperUrl string `json:"operUrl" gorm:"size:255;"` //访问地址
|
||||
OperIp string `json:"operIp" gorm:"size:128;"` //客户端ip
|
||||
OperLocation string `json:"operLocation" gorm:"size:128;"` //访问位置
|
||||
OperParam string `json:"operParam" gorm:"size:255;"` //请求参数
|
||||
Status string `json:"status" gorm:"size:4;"` //操作状态
|
||||
OperTime time.Time `json:"operTime" gorm:"type:timestamp;"` //操作时间
|
||||
JsonResult string `json:"jsonResult" gorm:"size:255;"` //返回数据
|
||||
CreateBy string `json:"createBy" gorm:"size:128;"` //创建人
|
||||
UpdateBy string `json:"updateBy" gorm:"size:128;"` //更新者
|
||||
DataScope string `json:"dataScope" gorm:"-"` //数据
|
||||
Params string `json:"params" gorm:"-"` //参数
|
||||
Remark string `json:"remark" gorm:"size:255;"` //备注
|
||||
LatencyTime string `json:"latencyime" gorm:"size:128;"` //耗时
|
||||
UserAgent string `json:"userAgent" gorm:"size:255;"` //ua
|
||||
BaseModel
|
||||
}
|
||||
|
||||
func (SysOperLog) TableName() string {
|
||||
return "sys_operlog"
|
||||
}
|
||||
|
||||
func (e *SysOperLog) Get() (SysOperLog, error) {
|
||||
var doc SysOperLog
|
||||
|
||||
table := orm.Eloquent.Table(e.TableName())
|
||||
if e.OperIp != "" {
|
||||
table = table.Where("oper_ip = ?", e.OperIp)
|
||||
}
|
||||
if e.OperId != 0 {
|
||||
table = table.Where("oper_id = ?", e.OperId)
|
||||
}
|
||||
|
||||
if err := table.First(&doc).Error; err != nil {
|
||||
return doc, err
|
||||
}
|
||||
return doc, nil
|
||||
}
|
||||
|
||||
func (e *SysOperLog) GetPage(pageSize int, pageIndex int) ([]SysOperLog, int, error) {
|
||||
var doc []SysOperLog
|
||||
|
||||
table := orm.Eloquent.Table(e.TableName())
|
||||
if e.OperIp != "" {
|
||||
table = table.Where("oper_ip = ?", e.OperIp)
|
||||
}
|
||||
if e.Status != "" {
|
||||
table = table.Where("status = ?", e.Status)
|
||||
}
|
||||
if e.OperName != "" {
|
||||
table = table.Where("oper_name = ?", e.OperName)
|
||||
}
|
||||
if e.BusinessType != "" {
|
||||
table = table.Where("business_type = ?", e.BusinessType)
|
||||
}
|
||||
|
||||
var count int64
|
||||
|
||||
if err := table.Order("oper_id desc").Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Offset(-1).Limit(-1).Count(&count).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
//table.Where("`deleted_at` IS NULL").Count(&count)
|
||||
return doc, int(count), nil
|
||||
}
|
||||
|
||||
func (e *SysOperLog) Create() (SysOperLog, error) {
|
||||
var doc SysOperLog
|
||||
e.CreateBy = "0"
|
||||
e.UpdateBy = "0"
|
||||
result := orm.Eloquent.Table(e.TableName()).Create(&e)
|
||||
if result.Error != nil {
|
||||
err := result.Error
|
||||
return doc, err
|
||||
}
|
||||
doc = *e
|
||||
return doc, nil
|
||||
}
|
||||
|
||||
func (e *SysOperLog) Update(id int) (update SysOperLog, err error) {
|
||||
if err = orm.Eloquent.Table(e.TableName()).First(&update, id).Error; err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
//参数1:是要修改的数据
|
||||
//参数2:是修改的数据
|
||||
if err = orm.Eloquent.Table(e.TableName()).Model(&update).Updates(&e).Error; err != nil {
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (e *SysOperLog) BatchDelete(id []int) (Result bool, err error) {
|
||||
if err = orm.Eloquent.Table(e.TableName()).Where(" oper_id in (?)", id).Delete(&SysOperLog{}).Error; err != nil {
|
||||
return
|
||||
}
|
||||
Result = true
|
||||
return
|
||||
}
|
||||
@@ -14,9 +14,10 @@ type Post struct {
|
||||
Remark string `gorm:"size:255;" json:"remark"` //描述
|
||||
CreateBy string `gorm:"size:128;" json:"createBy"`
|
||||
UpdateBy string `gorm:"size:128;" json:"updateBy"`
|
||||
BaseModel
|
||||
|
||||
DataScope string `gorm:"-" json:"dataScope"`
|
||||
Params string `gorm:"-" json:"params"`
|
||||
BaseModel
|
||||
}
|
||||
|
||||
func (Post) TableName() string {
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"github.com/pkg/errors"
|
||||
"errors"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
orm "go-admin/common/global"
|
||||
@@ -20,10 +21,11 @@ type SysRole struct {
|
||||
Remark string `json:"remark" gorm:"size:255;"` //备注
|
||||
Admin bool `json:"admin" gorm:"size:4;"`
|
||||
DataScope string `json:"dataScope" gorm:"size:128;"`
|
||||
Params string `json:"params" gorm:"-"`
|
||||
MenuIds []int `json:"menuIds" gorm:"-"`
|
||||
DeptIds []int `json:"deptIds" gorm:"-"`
|
||||
BaseModel
|
||||
|
||||
Params string `json:"params" gorm:"-"`
|
||||
MenuIds []int `json:"menuIds" gorm:"-"`
|
||||
DeptIds []int `json:"deptIds" gorm:"-"`
|
||||
}
|
||||
|
||||
func (SysRole) TableName() string {
|
||||
@@ -215,7 +217,7 @@ func (role *SysRole) BatchDelete(id []int) (Result bool, err error) {
|
||||
|
||||
// 删除casbin配置
|
||||
for i := 0; i < len(roles); i++ {
|
||||
if err := tx.Table("casbin_rule").Where("v0 in (?)", roles[0].RoleKey).Delete(&CasbinRule{}).Error; err != nil {
|
||||
if err := tx.Table("sys_casbin_rule").Where("v0 in (?)", roles[0].RoleKey).Delete(&CasbinRule{}).Error; err != nil {
|
||||
tx.Rollback()
|
||||
return false, err
|
||||
}
|
||||
|
||||
@@ -90,7 +90,7 @@ func (rm *RoleMenu) DeleteRoleMenu(roleId int) (bool, error) {
|
||||
tx.Rollback()
|
||||
return false, err
|
||||
}
|
||||
sql3 := "delete from casbin_rule where v0= '" + role.RoleKey + "';"
|
||||
sql3 := "delete from sys_casbin_rule where v0= '" + role.RoleKey + "';"
|
||||
if err := tx.Exec(sql3).Error; err != nil {
|
||||
tx.Rollback()
|
||||
return false, err
|
||||
@@ -127,7 +127,7 @@ func (rm *RoleMenu) BatchDeleteRoleMenu(roleIds []int) (bool, error) {
|
||||
}
|
||||
sql := ""
|
||||
for i := 0; i < len(role); i++ {
|
||||
sql += "delete from casbin_rule where v0= '" + role[i].RoleName + "';"
|
||||
sql += "delete from sys_casbin_rule where v0= '" + role[i].RoleName + "';"
|
||||
}
|
||||
if err := tx.Exec(sql).Error; err != nil {
|
||||
tx.Rollback()
|
||||
@@ -170,7 +170,7 @@ func (rm *RoleMenu) Insert(roleId int, menuId []int) (bool, error) {
|
||||
}
|
||||
//ORM不支持批量插入所以需要拼接 sql 串
|
||||
sysRoleMenuSql := "INSERT INTO `sys_role_menu` (`role_id`,`menu_id`,`role_name`) VALUES "
|
||||
casbinRuleSql := "INSERT INTO `casbin_rule` (`p_type`,`v0`,`v1`,`v2`) VALUES "
|
||||
casbinRuleSql := "INSERT INTO `sys_casbin_rule` (`p_type`,`v0`,`v1`,`v2`) VALUES "
|
||||
|
||||
for i, m := range menu {
|
||||
// 拼装'role_menu'表批量插入SQL语句
|
||||
@@ -196,7 +196,7 @@ func (rm *RoleMenu) Insert(roleId int, menuId []int) (bool, error) {
|
||||
return false, err
|
||||
}
|
||||
|
||||
// 拼装'casbin_rule'批量插入SQL语句
|
||||
// 拼装'sys_casbin_rule'批量插入SQL语句
|
||||
// TODO: casbinRuleQueue队列不为空时才会拼装,否则直接忽略不执行'for'循环
|
||||
for i, v := range casbinRuleQueue {
|
||||
casbinRuleSql += fmt.Sprintf("('p','%s','%s','%s')", v.V0, v.V1, v.V2)
|
||||
@@ -206,7 +206,7 @@ func (rm *RoleMenu) Insert(roleId int, menuId []int) (bool, error) {
|
||||
casbinRuleSql += ","
|
||||
}
|
||||
}
|
||||
// 执行批量插入casbin_rule
|
||||
// 执行批量插入sys_casbin_rule
|
||||
if len(casbinRuleQueue) > 0 {
|
||||
if err := tx.Exec(casbinRuleSql).Error; err != nil {
|
||||
tx.Rollback()
|
||||
|
||||
+17
-108
@@ -1,122 +1,31 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
orm "go-admin/common/global"
|
||||
"go-admin/tools"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-admin/common/models"
|
||||
)
|
||||
|
||||
type SysCategory struct {
|
||||
Id int `json:"id" gorm:"type:int(11);primary_key;AUTO_INCREMENT"` // 分类Id
|
||||
Name string `json:"name" gorm:"type:varchar(255);"` // 名称
|
||||
Img string `json:"img" gorm:"type:varchar(255);"` // 图片
|
||||
Sort string `json:"sort" gorm:"type:int(4);"` // 排序
|
||||
Status string `json:"status" gorm:"type:int(1);"` // 状态
|
||||
Remark string `json:"remark" gorm:"type:varchar(255);"` // 备注
|
||||
CreateBy string `json:"createBy" gorm:"type:varchar(64);"` // 创建者
|
||||
UpdateBy string `json:"updateBy" gorm:"type:varchar(64);"` // 更新者
|
||||
DataScope string `json:"dataScope" gorm:"-"`
|
||||
Params string `json:"params" gorm:"-"`
|
||||
BaseModel
|
||||
gorm.Model
|
||||
models.ControlBy
|
||||
|
||||
Name string `json:"name" gorm:"type:varchar(255);comment:名称"` //
|
||||
Img string `json:"img" gorm:"type:varchar(255);comment:图标"` //
|
||||
Sort string `json:"sort" gorm:"type:int(4);comment:排序"` //
|
||||
Status string `json:"status" gorm:"type:int(1);comment:状态"` //
|
||||
Remark string `json:"remark" gorm:"type:varchar(255);comment:备注"` //
|
||||
}
|
||||
|
||||
func (SysCategory) TableName() string {
|
||||
return "sys_category"
|
||||
return "sys_category"
|
||||
}
|
||||
|
||||
// 创建SysCategory
|
||||
func (e *SysCategory) Create() (SysCategory, error) {
|
||||
var doc SysCategory
|
||||
result := orm.Eloquent.Table(e.TableName()).Create(&e)
|
||||
if result.Error != nil {
|
||||
err := result.Error
|
||||
return doc, err
|
||||
}
|
||||
doc = *e
|
||||
return doc, nil
|
||||
func (e *SysCategory) Generate() models.ActiveRecord {
|
||||
o := *e
|
||||
return &o
|
||||
}
|
||||
|
||||
// 获取SysCategory
|
||||
func (e *SysCategory) Get() (SysCategory, error) {
|
||||
var doc SysCategory
|
||||
table := orm.Eloquent.Table(e.TableName())
|
||||
|
||||
if e.Id != 0 {
|
||||
table = table.Where("id = ?", e.Id)
|
||||
}
|
||||
|
||||
if e.Name != "" {
|
||||
table = table.Where("name = ?", e.Name)
|
||||
}
|
||||
|
||||
if e.Status != "" {
|
||||
table = table.Where("status = ?", e.Status)
|
||||
}
|
||||
|
||||
if err := table.First(&doc).Error; err != nil {
|
||||
return doc, err
|
||||
}
|
||||
return doc, nil
|
||||
}
|
||||
|
||||
// 获取SysCategory带分页
|
||||
func (e *SysCategory) GetPage(pageSize int, pageIndex int) ([]SysCategory, int, error) {
|
||||
var doc []SysCategory
|
||||
|
||||
table := orm.Eloquent.Table(e.TableName())
|
||||
|
||||
if e.Name != "" {
|
||||
table = table.Where("name = ?", e.Name)
|
||||
}
|
||||
|
||||
if e.Status != "" {
|
||||
table = table.Where("status = ?", e.Status)
|
||||
}
|
||||
|
||||
// 数据权限控制(如果不需要数据权限请将此处去掉)
|
||||
dataPermission := new(DataPermission)
|
||||
dataPermission.UserId, _ = tools.StringToInt(e.DataScope)
|
||||
table, err := dataPermission.GetDataScope(e.TableName(), table)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
var count int64
|
||||
|
||||
if err := table.Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&doc).Offset(-1).Limit(-1).Count(&count).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
//table.Where("`deleted_at` IS NULL").Count(&count)
|
||||
return doc, int(count), nil
|
||||
}
|
||||
|
||||
// 更新SysCategory
|
||||
func (e *SysCategory) Update(id int) (update SysCategory, err error) {
|
||||
if err = orm.Eloquent.Table(e.TableName()).Where("id = ?", id).First(&update).Error; err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
//参数1:是要修改的数据
|
||||
//参数2:是修改的数据
|
||||
if err = orm.Eloquent.Table(e.TableName()).Model(&update).Updates(&e).Error; err != nil {
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// 删除SysCategory
|
||||
func (e *SysCategory) Delete(id int) (success bool, err error) {
|
||||
if err = orm.Eloquent.Table(e.TableName()).Where("id = ?", id).Delete(&SysCategory{}).Error; err != nil {
|
||||
success = false
|
||||
return
|
||||
}
|
||||
success = true
|
||||
return
|
||||
}
|
||||
|
||||
//批量删除
|
||||
func (e *SysCategory) BatchDelete(id []int) (Result bool, err error) {
|
||||
if err = orm.Eloquent.Table(e.TableName()).Where("id in (?)", id).Delete(&SysCategory{}).Error; err != nil {
|
||||
return
|
||||
}
|
||||
Result = true
|
||||
return
|
||||
func (e *SysCategory) GetId() interface{} {
|
||||
return e.ID
|
||||
}
|
||||
|
||||
@@ -5,16 +5,16 @@ import (
|
||||
)
|
||||
|
||||
type SysFileInfo struct {
|
||||
Id int `json:"id" gorm:"type:int(11);primary_key;AUTO_INCREMENT"` // id
|
||||
Type string `json:"type" gorm:"type:varchar(255);"` // 文件类型
|
||||
Name string `json:"name" gorm:"type:varchar(255);"` // 文件名称
|
||||
Size string `json:"size" gorm:"type:int(11);"` // 文件大小
|
||||
PId int `json:"pId" gorm:"type:int(11);"` // 目录id
|
||||
Source string `json:"source" gorm:"type:varchar(255);"` // 文件源
|
||||
Url string `json:"url" gorm:"type:varchar(255);"` // 文件路径
|
||||
FullUrl string `json:"fullUrl" gorm:"type:varchar(255);"` // 文件全路径
|
||||
CreateBy string `json:"createBy" gorm:"type:varchar(128);"` // 创建人
|
||||
UpdateBy string `json:"updateBy" gorm:"type:varchar(128);"` // 编辑人
|
||||
Id int `json:"id"` // id
|
||||
Type string `json:"type" gorm:"type:varchar(255);"` // 文件类型
|
||||
Name string `json:"name" gorm:"type:varchar(255);"` // 文件名称
|
||||
Size string `json:"size" gorm:"type:int(11);"` // 文件大小
|
||||
PId int `json:"pId" gorm:"type:int(11);"` // 目录id
|
||||
Source string `json:"source" gorm:"type:varchar(255);"` // 文件源
|
||||
Url string `json:"url" gorm:"type:varchar(255);"` // 文件路径
|
||||
FullUrl string `json:"fullUrl" gorm:"type:varchar(255);"` // 文件全路径
|
||||
CreateBy string `json:"createBy" gorm:"type:varchar(128);"` // 创建人
|
||||
UpdateBy string `json:"updateBy" gorm:"type:varchar(128);"` // 编辑人
|
||||
DataScope string `json:"dataScope" gorm:"-"`
|
||||
Params string `json:"params" gorm:"-"`
|
||||
BaseModel
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
)
|
||||
|
||||
type SysJob struct {
|
||||
JobId int `json:"jobId" gorm:"primary_key;AUTO_INCREMENT"` // 编码
|
||||
JobId uint `json:"jobId" gorm:"primary_key;AUTO_INCREMENT"` // 编码
|
||||
JobName string `json:"jobName" gorm:"size:255;"` // 名称
|
||||
JobGroup string `json:"jobGroup" gorm:"size:255;"` // 任务分组
|
||||
JobType int `json:"jobType" gorm:"size:1;"` // 任务类型
|
||||
@@ -22,8 +22,9 @@ type SysJob struct {
|
||||
EntryId int `json:"entry_id" gorm:"size:11;"` // job启动时返回的id
|
||||
CreateBy string `json:"createBy" gorm:"size:128;"` //
|
||||
UpdateBy string `json:"updateBy" gorm:"size:128;"` //
|
||||
DataScope string `json:"dataScope" gorm:"-"`
|
||||
BaseModel
|
||||
|
||||
DataScope string `json:"dataScope" gorm:"-"`
|
||||
}
|
||||
|
||||
func (SysJob) TableName() string {
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
package system
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-admin/common/models"
|
||||
)
|
||||
|
||||
type SysConfig struct {
|
||||
gorm.Model
|
||||
models.ControlBy
|
||||
ConfigName string `json:"configName" gorm:"type:varchar(128);comment:ConfigName"` //
|
||||
ConfigKey string `json:"configKey" gorm:"type:varchar(128);comment:ConfigKey"` //
|
||||
ConfigValue string `json:"configValue" gorm:"type:varchar(255);comment:ConfigValue"` //
|
||||
ConfigType string `json:"configType" gorm:"type:varchar(64);comment:ConfigType"` //
|
||||
Remark string `json:"remark" gorm:"type:varchar(128);comment:Remark"` //
|
||||
}
|
||||
|
||||
func (SysConfig) TableName() string {
|
||||
return "sys_config"
|
||||
}
|
||||
|
||||
func (e *SysConfig) Generate() models.ActiveRecord {
|
||||
o := *e
|
||||
return &o
|
||||
}
|
||||
|
||||
func (e *SysConfig) GetId() interface{} {
|
||||
return e.ID
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package system
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-admin/common/models"
|
||||
|
||||
"time"
|
||||
)
|
||||
|
||||
type SysLoginLog struct {
|
||||
gorm.Model
|
||||
models.ControlBy
|
||||
|
||||
Username string `json:"username" gorm:"type:varchar(128);comment:用户名"` //
|
||||
Status string `json:"status" gorm:"type:varchar(4);comment:状态"` //
|
||||
Ipaddr string `json:"ipaddr" gorm:"type:varchar(255);comment:ip地址"` //
|
||||
LoginLocation string `json:"loginLocation" gorm:"type:varchar(255);comment:归属地"` //
|
||||
Browser string `json:"browser" gorm:"type:varchar(255);comment:浏览器"` //
|
||||
Os string `json:"os" gorm:"type:varchar(255);comment:系统"` //
|
||||
Platform string `json:"platform" gorm:"type:varchar(255);comment:固件"` //
|
||||
LoginTime time.Time `json:"loginTime" gorm:"type:timestamp;comment:登录时间"` //
|
||||
Remark string `json:"remark" gorm:"type:varchar(255);comment:备注"` //
|
||||
Msg string `json:"msg" gorm:"type:varchar(255);comment:信息"` //
|
||||
}
|
||||
|
||||
func (SysLoginLog) TableName() string {
|
||||
return "sys_login_log"
|
||||
}
|
||||
|
||||
func (e *SysLoginLog) Generate() models.ActiveRecord {
|
||||
o := *e
|
||||
return &o
|
||||
}
|
||||
|
||||
func (e *SysLoginLog) GetId() interface{} {
|
||||
return e.ID
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package system
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-admin/common/models"
|
||||
|
||||
"time"
|
||||
)
|
||||
|
||||
type SysOperaLog struct {
|
||||
gorm.Model
|
||||
models.ControlBy
|
||||
|
||||
Title string `json:"title" gorm:"type:varchar(255);comment:操作模块"` //
|
||||
BusinessType string `json:"businessType" gorm:"type:varchar(128);comment:操作类型"` //
|
||||
BusinessTypes string `json:"businessTypes" gorm:"type:varchar(128);comment:BusinessTypes"` //
|
||||
Method string `json:"method" gorm:"type:varchar(128);comment:函数"` //
|
||||
RequestMethod string `json:"requestMethod" gorm:"type:varchar(128);comment:请求方式"` //
|
||||
OperatorType string `json:"operatorType" gorm:"type:varchar(128);comment:操作类型"` //
|
||||
OperName string `json:"operName" gorm:"type:varchar(128);comment:操作者"` //
|
||||
DeptName string `json:"deptName" gorm:"type:varchar(128);comment:部门名称"` //
|
||||
OperUrl string `json:"operUrl" gorm:"type:varchar(255);comment:访问地址"` //
|
||||
OperIp string `json:"operIp" gorm:"type:varchar(128);comment:客户端ip"` //
|
||||
OperLocation string `json:"operLocation" gorm:"type:varchar(128);comment:访问位置"` //
|
||||
OperParam string `json:"operParam" gorm:"type:varchar(255);comment:请求参数"` //
|
||||
Status string `json:"status" gorm:"type:varchar(4);comment:操作状态"` //
|
||||
OperTime time.Time `json:"operTime" gorm:"type:timestamp;comment:操作时间"` //
|
||||
JsonResult string `json:"jsonResult" gorm:"type:varchar(255);comment:返回数据"` //
|
||||
Remark string `json:"remark" gorm:"type:varchar(255);comment:备注"` //
|
||||
LatencyTime string `json:"latencyTime" gorm:"type:varchar(128);comment:耗时"` //
|
||||
UserAgent string `json:"userAgent" gorm:"type:varchar(255);comment:ua"` //
|
||||
}
|
||||
|
||||
func (SysOperaLog) TableName() string {
|
||||
return "sys_opera_log"
|
||||
}
|
||||
|
||||
func (e *SysOperaLog) Generate() models.ActiveRecord {
|
||||
o := *e
|
||||
return &o
|
||||
}
|
||||
|
||||
func (e *SysOperaLog) GetId() interface{} {
|
||||
return e.ID
|
||||
}
|
||||
@@ -56,16 +56,16 @@ type SysUserB struct {
|
||||
UpdateBy string `gorm:"size:128" json:"updateBy"` //
|
||||
Remark string `gorm:"size:255" json:"remark"` //备注
|
||||
Status string `gorm:"size:4;" json:"status"`
|
||||
BaseModel
|
||||
|
||||
DataScope string `gorm:"-" json:"dataScope"`
|
||||
Params string `gorm:"-" json:"params"`
|
||||
|
||||
BaseModel
|
||||
}
|
||||
|
||||
type SysUser struct {
|
||||
SysUserId
|
||||
SysUserB
|
||||
LoginM
|
||||
SysUserB
|
||||
}
|
||||
|
||||
func (SysUser) TableName() string {
|
||||
|
||||
@@ -27,7 +27,7 @@ func (e *DBTables) GetPage(pageSize int, pageIndex int) ([]DBTables, int, error)
|
||||
|
||||
if config2.DatabaseConfig.Driver == "mysql" {
|
||||
table = orm.Eloquent.Table("information_schema.tables")
|
||||
table = table.Where("TABLE_NAME not in (select table_name from " + config2.GenConfig.DBName + ".sys_tables) ")
|
||||
table = table.Where("TABLE_NAME not in (select table_name from `" + config2.GenConfig.DBName + "`.sys_tables) ")
|
||||
table = table.Where("table_schema= ? ", config2.GenConfig.DBName)
|
||||
|
||||
if e.TableName != "" {
|
||||
|
||||
@@ -28,9 +28,9 @@ type SysTables struct {
|
||||
Tree bool `gorm:"size:1;" json:"tree"`
|
||||
Crud bool `gorm:"size:1;" json:"crud"`
|
||||
Remark string `gorm:"size:255;" json:"remark"`
|
||||
IsDataScope int `gorm:"size:1;" json:"isDataScope"`
|
||||
IsActions int `gorm:"size:1;" json:"isActions"`
|
||||
IsAuth int `gorm:"size:1;" json:"isAuth"`
|
||||
IsDataScope int `gorm:"size:1;" json:"isDataScope"`
|
||||
IsActions int `gorm:"size:1;" json:"isActions"`
|
||||
IsAuth int `gorm:"size:1;" json:"isAuth"`
|
||||
IsLogicalDelete string `gorm:"size:1;" json:"isLogicalDelete"`
|
||||
LogicalDelete bool `gorm:"size:1;" json:"logicalDelete"`
|
||||
LogicalDeleteColumn string `gorm:"size:128;" json:"logicalDeleteColumn"`
|
||||
@@ -160,16 +160,40 @@ func (e *SysTables) Update() (update SysTables, err error) {
|
||||
return
|
||||
}
|
||||
|
||||
tableNames := make([]string, 0)
|
||||
for i := range e.Columns {
|
||||
if e.Columns[i].FkTableName != "" {
|
||||
tableNames = append(tableNames, e.Columns[i].FkTableName)
|
||||
}
|
||||
}
|
||||
|
||||
tables := make([]SysTables, 0)
|
||||
tableMap := make(map[string]*SysTables)
|
||||
if len(tableNames) > 0 {
|
||||
if err = orm.Eloquent.Table("sys_tables").Where("table_name in (?)", tableNames).Find(&tables).Error; err != nil {
|
||||
return
|
||||
}
|
||||
for i := range tables {
|
||||
tableMap[tables[i].TBName] = &tables[i]
|
||||
}
|
||||
}
|
||||
|
||||
for i := 0; i < len(e.Columns); i++ {
|
||||
if e.Columns[i].FkTableName != "" {
|
||||
tableNameList := strings.Split(e.Columns[i].FkTableName, "_")
|
||||
e.Columns[i].FkTableNameClass = ""
|
||||
e.Columns[i].FkTableNamePackage = ""
|
||||
for a := 0; a < len(tableNameList); a++ {
|
||||
strStart := string([]byte(tableNameList[a])[:1])
|
||||
strEnd := string([]byte(tableNameList[a])[1:])
|
||||
e.Columns[i].FkTableNameClass += strings.ToUpper(strStart) + strEnd
|
||||
e.Columns[i].FkTableNamePackage += strings.ToLower(strStart) + strings.ToLower(strEnd)
|
||||
t, ok := tableMap[e.Columns[i].FkTableName]
|
||||
if ok {
|
||||
e.Columns[i].FkTableNameClass = t.ClassName
|
||||
e.Columns[i].FkTableNamePackage = t.ModuleName
|
||||
} else {
|
||||
tableNameList := strings.Split(e.Columns[i].FkTableName, "_")
|
||||
e.Columns[i].FkTableNameClass = ""
|
||||
e.Columns[i].FkTableNamePackage = ""
|
||||
for a := 0; a < len(tableNameList); a++ {
|
||||
strStart := string([]byte(tableNameList[a])[:1])
|
||||
strEnd := string([]byte(tableNameList[a])[1:])
|
||||
e.Columns[i].FkTableNameClass += strings.ToUpper(strStart) + strEnd
|
||||
e.Columns[i].FkTableNamePackage += strings.ToLower(strStart) + strings.ToLower(strEnd)
|
||||
}
|
||||
}
|
||||
}
|
||||
_, _ = e.Columns[i].Update()
|
||||
|
||||
@@ -1,20 +1,40 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"os"
|
||||
|
||||
"go-admin/app/admin/middleware"
|
||||
"go-admin/app/admin/middleware/handler"
|
||||
"go-admin/common/global"
|
||||
"go-admin/common/log"
|
||||
common "go-admin/common/middleware"
|
||||
_ "go-admin/pkg/jwtauth"
|
||||
"go-admin/tools"
|
||||
config2 "go-admin/tools/config"
|
||||
"go-admin/tools/config"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func InitRouter(r *gin.Engine) *gin.Engine {
|
||||
if config2.SslConfig.Enable {
|
||||
func InitRouter() {
|
||||
var r *gin.Engine
|
||||
h := global.Cfg.GetEngine()
|
||||
if h == nil {
|
||||
h = gin.New()
|
||||
global.Cfg.SetEngine(h)
|
||||
}
|
||||
switch h.(type) {
|
||||
case *gin.Engine:
|
||||
r = h.(*gin.Engine)
|
||||
default:
|
||||
log.Fatal("not support other engine")
|
||||
os.Exit(-1)
|
||||
}
|
||||
if config.SslConfig.Enable {
|
||||
r.Use(handler.TlsHandler())
|
||||
}
|
||||
r.Use(middleware.WithContextDb(middleware.GetGormFromConfig(global.Cfg)))
|
||||
|
||||
r.Use(common.Sentinel())
|
||||
middleware.InitMiddleware(r)
|
||||
// the jwt middleware
|
||||
var err error
|
||||
@@ -28,5 +48,5 @@ func InitRouter(r *gin.Engine) *gin.Engine {
|
||||
// TODO: 这里可存放业务路由,里边并无实际路由只有演示代码
|
||||
InitExamplesRouter(r, authMiddleware)
|
||||
|
||||
return r
|
||||
//return r
|
||||
}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/go-admin-team/go-admin-core/transfer"
|
||||
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||||
"go-admin/common/global"
|
||||
"go-admin/common/log"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func Monitor() {
|
||||
var r *gin.Engine
|
||||
h := global.Cfg.GetEngine()
|
||||
if h == nil {
|
||||
h = gin.New()
|
||||
global.Cfg.SetEngine(h)
|
||||
}
|
||||
switch h.(type) {
|
||||
case *gin.Engine:
|
||||
r = h.(*gin.Engine)
|
||||
default:
|
||||
log.Fatal("not support other engine")
|
||||
}
|
||||
//开发环境启动监控指标
|
||||
r.GET("/metrics", transfer.Handler(promhttp.Handler()))
|
||||
//健康检查
|
||||
r.GET("/health", func(c *gin.Context) {
|
||||
c.Status(http.StatusOK)
|
||||
})
|
||||
}
|
||||
@@ -51,7 +51,5 @@ func examplesCheckRoleRouter(r *gin.Engine, authMiddleware *jwtauth.GinJWTMiddle
|
||||
}
|
||||
|
||||
// {{认证路由自动补充在此处请勿删除}}
|
||||
registerSysContentRouter(v1, authMiddleware)
|
||||
registerSysCategoryRouter(v1, authMiddleware)
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"go-admin/app/admin/middleware"
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/app/admin/service/dto"
|
||||
"go-admin/common/actions"
|
||||
jwt "go-admin/pkg/jwtauth"
|
||||
)
|
||||
|
||||
func init() {
|
||||
routerCheckRole = append(routerCheckRole, registerSysCategoryRouter)
|
||||
}
|
||||
|
||||
// 需认证的路由代码
|
||||
func registerSysCategoryRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
|
||||
r := v1.Group("/syscategory").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
|
||||
{
|
||||
model := &models.SysCategory{}
|
||||
r.GET("", actions.PermissionAction(), actions.IndexAction(model, new(dto.SysCategorySearch), func() interface{} {
|
||||
list := make([]models.SysCategory, 0)
|
||||
return &list
|
||||
}))
|
||||
r.GET("/:id", actions.PermissionAction(), actions.ViewAction(new(dto.SysCategoryById), nil))
|
||||
r.POST("", actions.CreateAction(new(dto.SysCategoryControl)))
|
||||
r.PUT("/:id", actions.PermissionAction(), actions.UpdateAction(new(dto.SysCategoryControl)))
|
||||
r.DELETE("", actions.PermissionAction(), actions.DeleteAction(new(dto.SysCategoryById)))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"go-admin/app/admin/apis/system/sys_config"
|
||||
"go-admin/app/admin/middleware"
|
||||
"go-admin/app/admin/models/system"
|
||||
"go-admin/app/admin/service/dto"
|
||||
"go-admin/common/actions"
|
||||
jwt "go-admin/pkg/jwtauth"
|
||||
)
|
||||
|
||||
func init() {
|
||||
routerCheckRole = append(routerCheckRole, registerSysConfigRouter)
|
||||
}
|
||||
|
||||
// 需认证的路由代码
|
||||
func registerSysConfigRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
|
||||
r := v1.Group("/config").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
|
||||
{
|
||||
model := &system.SysConfig{}
|
||||
r.GET("", actions.PermissionAction(), actions.IndexAction(model, new(dto.SysConfigSearch), func() interface{} {
|
||||
list := make([]system.SysConfig, 0)
|
||||
return &list
|
||||
}))
|
||||
r.GET("/:id", actions.PermissionAction(), actions.ViewAction(new(dto.SysConfigById), nil))
|
||||
r.POST("", actions.CreateAction(new(dto.SysConfigControl)))
|
||||
r.PUT("/:id", actions.PermissionAction(), actions.UpdateAction(new(dto.SysConfigControl)))
|
||||
r.DELETE("", actions.PermissionAction(), actions.DeleteAction(new(dto.SysConfigById)))
|
||||
}
|
||||
|
||||
r1 := v1.Group("/configKey").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
|
||||
{
|
||||
model := &sys_config.SysConfig{}
|
||||
r1.POST("", model.GetSysConfigByKEYForService)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"go-admin/app/admin/apis/system/sys_login_log"
|
||||
"go-admin/app/admin/middleware"
|
||||
jwt "go-admin/pkg/jwtauth"
|
||||
)
|
||||
|
||||
func init() {
|
||||
routerCheckRole = append(routerCheckRole, registerSysLoginLogRouter)
|
||||
}
|
||||
|
||||
// 需认证的路由代码
|
||||
func registerSysLoginLogRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
|
||||
api := &sys_login_log.SysLoginLog{}
|
||||
r := v1.Group("/sys-login-log").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
|
||||
{
|
||||
r.GET("", api.GetSysLoginLogList)
|
||||
r.GET("/:id", api.GetSysLoginLog)
|
||||
r.POST("", api.InsertSysLoginLog)
|
||||
r.PUT("/:id", api.UpdateSysLoginLog)
|
||||
r.DELETE("", api.DeleteSysLoginLog)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"go-admin/app/admin/apis/system/sys_opera_log"
|
||||
"go-admin/app/admin/middleware"
|
||||
jwt "go-admin/pkg/jwtauth"
|
||||
)
|
||||
|
||||
func init() {
|
||||
routerCheckRole = append(routerCheckRole, registerSysOperaLogRouter)
|
||||
}
|
||||
|
||||
// 需认证的路由代码
|
||||
func registerSysOperaLogRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
|
||||
api := &sys_opera_log.SysOperaLog{}
|
||||
r := v1.Group("/sys-opera-log").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
|
||||
{
|
||||
r.GET("", api.GetSysOperaLogList)
|
||||
r.GET("/:id", api.GetSysOperaLog)
|
||||
r.POST("", api.InsertSysOperaLog)
|
||||
r.PUT("/:id", api.UpdateSysOperaLog)
|
||||
r.DELETE("", api.DeleteSysOperaLog)
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"go-admin/app/admin/apis/syscategory"
|
||||
"go-admin/app/admin/middleware"
|
||||
jwt "go-admin/pkg/jwtauth"
|
||||
)
|
||||
|
||||
// 需认证的路由代码
|
||||
func registerSysCategoryRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
|
||||
|
||||
r := v1.Group("/syscategory").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
|
||||
{
|
||||
r.GET("/:id", syscategory.GetSysCategory)
|
||||
r.POST("", syscategory.InsertSysCategory)
|
||||
r.PUT("", syscategory.UpdateSysCategory)
|
||||
r.DELETE("/:id", syscategory.DeleteSysCategory)
|
||||
}
|
||||
|
||||
l := v1.Group("").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
|
||||
{
|
||||
l.GET("/syscategoryList", syscategory.GetSysCategoryList)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -7,6 +7,11 @@ import (
|
||||
jwt "go-admin/pkg/jwtauth"
|
||||
)
|
||||
|
||||
|
||||
func init() {
|
||||
routerCheckRole = append(routerCheckRole, registerSysContentRouter)
|
||||
}
|
||||
|
||||
// 需认证的路由代码
|
||||
func registerSysContentRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
jwt "go-admin/pkg/jwtauth"
|
||||
)
|
||||
|
||||
func init() {
|
||||
func init() {
|
||||
routerCheckRole = append(routerCheckRole, registerSysJobRouter)
|
||||
}
|
||||
|
||||
@@ -24,12 +24,15 @@ func registerSysJobRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddlew
|
||||
list := make([]models.SysJob, 0)
|
||||
return &list
|
||||
}))
|
||||
r.GET("/:id", actions.PermissionAction(), actions.ViewAction(new(dto.SysJobById)))
|
||||
r.GET("/:id", actions.PermissionAction(), actions.ViewAction(new(dto.SysJobById), func() interface{} {
|
||||
return &dto.SysJobItem{}
|
||||
}))
|
||||
r.POST("", actions.CreateAction(new(dto.SysJobControl)))
|
||||
r.PUT("", actions.PermissionAction(), actions.UpdateAction(new(dto.SysJobControl)))
|
||||
r.DELETE("/:id", actions.PermissionAction(), actions.DeleteAction(new(dto.SysJobById)))
|
||||
r.DELETE("", actions.PermissionAction(), actions.DeleteAction(new(dto.SysJobById)))
|
||||
}
|
||||
sysJob := &sysjob.SysJob{}
|
||||
|
||||
v1.GET("/job/remove/:jobId", sysjob.RemoveJob)
|
||||
v1.GET("/job/start/:jobId", sysjob.StartJob)
|
||||
v1.GET("/job/remove/:id", sysJob.RemoveJobForService)
|
||||
v1.GET("/job/start/:id", sysJob.StartJobForService)
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ package router
|
||||
import (
|
||||
"mime"
|
||||
|
||||
log2 "go-admin/app/admin/apis/log"
|
||||
"go-admin/app/admin/apis/monitor"
|
||||
"go-admin/app/admin/apis/public"
|
||||
"go-admin/app/admin/apis/system"
|
||||
@@ -25,15 +24,12 @@ func InitSysRouter(r *gin.Engine, authMiddleware *jwt.GinJWTMiddleware) *gin.Rou
|
||||
sysBaseRouter(g)
|
||||
// 静态文件
|
||||
sysStaticFileRouter(g)
|
||||
|
||||
// swagger;注意:生产环境可以注释掉
|
||||
sysSwaggerRouter(g)
|
||||
|
||||
// 无需认证
|
||||
sysNoCheckRoleRouter(g)
|
||||
// 需要认证
|
||||
sysCheckRoleRouterInit(g, authMiddleware)
|
||||
|
||||
return g
|
||||
}
|
||||
|
||||
@@ -44,13 +40,11 @@ func sysBaseRouter(r *gin.RouterGroup) {
|
||||
go ws.WebsocketManager.SendAllService()
|
||||
|
||||
r.GET("/", system.HelloWorld)
|
||||
|
||||
r.GET("/info", handler.Ping)
|
||||
}
|
||||
|
||||
func sysStaticFileRouter(r *gin.RouterGroup) {
|
||||
mime.AddExtensionType(".js", "application/javascript")
|
||||
|
||||
r.Static("/static", "./static")
|
||||
r.Static("/form-generator", "./static/form-generator")
|
||||
}
|
||||
@@ -65,20 +59,16 @@ func sysNoCheckRoleRouter(r *gin.RouterGroup) {
|
||||
v1.GET("/monitor/server", monitor.ServerInfo)
|
||||
v1.GET("/getCaptcha", system.GenerateCaptchaHandler)
|
||||
v1.GET("/gen/preview/:tableId", Preview)
|
||||
v1.GET("/gen/toproject/:tableId", GenCodeV2)
|
||||
v1.GET("/gen/toproject/:tableId", GenCodeV3)
|
||||
v1.GET("/gen/todb/:tableId", GenMenuAndApi)
|
||||
v1.GET("/gen/tabletree", GetSysTablesTree)
|
||||
v1.GET("/menuTreeselect", system.GetMenuTreeelect)
|
||||
v1.GET("/dict/databytype/:dictType", dict.GetDictDataByDictType)
|
||||
|
||||
registerDBRouter(v1)
|
||||
|
||||
registerSysTableRouter(v1)
|
||||
|
||||
registerPublicRouter(v1)
|
||||
|
||||
registerSysSettingRouter(v1)
|
||||
|
||||
}
|
||||
|
||||
func registerDBRouter(api *gin.RouterGroup) {
|
||||
@@ -108,11 +98,8 @@ func sysCheckRoleRouterInit(r *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddle
|
||||
r.POST("/login", authMiddleware.LoginHandler)
|
||||
// Refresh time can be longer than token timeout
|
||||
r.GET("/refresh_token", authMiddleware.RefreshHandler)
|
||||
|
||||
r.Group("").Use(authMiddleware.MiddlewareFunc()).GET("/ws/:id/:channel", ws.WebsocketManager.WsClient)
|
||||
|
||||
r.Group("").Use(authMiddleware.MiddlewareFunc()).GET("/wslogout/:id/:channel", ws.WebsocketManager.UnWsClient)
|
||||
|
||||
v1 := r.Group("/api/v1")
|
||||
|
||||
registerPageRouter(v1, authMiddleware)
|
||||
@@ -121,12 +108,9 @@ func sysCheckRoleRouterInit(r *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddle
|
||||
registerDictRouter(v1, authMiddleware)
|
||||
registerSysUserRouter(v1, authMiddleware)
|
||||
registerRoleRouter(v1, authMiddleware)
|
||||
registerConfigRouter(v1, authMiddleware)
|
||||
registerUserCenterRouter(v1, authMiddleware)
|
||||
registerPostRouter(v1, authMiddleware)
|
||||
registerMenuRouter(v1, authMiddleware)
|
||||
registerLoginLogRouter(v1, authMiddleware)
|
||||
registerOperLogRouter(v1, authMiddleware)
|
||||
}
|
||||
|
||||
func registerBaseRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
|
||||
@@ -140,9 +124,6 @@ func registerBaseRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddlewar
|
||||
|
||||
v1auth.POST("/logout", handler.LogOut)
|
||||
v1auth.GET("/menuids", system.GetMenuIDS)
|
||||
|
||||
v1auth.GET("/operloglist", log2.GetOperLogList)
|
||||
v1auth.GET("/configKey/:configKey", system.GetConfigByConfigKey)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -153,10 +134,9 @@ func registerPageRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddlewar
|
||||
v1auth.GET("/deptTree", system.GetDeptTree)
|
||||
v1auth.GET("/sysUserList", system.GetSysUserList)
|
||||
v1auth.GET("/rolelist", system.GetRoleList)
|
||||
v1auth.GET("/configList", system.GetConfigList)
|
||||
//v1auth.GET("/configList", system.GetConfigList)
|
||||
v1auth.GET("/postlist", system.GetPostList)
|
||||
v1auth.GET("/menulist", system.GetMenuList)
|
||||
v1auth.GET("/loginloglist", log2.GetLoginLogList)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -169,24 +149,6 @@ func registerUserCenterRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMid
|
||||
}
|
||||
}
|
||||
|
||||
func registerOperLogRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
|
||||
operlog := v1.Group("/operlog").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
|
||||
{
|
||||
operlog.GET("/:operId", log2.GetOperLog)
|
||||
operlog.DELETE("/:operId", log2.DeleteOperLog)
|
||||
}
|
||||
}
|
||||
|
||||
func registerLoginLogRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
|
||||
loginlog := v1.Group("/loginlog").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
|
||||
{
|
||||
loginlog.GET("/:infoId", log2.GetLoginLog)
|
||||
loginlog.POST("", log2.InsertLoginLog)
|
||||
loginlog.PUT("", log2.UpdateLoginLog)
|
||||
loginlog.DELETE("/:infoId", log2.DeleteLoginLog)
|
||||
}
|
||||
}
|
||||
|
||||
func registerPostRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
|
||||
post := v1.Group("/post").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
|
||||
{
|
||||
@@ -207,16 +169,6 @@ func registerMenuRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddlewar
|
||||
}
|
||||
}
|
||||
|
||||
func registerConfigRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
|
||||
config := v1.Group("/config").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
|
||||
{
|
||||
config.GET("/:configId", system.GetConfig)
|
||||
config.POST("", system.InsertConfig)
|
||||
config.PUT("", system.UpdateConfig)
|
||||
config.DELETE("/:configId", system.DeleteConfig)
|
||||
}
|
||||
}
|
||||
|
||||
func registerRoleRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
|
||||
role := v1.Group("/role").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
|
||||
{
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/common/dto"
|
||||
"go-admin/common/log"
|
||||
common "go-admin/common/models"
|
||||
"go-admin/tools"
|
||||
)
|
||||
|
||||
type SysCategorySearch struct {
|
||||
dto.Pagination `search:"-"`
|
||||
Name string `form:"name" search:"type:exact;column:name;table:sys_category" comment:"名称"`
|
||||
|
||||
Status string `form:"status" search:"type:exact;column:status;table:sys_category" comment:"状态"`
|
||||
|
||||
|
||||
}
|
||||
|
||||
func (m *SysCategorySearch) GetNeedSearch() interface{} {
|
||||
return *m
|
||||
}
|
||||
|
||||
func (m *SysCategorySearch) Bind(ctx *gin.Context) error {
|
||||
msgID := tools.GenerateMsgIDFromContext(ctx)
|
||||
err := ctx.ShouldBind(m)
|
||||
if err != nil {
|
||||
log.Debugf("MsgID[%s] ShouldBind error: %s", msgID, err.Error())
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (m *SysCategorySearch) Generate() dto.Index {
|
||||
o := *m
|
||||
return &o
|
||||
}
|
||||
|
||||
type SysCategoryControl struct {
|
||||
|
||||
ID uint `uri:"ID" comment:"标识"` // 标识
|
||||
|
||||
Name string `json:"name" comment:"名称"`
|
||||
|
||||
|
||||
Img string `json:"img" comment:"图标"`
|
||||
|
||||
|
||||
Sort string `json:"sort" comment:"排序"`
|
||||
|
||||
|
||||
Status string `json:"status" comment:"状态"`
|
||||
|
||||
|
||||
Remark string `json:"remark" comment:"备注"`
|
||||
|
||||
}
|
||||
|
||||
func (s *SysCategoryControl) Bind(ctx *gin.Context) error {
|
||||
msgID := tools.GenerateMsgIDFromContext(ctx)
|
||||
err := ctx.ShouldBindUri(s)
|
||||
if err != nil {
|
||||
log.Debugf("MsgID[%s] ShouldBindUri error: %s", msgID, err.Error())
|
||||
return err
|
||||
}
|
||||
err = ctx.ShouldBind(s)
|
||||
if err != nil {
|
||||
log.Debugf("MsgID[%s] ShouldBind error: %#v", msgID, err.Error())
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *SysCategoryControl) Generate() dto.Control {
|
||||
cp := *s
|
||||
return &cp
|
||||
}
|
||||
|
||||
func (s *SysCategoryControl) GenerateM() (common.ActiveRecord, error) {
|
||||
return &models.SysCategory{
|
||||
|
||||
Model: gorm.Model{ID: s.ID},
|
||||
Name: s.Name,
|
||||
Img: s.Img,
|
||||
Sort: s.Sort,
|
||||
Status: s.Status,
|
||||
Remark: s.Remark,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *SysCategoryControl) GetId() interface{} {
|
||||
return s.ID
|
||||
}
|
||||
|
||||
type SysCategoryById struct {
|
||||
dto.ObjectById
|
||||
}
|
||||
|
||||
func (s *SysCategoryById) Generate() dto.Control {
|
||||
cp := *s
|
||||
return &cp
|
||||
}
|
||||
|
||||
func (s *SysCategoryById) GenerateM() (common.ActiveRecord, error) {
|
||||
return &models.SysCategory{}, nil
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"go-admin/app/admin/models/system"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-admin/common/dto"
|
||||
"go-admin/common/log"
|
||||
common "go-admin/common/models"
|
||||
"go-admin/tools"
|
||||
)
|
||||
|
||||
type SysConfigSearch struct {
|
||||
dto.Pagination `search:"-"`
|
||||
ConfigName string `form:"configName" search:"type:exact;column:config_name;table:sys_config" comment:""`
|
||||
ConfigKey string `form:"configKey" search:"type:exact;column:config_key;table:sys_config" comment:""`
|
||||
ConfigType string `form:"configType" search:"type:exact;column:config_type;table:sys_config" comment:""`
|
||||
}
|
||||
|
||||
func (m *SysConfigSearch) GetNeedSearch() interface{} {
|
||||
return *m
|
||||
}
|
||||
|
||||
func (m *SysConfigSearch) Bind(ctx *gin.Context) error {
|
||||
msgID := tools.GenerateMsgIDFromContext(ctx)
|
||||
err := ctx.ShouldBind(m)
|
||||
if err != nil {
|
||||
log.Debugf("MsgID[%s] ShouldBind error: %s", msgID, err.Error())
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (m *SysConfigSearch) Generate() dto.Index {
|
||||
o := *m
|
||||
return &o
|
||||
}
|
||||
|
||||
type SysConfigControl struct {
|
||||
ID uint `uri:"ID" comment:"编码"` // 编码
|
||||
ConfigName string `json:"configName" comment:""`
|
||||
ConfigKey string `json:"configKey" comment:""`
|
||||
ConfigValue string `json:"configValue" comment:""`
|
||||
ConfigType string `json:"configType" comment:""`
|
||||
Remark string `json:"remark" comment:""`
|
||||
}
|
||||
|
||||
func (s *SysConfigControl) Bind(ctx *gin.Context) error {
|
||||
msgID := tools.GenerateMsgIDFromContext(ctx)
|
||||
err := ctx.ShouldBindUri(s)
|
||||
if err != nil {
|
||||
log.Debugf("MsgID[%s] ShouldBindUri error: %s", msgID, err.Error())
|
||||
return err
|
||||
}
|
||||
err = ctx.ShouldBind(s)
|
||||
if err != nil {
|
||||
log.Debugf("MsgID[%s] ShouldBind error: %#v", msgID, err.Error())
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *SysConfigControl) Generate() dto.Control {
|
||||
cp := *s
|
||||
return &cp
|
||||
}
|
||||
|
||||
func (s *SysConfigControl) GenerateM() (common.ActiveRecord, error) {
|
||||
return &system.SysConfig{
|
||||
Model: gorm.Model{ID: s.ID},
|
||||
ConfigName: s.ConfigName,
|
||||
ConfigKey: s.ConfigKey,
|
||||
ConfigValue: s.ConfigValue,
|
||||
ConfigType: s.ConfigType,
|
||||
Remark: s.Remark,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *SysConfigControl) GetId() interface{} {
|
||||
return s.ID
|
||||
}
|
||||
|
||||
type SysConfigById struct {
|
||||
dto.ObjectById
|
||||
}
|
||||
|
||||
func (s *SysConfigById) Generate() dto.Control {
|
||||
cp := *s
|
||||
return &cp
|
||||
}
|
||||
|
||||
func (s *SysConfigById) GenerateM() (common.ActiveRecord, error) {
|
||||
return &system.SysConfig{}, nil
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-admin/app/admin/models/system"
|
||||
"go-admin/common/dto"
|
||||
"go-admin/common/log"
|
||||
common "go-admin/common/models"
|
||||
"go-admin/tools"
|
||||
|
||||
"time"
|
||||
)
|
||||
|
||||
type SysLoginLogSearch struct {
|
||||
dto.Pagination `search:"-"`
|
||||
|
||||
Username string `form:"username" search:"type:exact;column:username;table:sys_login_log" comment:"用户名"`
|
||||
Status string `form:"status" search:"type:exact;column:status;table:sys_login_log" comment:"状态"`
|
||||
Ipaddr string `form:"ipaddr" search:"type:exact;column:ipaddr;table:sys_login_log" comment:"ip地址"`
|
||||
LoginLocation string `form:"loginLocation" search:"type:exact;column:login_location;table:sys_login_log" comment:"归属地"`
|
||||
}
|
||||
|
||||
func (m *SysLoginLogSearch) GetNeedSearch() interface{} {
|
||||
return *m
|
||||
}
|
||||
|
||||
func (m *SysLoginLogSearch) Bind(ctx *gin.Context) error {
|
||||
msgID := tools.GenerateMsgIDFromContext(ctx)
|
||||
err := ctx.ShouldBind(m)
|
||||
if err != nil {
|
||||
log.Debugf("MsgID[%s] ShouldBind error: %s", msgID, err.Error())
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (m *SysLoginLogSearch) Generate() dto.Index {
|
||||
o := *m
|
||||
return &o
|
||||
}
|
||||
|
||||
type SysLoginLogControl struct {
|
||||
ID uint `uri:"ID" comment:"主键"` // 主键
|
||||
Username string `json:"username" comment:"用户名"`
|
||||
Status string `json:"status" comment:"状态"`
|
||||
Ipaddr string `json:"ipaddr" comment:"ip地址"`
|
||||
LoginLocation string `json:"loginLocation" comment:"归属地"`
|
||||
Browser string `json:"browser" comment:"浏览器"`
|
||||
Os string `json:"os" comment:"系统"`
|
||||
Platform string `json:"platform" comment:"固件"`
|
||||
LoginTime time.Time `json:"loginTime" comment:"登录时间"`
|
||||
Remark string `json:"remark" comment:"备注"`
|
||||
Msg string `json:"msg" comment:"信息"`
|
||||
}
|
||||
|
||||
func (s *SysLoginLogControl) Bind(ctx *gin.Context) error {
|
||||
msgID := tools.GenerateMsgIDFromContext(ctx)
|
||||
err := ctx.ShouldBindUri(s)
|
||||
if err != nil {
|
||||
log.Debugf("MsgID[%s] ShouldBindUri error: %s", msgID, err.Error())
|
||||
return err
|
||||
}
|
||||
err = ctx.ShouldBind(s)
|
||||
if err != nil {
|
||||
log.Debugf("MsgID[%s] ShouldBind error: %#v", msgID, err.Error())
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *SysLoginLogControl) Generate() dto.Control {
|
||||
cp := *s
|
||||
return &cp
|
||||
}
|
||||
|
||||
func (s *SysLoginLogControl) GenerateM() (common.ActiveRecord, error) {
|
||||
return &system.SysLoginLog{
|
||||
|
||||
Model: gorm.Model{ID: s.ID},
|
||||
Username: s.Username,
|
||||
Status: s.Status,
|
||||
Ipaddr: s.Ipaddr,
|
||||
LoginLocation: s.LoginLocation,
|
||||
Browser: s.Browser,
|
||||
Os: s.Os,
|
||||
Platform: s.Platform,
|
||||
LoginTime: s.LoginTime,
|
||||
Remark: s.Remark,
|
||||
Msg: s.Msg,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *SysLoginLogControl) GetId() interface{} {
|
||||
return s.ID
|
||||
}
|
||||
|
||||
type SysLoginLogById struct {
|
||||
dto.ObjectById
|
||||
}
|
||||
|
||||
func (s *SysLoginLogById) Generate() dto.Control {
|
||||
cp := *s
|
||||
return &cp
|
||||
}
|
||||
|
||||
func (s *SysLoginLogById) GenerateM() (common.ActiveRecord, error) {
|
||||
return &system.SysLoginLog{}, nil
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-admin/app/admin/models/system"
|
||||
"go-admin/common/dto"
|
||||
"go-admin/common/log"
|
||||
common "go-admin/common/models"
|
||||
"go-admin/tools"
|
||||
|
||||
"time"
|
||||
)
|
||||
|
||||
type SysOperaLogSearch struct {
|
||||
dto.Pagination `search:"-"`
|
||||
|
||||
Title string `form:"title" search:"type:contains;column:title;table:sys_opera_log" comment:"操作模块"`
|
||||
Method string `form:"method" search:"type:contains;column:method;table:sys_opera_log" comment:"函数"`
|
||||
RequestMethod string `form:"requestMethod" search:"type:contains;column:request_method;table:sys_opera_log" comment:"请求方式"`
|
||||
OperUrl string `form:"operUrl" search:"type:contains;column:oper_url;table:sys_opera_log" comment:"访问地址"`
|
||||
OperIp string `form:"operIp" search:"type:exact;column:oper_ip;table:sys_opera_log" comment:"客户端ip"`
|
||||
}
|
||||
|
||||
func (m *SysOperaLogSearch) GetNeedSearch() interface{} {
|
||||
return *m
|
||||
}
|
||||
|
||||
func (m *SysOperaLogSearch) Bind(ctx *gin.Context) error {
|
||||
msgID := tools.GenerateMsgIDFromContext(ctx)
|
||||
err := ctx.ShouldBind(m)
|
||||
if err != nil {
|
||||
log.Debugf("MsgID[%s] ShouldBind error: %s", msgID, err.Error())
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (m *SysOperaLogSearch) Generate() dto.Index {
|
||||
o := *m
|
||||
return &o
|
||||
}
|
||||
|
||||
type SysOperaLogControl struct {
|
||||
ID uint `uri:"ID" comment:"编码"` // 编码
|
||||
Title string `json:"title" comment:"操作模块"`
|
||||
BusinessType string `json:"businessType" comment:"操作类型"`
|
||||
BusinessTypes string `json:"businessTypes" comment:""`
|
||||
Method string `json:"method" comment:"函数"`
|
||||
RequestMethod string `json:"requestMethod" comment:"请求方式"`
|
||||
OperatorType string `json:"operatorType" comment:"操作类型"`
|
||||
OperName string `json:"operName" comment:"操作者"`
|
||||
DeptName string `json:"deptName" comment:"部门名称"`
|
||||
OperUrl string `json:"operUrl" comment:"访问地址"`
|
||||
OperIp string `json:"operIp" comment:"客户端ip"`
|
||||
OperLocation string `json:"operLocation" comment:"访问位置"`
|
||||
OperParam string `json:"operParam" comment:"请求参数"`
|
||||
Status string `json:"status" comment:"操作状态"`
|
||||
OperTime time.Time `json:"operTime" comment:"操作时间"`
|
||||
JsonResult string `json:"jsonResult" comment:"返回数据"`
|
||||
Remark string `json:"remark" comment:"备注"`
|
||||
LatencyTime string `json:"latencyTime" comment:"耗时"`
|
||||
UserAgent string `json:"userAgent" comment:"ua"`
|
||||
}
|
||||
|
||||
func (s *SysOperaLogControl) Bind(ctx *gin.Context) error {
|
||||
msgID := tools.GenerateMsgIDFromContext(ctx)
|
||||
err := ctx.ShouldBindUri(s)
|
||||
if err != nil {
|
||||
log.Debugf("MsgID[%s] ShouldBindUri error: %s", msgID, err.Error())
|
||||
return err
|
||||
}
|
||||
err = ctx.ShouldBind(s)
|
||||
if err != nil {
|
||||
log.Debugf("MsgID[%s] ShouldBind error: %#v", msgID, err.Error())
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *SysOperaLogControl) Generate() dto.Control {
|
||||
cp := *s
|
||||
return &cp
|
||||
}
|
||||
|
||||
func (s *SysOperaLogControl) GenerateM() (common.ActiveRecord, error) {
|
||||
return &system.SysOperaLog{
|
||||
Model: gorm.Model{ID: s.ID},
|
||||
Title: s.Title,
|
||||
BusinessType: s.BusinessType,
|
||||
BusinessTypes: s.BusinessTypes,
|
||||
Method: s.Method,
|
||||
RequestMethod: s.RequestMethod,
|
||||
OperatorType: s.OperatorType,
|
||||
OperName: s.OperName,
|
||||
DeptName: s.DeptName,
|
||||
OperUrl: s.OperUrl,
|
||||
OperIp: s.OperIp,
|
||||
OperLocation: s.OperLocation,
|
||||
OperParam: s.OperParam,
|
||||
Status: s.Status,
|
||||
OperTime: s.OperTime,
|
||||
JsonResult: s.JsonResult,
|
||||
Remark: s.Remark,
|
||||
LatencyTime: s.LatencyTime,
|
||||
UserAgent: s.UserAgent,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *SysOperaLogControl) GetId() interface{} {
|
||||
return s.ID
|
||||
}
|
||||
|
||||
type SysOperaLogById struct {
|
||||
dto.ObjectById
|
||||
}
|
||||
|
||||
func (s *SysOperaLogById) Generate() dto.Control {
|
||||
cp := *s
|
||||
return &cp
|
||||
}
|
||||
|
||||
func (s *SysOperaLogById) GenerateM() (common.ActiveRecord, error) {
|
||||
return &system.SysOperaLog{}, nil
|
||||
}
|
||||
@@ -5,7 +5,8 @@ import (
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/common/dto"
|
||||
models2 "go-admin/common/models"
|
||||
"go-admin/common/log"
|
||||
common "go-admin/common/models"
|
||||
)
|
||||
|
||||
type SysJobSearch struct {
|
||||
@@ -23,7 +24,11 @@ func (m *SysJobSearch) GetNeedSearch() interface{} {
|
||||
}
|
||||
|
||||
func (m *SysJobSearch) Bind(ctx *gin.Context) error {
|
||||
return ctx.Bind(m)
|
||||
err := ctx.ShouldBind(m)
|
||||
if err != nil {
|
||||
log.Errorf("MsgID[%s] Bind error: %s", err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (m *SysJobSearch) Generate() dto.Index {
|
||||
@@ -31,30 +36,22 @@ func (m *SysJobSearch) Generate() dto.Index {
|
||||
return &o
|
||||
}
|
||||
|
||||
func (m *SysJobSearch) GetPageIndex() int {
|
||||
return m.PageIndex
|
||||
}
|
||||
|
||||
func (m *SysJobSearch) GetPageSize() int {
|
||||
return m.PageSize
|
||||
}
|
||||
|
||||
type SysJobControl struct {
|
||||
JobId int `json:"jobId"`
|
||||
JobId uint `json:"jobId"`
|
||||
JobName string `json:"jobName" validate:"required"` // 名称
|
||||
JobGroup string `json:"jobGroup"` // 任务分组
|
||||
JobType int `json:"jobType"` // 任务类型
|
||||
CronExpression string `json:"cronExpression"` // cron表达式
|
||||
InvokeTarget string `json:"invokeTarget"` // 调用目标
|
||||
Args string `json:"args"` // 目标参数
|
||||
MisfirePolicy int `json:"misfirePolicy"` // 执行策略
|
||||
MisfirePolicy int `json:"misfirePolicy"` // 执行策略
|
||||
Concurrent int `json:"concurrent"` // 是否并发
|
||||
Status int `json:"status"` // 状态
|
||||
EntryId int `json:"entryId"` // job启动时返回的id
|
||||
EntryId int `json:"entryId"` // job启动时返回的id
|
||||
}
|
||||
|
||||
func (s *SysJobControl) Bind(ctx *gin.Context) error {
|
||||
return ctx.Bind(s)
|
||||
return ctx.ShouldBind(s)
|
||||
}
|
||||
|
||||
func (s *SysJobControl) Generate() dto.Control {
|
||||
@@ -62,7 +59,7 @@ func (s *SysJobControl) Generate() dto.Control {
|
||||
return &cp
|
||||
}
|
||||
|
||||
func (s *SysJobControl) GenerateM() (models2.ActiveRecord, error) {
|
||||
func (s *SysJobControl) GenerateM() (common.ActiveRecord, error) {
|
||||
return &models.SysJob{
|
||||
JobId: s.JobId,
|
||||
JobName: s.JobName,
|
||||
@@ -91,6 +88,20 @@ func (s *SysJobById) Generate() dto.Control {
|
||||
return &cp
|
||||
}
|
||||
|
||||
func (s *SysJobById) GenerateM() (models2.ActiveRecord, error) {
|
||||
func (s *SysJobById) GenerateM() (common.ActiveRecord, error) {
|
||||
return &models.SysJob{}, nil
|
||||
}
|
||||
|
||||
type SysJobItem struct {
|
||||
JobId uint `json:"jobId"`
|
||||
JobName string `json:"jobName" validate:"required"` // 名称
|
||||
JobGroup string `json:"jobGroup"` // 任务分组
|
||||
JobType int `json:"jobType"` // 任务类型
|
||||
CronExpression string `json:"cronExpression"` // cron表达式
|
||||
InvokeTarget string `json:"invokeTarget"` // 调用目标
|
||||
Args string `json:"args"` // 目标参数
|
||||
MisfirePolicy int `json:"misfirePolicy"` // 执行策略
|
||||
Concurrent int `json:"concurrent"` // 是否并发
|
||||
Status int `json:"status"` // 状态
|
||||
EntryId int `json:"entryId"` // job启动时返回的id
|
||||
}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"go-admin/app/admin/models/system"
|
||||
"go-admin/app/admin/service/dto"
|
||||
"go-admin/common/log"
|
||||
"go-admin/common/service"
|
||||
)
|
||||
|
||||
type SysConfig struct {
|
||||
service.Service
|
||||
}
|
||||
|
||||
// GetSysConfigByKEY 根据Key获取SysConfig
|
||||
func (e *SysConfig) GetSysConfigByKEY(c *dto.SysConfigControl) error {
|
||||
var err error
|
||||
var data system.SysConfig
|
||||
msgID := e.MsgID
|
||||
data.ConfigKey = c.ConfigKey
|
||||
err = e.Orm.Table(data.TableName()).Where("config_key = ?", data.ConfigKey).First(c).Error
|
||||
if err != nil {
|
||||
log.Errorf("msgID[%s] db error:%s", msgID, err)
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"go-admin/app/admin/models/system"
|
||||
cDto "go-admin/common/dto"
|
||||
"go-admin/common/log"
|
||||
common "go-admin/common/models"
|
||||
"go-admin/common/service"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type SysLoginLog struct {
|
||||
service.Service
|
||||
}
|
||||
|
||||
// GetSysLoginLogPage 获取SysLoginLog列表
|
||||
func (e *SysLoginLog) GetSysLoginLogPage(c cDto.Index, list *[]system.SysLoginLog, count *int64) error {
|
||||
var err error
|
||||
var data system.SysLoginLog
|
||||
msgID := e.MsgID
|
||||
|
||||
err = e.Orm.Model(&data).
|
||||
Scopes(
|
||||
cDto.MakeCondition(c.GetNeedSearch()),
|
||||
cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
|
||||
).
|
||||
Find(list).Limit(-1).Offset(-1).
|
||||
Count(count).Error
|
||||
if err != nil {
|
||||
log.Errorf("msgID[%s] db error:%s", msgID, err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetSysLoginLog 获取SysLoginLog对象
|
||||
func (e *SysLoginLog) GetSysLoginLog(d cDto.Control, model *system.SysLoginLog) error {
|
||||
var err error
|
||||
var data system.SysLoginLog
|
||||
msgID := e.MsgID
|
||||
|
||||
db := e.Orm.Model(&data).
|
||||
First(model, d.GetId())
|
||||
err = db.Error
|
||||
if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
err = errors.New("查看对象不存在或无权查看")
|
||||
log.Errorf("msgID[%s] db error:%s", msgID, err)
|
||||
return err
|
||||
}
|
||||
if db.Error != nil {
|
||||
log.Errorf("msgID[%s] db error:%s", msgID, err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// InsertSysLoginLog 创建SysLoginLog对象
|
||||
func (e *SysLoginLog) InsertSysLoginLog(model common.ActiveRecord) error {
|
||||
var err error
|
||||
var data system.SysLoginLog
|
||||
msgID := e.MsgID
|
||||
|
||||
err = e.Orm.Model(&data).
|
||||
Create(model).Error
|
||||
if err != nil {
|
||||
log.Errorf("msgID[%s] db error:%s", msgID, err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdateSysLoginLog 修改SysLoginLog对象
|
||||
func (e *SysLoginLog) UpdateSysLoginLog(c common.ActiveRecord) error {
|
||||
var err error
|
||||
var data system.SysLoginLog
|
||||
msgID := e.MsgID
|
||||
|
||||
db := e.Orm.Model(&data).
|
||||
Where(c.GetId()).Updates(c)
|
||||
if db.Error != nil {
|
||||
log.Errorf("msgID[%s] db error:%s", msgID, err)
|
||||
return err
|
||||
}
|
||||
if db.RowsAffected == 0 {
|
||||
return errors.New("无权更新该数据")
|
||||
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RemoveSysLoginLog 删除SysLoginLog
|
||||
func (e *SysLoginLog) RemoveSysLoginLog(d cDto.Control, c common.ActiveRecord) error {
|
||||
var err error
|
||||
var data system.SysLoginLog
|
||||
msgID := e.MsgID
|
||||
|
||||
db := e.Orm.Model(&data).
|
||||
Where(d.GetId()).Delete(c)
|
||||
if db.Error != nil {
|
||||
err = db.Error
|
||||
log.Errorf("MsgID[%s] Delete error: %s", msgID, err)
|
||||
return err
|
||||
}
|
||||
if db.RowsAffected == 0 {
|
||||
err = errors.New("无权删除该数据")
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"go-admin/app/admin/models/system"
|
||||
cDto "go-admin/common/dto"
|
||||
"go-admin/common/log"
|
||||
common "go-admin/common/models"
|
||||
"go-admin/common/service"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type SysOperaLog struct {
|
||||
service.Service
|
||||
}
|
||||
|
||||
// GetSysOperaLogPage 获取SysOperaLog列表
|
||||
func (e *SysOperaLog) GetSysOperaLogPage(c cDto.Index, list *[]system.SysOperaLog, count *int64) error {
|
||||
var err error
|
||||
var data system.SysOperaLog
|
||||
msgID := e.MsgID
|
||||
|
||||
err = e.Orm.Model(&data).
|
||||
Scopes(
|
||||
cDto.MakeCondition(c.GetNeedSearch()),
|
||||
cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
|
||||
).
|
||||
Find(list).Limit(-1).Offset(-1).
|
||||
Count(count).Error
|
||||
if err != nil {
|
||||
log.Errorf("msgID[%s] db error:%s", msgID, err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetSysOperaLog 获取SysOperaLog对象
|
||||
func (e *SysOperaLog) GetSysOperaLog(d cDto.Control, model *system.SysOperaLog) error {
|
||||
var err error
|
||||
var data system.SysOperaLog
|
||||
msgID := e.MsgID
|
||||
|
||||
db := e.Orm.Model(&data).
|
||||
First(model, d.GetId())
|
||||
err = db.Error
|
||||
if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
err = errors.New("查看对象不存在或无权查看")
|
||||
log.Errorf("msgID[%s] db error:%s", msgID, err)
|
||||
return err
|
||||
}
|
||||
if db.Error != nil {
|
||||
log.Errorf("msgID[%s] db error:%s", msgID, err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// InsertSysOperaLog 创建SysOperaLog对象
|
||||
func (e *SysOperaLog) InsertSysOperaLog(model common.ActiveRecord) error {
|
||||
var err error
|
||||
var data system.SysOperaLog
|
||||
msgID := e.MsgID
|
||||
|
||||
err = e.Orm.Model(&data).
|
||||
Create(model).Error
|
||||
if err != nil {
|
||||
log.Errorf("msgID[%s] db error:%s", msgID, err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdateSysOperaLog 修改SysOperaLog对象
|
||||
func (e *SysOperaLog) UpdateSysOperaLog(c common.ActiveRecord) error {
|
||||
var err error
|
||||
var data system.SysOperaLog
|
||||
msgID := e.MsgID
|
||||
|
||||
db := e.Orm.Model(&data).
|
||||
Where(c.GetId()).Updates(c)
|
||||
if db.Error != nil {
|
||||
log.Errorf("msgID[%s] db error:%s", msgID, err)
|
||||
return err
|
||||
}
|
||||
if db.RowsAffected == 0 {
|
||||
return errors.New("无权更新该数据")
|
||||
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RemoveSysOperaLog 删除SysOperaLog
|
||||
func (e *SysOperaLog) RemoveSysOperaLog(d cDto.Control, c common.ActiveRecord) error {
|
||||
var err error
|
||||
var data system.SysOperaLog
|
||||
msgID := e.MsgID
|
||||
|
||||
db := e.Orm.Model(&data).
|
||||
Where(d.GetId()).Delete(c)
|
||||
if db.Error != nil {
|
||||
err = db.Error
|
||||
log.Errorf("MsgID[%s] Delete error: %s", msgID, err)
|
||||
return err
|
||||
}
|
||||
if db.RowsAffected == 0 {
|
||||
err = errors.New("无权删除该数据")
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/app/jobs"
|
||||
"go-admin/common/dto"
|
||||
"go-admin/common/log"
|
||||
"go-admin/common/service"
|
||||
"go-admin/tools/app/msg"
|
||||
)
|
||||
|
||||
type SysJob struct {
|
||||
service.Service
|
||||
}
|
||||
|
||||
// RemoveJob 删除job
|
||||
func (e *SysJob) RemoveJob(c *dto.GeneralDelDto) error {
|
||||
var err error
|
||||
var data models.SysJob
|
||||
msgID := e.MsgID
|
||||
data.JobId = c.Id
|
||||
err = e.Orm.Table(data.TableName()).First(&data).Error
|
||||
if err != nil {
|
||||
log.Errorf("msgID[%s] db error:%s", msgID, err)
|
||||
return err
|
||||
}
|
||||
cn := jobs.Remove(data.EntryId)
|
||||
|
||||
select {
|
||||
case res := <-cn:
|
||||
if res {
|
||||
err = e.Orm.Table(data.TableName()).Where("entry_id = ?", data.EntryId).Update("entry_id", 0).Error
|
||||
if err != nil {
|
||||
log.Errorf("msgID[%s] db error:%s", msgID, err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
case <-time.After(time.Second * 1):
|
||||
e.Msg = msg.TimeOut
|
||||
return nil
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// StartJob 启动任务
|
||||
func (e *SysJob) StartJob(c *dto.GeneralGetDto) error {
|
||||
var data models.SysJob
|
||||
var err error
|
||||
msgID := e.MsgID
|
||||
err = e.Orm.Table(data.TableName()).First(&data, c.Id).Error
|
||||
if err != nil {
|
||||
log.Errorf("msgID[%s] db error:%s", msgID, err)
|
||||
return err
|
||||
}
|
||||
if data.JobType == 1 {
|
||||
var j = &jobs.HttpJob{}
|
||||
j.InvokeTarget = data.InvokeTarget
|
||||
j.CronExpression = data.CronExpression
|
||||
j.JobId = data.JobId
|
||||
j.Name = data.JobName
|
||||
data.EntryId, err = jobs.AddJob(j)
|
||||
if err != nil {
|
||||
log.Errorf("msgID[%s] jobs AddJob[HttpJob] error:%s", msgID, err)
|
||||
}
|
||||
} else {
|
||||
var j = &jobs.ExecJob{}
|
||||
j.InvokeTarget = data.InvokeTarget
|
||||
j.CronExpression = data.CronExpression
|
||||
j.JobId = data.JobId
|
||||
j.Name = data.JobName
|
||||
j.Args = data.Args
|
||||
data.EntryId, err = jobs.AddJob(j)
|
||||
if err != nil {
|
||||
log.Errorf("msgID[%s] jobs AddJob[ExecJob] error:%s", msgID, err)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = e.Orm.Table(data.TableName()).Where(c.Id).Updates(&data).Error
|
||||
if err != nil {
|
||||
log.Errorf("msgID[%s] db error:%s", msgID, err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
+15
-7
@@ -22,7 +22,7 @@ var lock sync.Mutex
|
||||
type JobCore struct {
|
||||
InvokeTarget string
|
||||
Name string
|
||||
JobId int
|
||||
JobId uint
|
||||
EntryId int
|
||||
CronExpression string
|
||||
Args string
|
||||
@@ -41,10 +41,14 @@ func (e *ExecJob) Run() {
|
||||
startTime := time.Now()
|
||||
var obj = jobList[e.InvokeTarget]
|
||||
if obj == nil {
|
||||
global.JobLogger.Warning(" ExecJob Run job nil", e)
|
||||
global.JobLogger.Warn(" ExecJob Run job nil")
|
||||
return
|
||||
}
|
||||
CallExec(obj.(JobsExec), e.Args)
|
||||
err := CallExec(obj.(JobsExec), e.Args)
|
||||
if err != nil {
|
||||
// 如果失败暂停一段时间重试
|
||||
fmt.Println(time.Now().Format(timeFormat), " [ERROR] mission failed! ", err)
|
||||
}
|
||||
// 结束时间
|
||||
endTime := time.Now()
|
||||
|
||||
@@ -54,6 +58,7 @@ func (e *ExecJob) Run() {
|
||||
//str := time.Now().Format(timeFormat) + " [INFO] JobCore " + string(e.EntryId) + "exec success , spend :" + latencyTime.String()
|
||||
//ws.SendAll(str)
|
||||
global.JobLogger.Info(time.Now().Format(timeFormat), " [INFO] JobCore ", e, "exec success , spend :", latencyTime)
|
||||
return
|
||||
}
|
||||
|
||||
//http 任务接口
|
||||
@@ -61,19 +66,21 @@ func (h *HttpJob) Run() {
|
||||
|
||||
startTime := time.Now()
|
||||
var count = 0
|
||||
var err error
|
||||
var str string
|
||||
/* 循环 */
|
||||
LOOP:
|
||||
if count < retryCount {
|
||||
/* 跳过迭代 */
|
||||
str, err := pkg.Get(h.InvokeTarget)
|
||||
str, err = pkg.Get(h.InvokeTarget)
|
||||
if err != nil {
|
||||
// 如果失败暂停一段时间重试
|
||||
fmt.Println(time.Now().Format(timeFormat), " [ERROR] mission failed! ", err)
|
||||
fmt.Printf(time.Now().Format(timeFormat)+" [INFO] Retry after the task fails %d seconds! %s \n", time.Duration(count)*time.Second, str)
|
||||
time.Sleep(time.Duration(count) * time.Second)
|
||||
fmt.Printf(time.Now().Format(timeFormat)+" [INFO] Retry after the task fails %d seconds! %s \n", (count+1)*5, str)
|
||||
time.Sleep(time.Duration(count+1) * 5 * time.Second)
|
||||
count = count + 1
|
||||
goto LOOP
|
||||
}
|
||||
count = count + 1
|
||||
}
|
||||
// 结束时间
|
||||
endTime := time.Now()
|
||||
@@ -83,6 +90,7 @@ LOOP:
|
||||
//TODO: 待完善部分
|
||||
|
||||
global.JobLogger.Info(time.Now().Format(timeFormat), " [INFO] JobCore ", h, "exec success , spend :", latencyTime)
|
||||
return
|
||||
}
|
||||
|
||||
// 初始化
|
||||
|
||||
+37
-26
@@ -3,7 +3,7 @@ package api
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"go-admin/tools/trace"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
"go-admin/app/jobs"
|
||||
"go-admin/common/database"
|
||||
"go-admin/common/global"
|
||||
"go-admin/common/log"
|
||||
mycasbin "go-admin/pkg/casbin"
|
||||
"go-admin/pkg/logger"
|
||||
"go-admin/tools"
|
||||
@@ -24,10 +25,11 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
configYml string
|
||||
port string
|
||||
mode string
|
||||
StartCmd = &cobra.Command{
|
||||
configYml string
|
||||
port string
|
||||
mode string
|
||||
traceStart bool
|
||||
StartCmd = &cobra.Command{
|
||||
Use: "server",
|
||||
Short: "Start API server",
|
||||
Example: "go-admin server -c config/settings.yml",
|
||||
@@ -41,12 +43,16 @@ var (
|
||||
}
|
||||
)
|
||||
|
||||
var echoTimes int
|
||||
var AppRouters = make([]func(), 0)
|
||||
|
||||
func init() {
|
||||
StartCmd.PersistentFlags().StringVarP(&configYml, "config", "c", "config/settings.yml", "Start server with provided configuration file")
|
||||
StartCmd.PersistentFlags().StringVarP(&port, "port", "p", "8000", "Tcp port server listening on")
|
||||
StartCmd.PersistentFlags().StringVarP(&mode, "mode", "m", "dev", "server mode ; eg:dev,test,prod")
|
||||
StartCmd.PersistentFlags().BoolVarP(&traceStart, "traceStart", "t", false, "start traceStart app dash")
|
||||
|
||||
//注册路由 fixme 其他应用的路由,在本目录新建文件放在init方法
|
||||
AppRouters = append(AppRouters, router.InitRouter)
|
||||
}
|
||||
|
||||
func setup() {
|
||||
@@ -54,14 +60,16 @@ func setup() {
|
||||
//1. 读取配置
|
||||
config.Setup(configYml)
|
||||
//2. 设置日志
|
||||
logger.Setup()
|
||||
global.Logger.Logger = logger.SetupLogger(config.LoggerConfig.Path, "bus")
|
||||
global.JobLogger.Logger = logger.SetupLogger(config.LoggerConfig.Path, "job")
|
||||
global.RequestLogger.Logger = logger.SetupLogger(config.LoggerConfig.Path, "request")
|
||||
//3. 初始化数据库链接
|
||||
database.Setup(config.DatabaseConfig.Driver)
|
||||
//4. 接口访问控制加载
|
||||
mycasbin.Setup()
|
||||
global.CasbinEnforcer = mycasbin.Setup(global.Eloquent, "sys_")
|
||||
|
||||
usageStr := `starting api server`
|
||||
global.Logger.Info(usageStr)
|
||||
log.Info(usageStr)
|
||||
|
||||
}
|
||||
|
||||
@@ -74,17 +82,14 @@ func run() error {
|
||||
engine = gin.New()
|
||||
}
|
||||
|
||||
var r *gin.Engine
|
||||
switch engine.(type) {
|
||||
case *gin.Engine:
|
||||
r = engine.(*gin.Engine)
|
||||
default:
|
||||
panic("not support this engine")
|
||||
if mode == "dev" {
|
||||
//监控
|
||||
AppRouters = append(AppRouters, router.Monitor)
|
||||
}
|
||||
|
||||
r = router.InitRouter(r)
|
||||
//defer global.Eloquent.Close()
|
||||
global.Cfg.SetEngine(r)
|
||||
for _, f := range AppRouters {
|
||||
f()
|
||||
}
|
||||
|
||||
srv := &http.Server{
|
||||
Addr: config.ApplicationConfig.Host + ":" + config.ApplicationConfig.Port,
|
||||
@@ -96,20 +101,28 @@ func run() error {
|
||||
|
||||
}()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if traceStart {
|
||||
//链路追踪, fixme 页面显示需要自备梯子
|
||||
trace.Start()
|
||||
defer trace.Stop(ctx)
|
||||
}
|
||||
|
||||
go func() {
|
||||
// 服务连接
|
||||
if config.SslConfig.Enable {
|
||||
if err := srv.ListenAndServeTLS(config.SslConfig.Pem, config.SslConfig.KeyStr); err != nil && err != http.ErrServerClosed {
|
||||
global.Logger.Fatal("listen: ", err)
|
||||
log.Fatal("listen: ", err)
|
||||
}
|
||||
} else {
|
||||
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
global.Logger.Fatal("listen: ", err)
|
||||
log.Fatal("listen: ", err)
|
||||
}
|
||||
}
|
||||
}()
|
||||
content, _ := ioutil.ReadFile("./static/go-admin.txt")
|
||||
fmt.Println(tools.Red(string(content)))
|
||||
fmt.Println(tools.Red(string(global.LogoContent)))
|
||||
tip()
|
||||
fmt.Println(tools.Green("Server run at:"))
|
||||
fmt.Printf("- Local: http://localhost:%s/ \r\n", config.ApplicationConfig.Port)
|
||||
@@ -124,12 +137,10 @@ func run() error {
|
||||
<-quit
|
||||
fmt.Printf("%s Shutdown Server ... \r\n", tools.GetCurrentTimeStr())
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
if err := srv.Shutdown(ctx); err != nil {
|
||||
global.Logger.Fatal("Server Shutdown:", err)
|
||||
log.Fatal("Server Shutdown:", err)
|
||||
}
|
||||
global.Logger.Println("Server exiting")
|
||||
log.Info("Server exiting")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1,19 +1,23 @@
|
||||
package migration
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
"log"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strconv"
|
||||
"sync"
|
||||
|
||||
"github.com/spf13/cast"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var Migrate = &Migration{
|
||||
version: make(map[string]func(db *gorm.DB, version string) error),
|
||||
version: make(map[int]func(db *gorm.DB, version string) error),
|
||||
}
|
||||
|
||||
type Migration struct {
|
||||
db *gorm.DB
|
||||
version map[string]func(db *gorm.DB, version string) error
|
||||
version map[int]func(db *gorm.DB, version string) error
|
||||
mutex sync.Mutex
|
||||
}
|
||||
|
||||
@@ -25,19 +29,20 @@ func (e *Migration) SetDb(db *gorm.DB) {
|
||||
e.db = db
|
||||
}
|
||||
|
||||
func (e *Migration) SetVersion(k string, f func(db *gorm.DB, version string) error) {
|
||||
func (e *Migration) SetVersion(k int, f func(db *gorm.DB, version string) error) {
|
||||
e.mutex.Lock()
|
||||
defer e.mutex.Unlock()
|
||||
e.version[k] = f
|
||||
}
|
||||
|
||||
func (e *Migration) Migrate() {
|
||||
versions := make([]string, 0)
|
||||
versions := make([]int, 0)
|
||||
for k := range e.version {
|
||||
versions = append(versions, k)
|
||||
}
|
||||
sort.StringsAreSorted(versions)
|
||||
log.Println(versions)
|
||||
if !sort.IntsAreSorted(versions) {
|
||||
sort.Ints(versions)
|
||||
}
|
||||
var err error
|
||||
var count int64
|
||||
for _, v := range versions {
|
||||
@@ -50,9 +55,14 @@ func (e *Migration) Migrate() {
|
||||
count = 0
|
||||
continue
|
||||
}
|
||||
err = (e.version[v])(e.db.Debug(), v)
|
||||
err = (e.version[v])(e.db.Debug(), strconv.Itoa(v))
|
||||
if err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func GetFilename(s string) int {
|
||||
s = filepath.Base(s)
|
||||
return cast.ToInt(s[:13])
|
||||
}
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
package version_local
|
||||
|
||||
func init() {
|
||||
}
|
||||
|
||||
/**
|
||||
开发者项目的迁移脚本放在这个目录里,init写法参考version目录里的migrate或者自动生成
|
||||
*/
|
||||
@@ -1,32 +1,32 @@
|
||||
package version
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
|
||||
"go-admin/app/admin/models/system"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/app/admin/models/tools"
|
||||
"go-admin/cmd/migrate/migration"
|
||||
common "go-admin/common/models"
|
||||
"gorm.io/gorm"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
func init() {
|
||||
_, fileName, _, _ := runtime.Caller(0)
|
||||
fileName = filepath.Base(fileName)
|
||||
fileName = fileName[:len(fileName)-3]
|
||||
migration.Migrate.SetVersion(fileName, _1599190683659Tables)
|
||||
migration.Migrate.SetVersion(migration.GetFilename(fileName), _1599190683659Tables)
|
||||
}
|
||||
|
||||
func _1599190683659Tables(db *gorm.DB, version string) error {
|
||||
err := db.Debug().Migrator().AutoMigrate(
|
||||
new(models.CasbinRule),
|
||||
new(models.SysDept),
|
||||
new(models.SysConfig),
|
||||
new(system.SysConfig),
|
||||
new(tools.SysTables),
|
||||
new(tools.SysColumns),
|
||||
new(models.Menu),
|
||||
new(models.LoginLog),
|
||||
new(models.SysOperLog),
|
||||
new(system.SysLoginLog),
|
||||
new(system.SysOperaLog),
|
||||
new(models.RoleMenu),
|
||||
new(models.SysRoleDept),
|
||||
new(models.SysUser),
|
||||
@@ -35,9 +35,10 @@ func _1599190683659Tables(db *gorm.DB, version string) error {
|
||||
new(models.DictData),
|
||||
new(models.DictType),
|
||||
new(models.SysJob),
|
||||
new(models.SysConfig),
|
||||
new(system.SysConfig),
|
||||
new(models.SysSetting),
|
||||
new(models.SysFileDir),
|
||||
new(models.SysFileInfo),
|
||||
new(models.SysCategory),
|
||||
new(models.SysContent),
|
||||
)
|
||||
|
||||
@@ -1,29 +1,158 @@
|
||||
package version
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/app/admin/models/system"
|
||||
"go-admin/cmd/migrate/migration"
|
||||
common "go-admin/common/models"
|
||||
"gorm.io/gorm"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
func init() {
|
||||
_, fileName, _, _ := runtime.Caller(0)
|
||||
fileName = filepath.Base(fileName)
|
||||
fileName = fileName[:len(fileName)-3]
|
||||
migration.Migrate.SetVersion(fileName, _1599190683670Test)
|
||||
migration.Migrate.SetVersion(migration.GetFilename(fileName), _1599190683670Test)
|
||||
}
|
||||
|
||||
func _1599190683670Test(db *gorm.DB, version string) error {
|
||||
return db.Transaction(func(tx *gorm.DB) error {
|
||||
|
||||
list3 := []models.SysDept{
|
||||
{DeptId: 1, ParentId: 0, DeptPath: "/0/1", DeptName: "爱拓科技", Sort: 0, Leader: "aituo", Phone: "13782218188", Email: "atuo@aituo.com", Status: "0", CreateBy: "1", UpdateBy: "1", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DeptId: 7, ParentId: 1, DeptPath: "/0/1/7", DeptName: "研发部", Sort: 1, Leader: "aituo", Phone: "13782218188", Email: "atuo@aituo.com", Status: "0", CreateBy: "1", UpdateBy: "1", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DeptId: 8, ParentId: 1, DeptPath: "/0/1/8", DeptName: "运维部", Sort: 0, Leader: "aituo", Phone: "13782218188", Email: "atuo@aituo.com", Status: "0", CreateBy: "1", UpdateBy: "1", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DeptId: 9, ParentId: 1, DeptPath: "/0/1/9", DeptName: "客服部", Sort: 0, Leader: "aituo", Phone: "13782218188", Email: "atuo@aituo.com", Status: "0", CreateBy: "1", UpdateBy: "1", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DeptId: 10, ParentId: 1, DeptPath: "/0/1/10", DeptName: "人力资源", Sort: 3, Leader: "aituo", Phone: "13782218188", Email: "atuo@aituo.com", Status: "1", CreateBy: "1", UpdateBy: "1", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
}
|
||||
|
||||
list4 := []system.SysConfig{
|
||||
{Model: gorm.Model{ID: 1, CreatedAt: time.Now(), UpdatedAt: time.Now(), DeletedAt: gorm.DeletedAt{}}, ControlBy: common.ControlBy{CreateBy: 1, UpdateBy: 1}, ConfigName: "主框架页-默认皮肤样式名称", ConfigKey: "sys_index_skinName", ConfigValue: "skin-blue", ConfigType: "Y", Remark: "蓝色 skin-blue、绿色 skin-green、紫色 skin-purple、红色 skin-red、黄色 skin-yellow"},
|
||||
{Model: gorm.Model{ID: 2, CreatedAt: time.Now(), UpdatedAt: time.Now(), DeletedAt: gorm.DeletedAt{}}, ControlBy: common.ControlBy{CreateBy: 1, UpdateBy: 1}, ConfigName: "用户管理-账号初始密码", ConfigKey: "sys.user.initPassword", ConfigValue: "123456", ConfigType: "Y", Remark: "初始化密码 123456"},
|
||||
{Model: gorm.Model{ID: 3, CreatedAt: time.Now(), UpdatedAt: time.Now(), DeletedAt: gorm.DeletedAt{}}, ControlBy: common.ControlBy{CreateBy: 1, UpdateBy: 1}, ConfigName: "主框架页-侧边栏主题", ConfigKey: "sys_index_sideTheme", ConfigValue: "theme-dark", ConfigType: "Y", Remark: "深色主题theme-dark,浅色主题theme-light"},
|
||||
}
|
||||
|
||||
list5 := []models.Post{
|
||||
{PostId: 1, PostName: "首席执行官", PostCode: "CEO", Sort: 0, Status: "0", Remark: "首席执行官", CreateBy: "1", UpdateBy: "1", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{PostId: 2, PostName: "首席技术执行官", PostCode: "CTO", Sort: 2, Status: "0", Remark: "首席技术执行官", CreateBy: "1", UpdateBy: "1", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{PostId: 3, PostName: "首席运营官", PostCode: "COO", Sort: 3, Status: "0", Remark: "测试工程师", CreateBy: "1", UpdateBy: "1", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
}
|
||||
|
||||
list6 := []models.SysRole{
|
||||
{1, "系统管理员", "0", "admin", 1, "", "1", "", "", true, "", models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}, "", []int{}, []int{}},
|
||||
}
|
||||
|
||||
list7 := []models.DictType{
|
||||
{DictId: 1, DictName: "系统开关", DictType: "sys_normal_disable", Status: "0", CreateBy: "1", UpdateBy: "1", Remark: "系统开关列表", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictId: 2, DictName: "用户性别", DictType: "sys_user_sex", Status: "0", CreateBy: "1", UpdateBy: "", Remark: "用户性别列表", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictId: 3, DictName: "菜单状态", DictType: "sys_show_hide", Status: "0", CreateBy: "1", UpdateBy: "", Remark: "菜单状态列表", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictId: 4, DictName: "系统是否", DictType: "sys_yes_no", Status: "0", CreateBy: "1", UpdateBy: "", Remark: "系统是否列表", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictId: 5, DictName: "任务状态", DictType: "sys_job_status", Status: "0", CreateBy: "1", UpdateBy: "", Remark: "任务状态列表", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictId: 6, DictName: "任务分组", DictType: "sys_job_group", Status: "0", CreateBy: "1", UpdateBy: "", Remark: "任务分组列表", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictId: 7, DictName: "通知类型", DictType: "sys_notice_type", Status: "0", CreateBy: "1", UpdateBy: "", Remark: "通知类型列表", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictId: 8, DictName: "系统状态", DictType: "sys_common_status", Status: "0", CreateBy: "1", UpdateBy: "", Remark: "登录状态列表", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictId: 9, DictName: "操作类型", DictType: "sys_oper_type", Status: "0", CreateBy: "1", UpdateBy: "", Remark: "操作类型列表", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictId: 10, DictName: "通知状态", DictType: "sys_notice_status", Status: "0", CreateBy: "1", UpdateBy: "", Remark: "通知状态列表", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
}
|
||||
|
||||
list8 := []models.SysUser{
|
||||
{models.SysUserId{1}, models.LoginM{models.UserName{"admin"}, models.PassWord{"$2a$10$cKFFTCzGOvaIHHJY2K45Zuwt8TD6oPzYi4s5MzYIBAWCLL6ZhouP2"}}, models.SysUserB{"zhangwj", "13818888888", 1, "", "", "0", "1@qq.com", 1, 1, "1", "1", "", "0", models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}, "", ""}},
|
||||
}
|
||||
|
||||
list9 := []models.DictData{
|
||||
{DictCode: 1, DictSort: 0, DictLabel: "正常", DictValue: "0", DictType: "sys_normal_disable", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "系统正常", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 2, DictSort: 0, DictLabel: "停用", DictValue: "1", DictType: "sys_normal_disable", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "系统停用", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 3, DictSort: 0, DictLabel: "男", DictValue: "0", DictType: "sys_user_sex", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "性别男", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 4, DictSort: 0, DictLabel: "女", DictValue: "1", DictType: "sys_user_sex", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "性别女", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 5, DictSort: 0, DictLabel: "未知", DictValue: "2", DictType: "sys_user_sex", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "性别未知", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 6, DictSort: 0, DictLabel: "显示", DictValue: "0", DictType: "sys_show_hide", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "显示菜单", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 7, DictSort: 0, DictLabel: "隐藏", DictValue: "1", DictType: "sys_show_hide", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "隐藏菜单", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 8, DictSort: 0, DictLabel: "是", DictValue: "Y", DictType: "sys_yes_no", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "系统默认是", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 9, DictSort: 0, DictLabel: "否", DictValue: "N", DictType: "sys_yes_no", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "系统默认否", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 10, DictSort: 0, DictLabel: "正常", DictValue: "2", DictType: "sys_job_status", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "正常状态", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 11, DictSort: 0, DictLabel: "停用", DictValue: "1", DictType: "sys_job_status", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "停用状态", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 12, DictSort: 0, DictLabel: "默认", DictValue: "DEFAULT", DictType: "sys_job_group", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "默认分组", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 13, DictSort: 0, DictLabel: "系统", DictValue: "SYSTEM", DictType: "sys_job_group", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "系统分组", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 14, DictSort: 0, DictLabel: "通知", DictValue: "1", DictType: "sys_notice_type", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "通知", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 15, DictSort: 0, DictLabel: "公告", DictValue: "2", DictType: "sys_notice_type", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "公告", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 16, DictSort: 0, DictLabel: "正常", DictValue: "0", DictType: "sys_common_status", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "正常状态", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 17, DictSort: 0, DictLabel: "关闭", DictValue: "1", DictType: "sys_common_status", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "关闭状态", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 18, DictSort: 0, DictLabel: "新增", DictValue: "1", DictType: "sys_oper_type", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "新增操作", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 19, DictSort: 0, DictLabel: "修改", DictValue: "2", DictType: "sys_oper_type", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "修改操作", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 20, DictSort: 0, DictLabel: "删除", DictValue: "3", DictType: "sys_oper_type", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "删除操作", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 21, DictSort: 0, DictLabel: "授权", DictValue: "4", DictType: "sys_oper_type", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "授权操作", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 22, DictSort: 0, DictLabel: "导出", DictValue: "5", DictType: "sys_oper_type", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "导出操作", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 23, DictSort: 0, DictLabel: "导入", DictValue: "6", DictType: "sys_oper_type", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "导入操作", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 24, DictSort: 0, DictLabel: "强退", DictValue: "7", DictType: "sys_oper_type", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "强退操作", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 25, DictSort: 0, DictLabel: "生成代码", DictValue: "8", DictType: "sys_oper_type", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "生成操作", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 26, DictSort: 0, DictLabel: "清空数据", DictValue: "9", DictType: "sys_oper_type", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "清空操作", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 27, DictSort: 0, DictLabel: "成功", DictValue: "0", DictType: "sys_notice_status", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "成功状态", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 28, DictSort: 0, DictLabel: "失败", DictValue: "1", DictType: "sys_notice_status", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "", Remark: "失败状态", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 29, DictSort: 0, DictLabel: "登录", DictValue: "10", DictType: "sys_oper_type", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "1", Remark: "登录操作", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 30, DictSort: 0, DictLabel: "退出", DictValue: "11", DictType: "sys_oper_type", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "1", Remark: "", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
{DictCode: 31, DictSort: 0, DictLabel: "获取验证码", DictValue: "12", DictType: "sys_oper_type", CssClass: "", ListClass: "", IsDefault: "", Status: "0", Default: "", CreateBy: "1", UpdateBy: "1", Remark: "获取验证码", BaseModel: models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
}
|
||||
|
||||
list10 := []models.SysSetting{
|
||||
{1, "go-admin管理系统", "https://gitee.com/mydearzwj/image/raw/master/img/go-admin.png", models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}},
|
||||
}
|
||||
|
||||
list11 := []models.SysJob{
|
||||
{1, "接口测试", "DEFAULT", 1, "0/5 * * * * ", "http://localhost:8000", "", 1, 1, 1, 0, "", "", models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}, ""},
|
||||
{2, "函数测试", "DEFAULT", 2, "0/5 * * * * ", "ExamplesOne", "参数", 1, 1, 1, 0, "", "", models.BaseModel{CreatedAt: time.Now(), UpdatedAt: time.Now()}, ""},
|
||||
}
|
||||
|
||||
err := tx.Create(list3).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = tx.Create(list4).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = tx.Create(list5).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = tx.Create(list6).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = tx.Create(list7).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = tx.Create(list8).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = tx.Create(list9).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = tx.Create(list10).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = tx.Create(list11).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := models.InitDb(tx); err != nil {
|
||||
|
||||
}
|
||||
|
||||
|
||||
return tx.Create(&common.Migration{
|
||||
Version: version,
|
||||
}).Error
|
||||
|
||||
@@ -1,19 +1,18 @@
|
||||
package version
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/cmd/migrate/migration"
|
||||
common "go-admin/common/models"
|
||||
"gorm.io/gorm"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
func init() {
|
||||
_, fileName, _, _ := runtime.Caller(0)
|
||||
fileName = filepath.Base(fileName)
|
||||
fileName = fileName[:len(fileName)-3]
|
||||
migration.Migrate.SetVersion(fileName, _1599190683680Test)
|
||||
migration.Migrate.SetVersion(migration.GetFilename(fileName), _1599190683680Test)
|
||||
}
|
||||
|
||||
func _1599190683680Test(db *gorm.DB, version string) error {
|
||||
@@ -22,7 +21,7 @@ func _1599190683680Test(db *gorm.DB, version string) error {
|
||||
|
||||
list := []models.Menu{
|
||||
{MenuId: 496, MenuName: "Sources", Title: "资源管理", Icon: "network", Path: "/sources", Paths: "/0/496", MenuType: "M", Action: "无", Permission: "", ParentId: 0, NoCache: true, Breadcrumb: "", Component: "Layout", Sort: 3, Visible: "0", CreateBy: "1", UpdateBy: "1", IsFrame: "1"},
|
||||
{MenuId: 497, MenuName: "File", Title: "文件管理", Icon: "documentation", Path: "filemanage", Paths: "/0/496/497", MenuType: "C", Action: "", Permission: "", ParentId: 496, NoCache: true, Breadcrumb: "", Component: "/filemanage/index", Sort: 0, Visible: "0", CreateBy: "1", UpdateBy: "1", IsFrame: "1"},
|
||||
{MenuId: 497, MenuName: "File", Title: "文件管理", Icon: "documentation", Path: "file-manage", Paths: "/0/496/497", MenuType: "C", Action: "", Permission: "", ParentId: 496, NoCache: true, Breadcrumb: "", Component: "/fileManage/index", Sort: 0, Visible: "0", CreateBy: "1", UpdateBy: "1", IsFrame: "1"},
|
||||
{MenuId: 498, MenuName: "", Title: "内容管理", Icon: "pass", Path: "/content", Paths: "/0/498", MenuType: "M", Action: "无", Permission: "", ParentId: 0, NoCache: true, Breadcrumb: "", Component: "Layout", Sort: 4, Visible: "0", CreateBy: "1", UpdateBy: "1", IsFrame: "1"},
|
||||
{MenuId: 499, MenuName: "SysCategory", Title: "分类", Icon: "pass", Path: "syscategory", Paths: "/0/498/499", MenuType: "C", Action: "无", Permission: "syscategory:syscategory:list", ParentId: 498, NoCache: true, Breadcrumb: "", Component: "/syscategory/index", Sort: 0, Visible: "0", CreateBy: "1", UpdateBy: "1", IsFrame: "0"},
|
||||
{MenuId: 500, MenuName: "", Title: "分页获取分类", Icon: "pass", Path: "", Paths: "/0/498/499/500", MenuType: "F", Action: "无", Permission: "syscategory:syscategory:query", ParentId: 499, NoCache: true, Breadcrumb: "", Component: "", Sort: 0, Visible: "0", CreateBy: "1", UpdateBy: "1", IsFrame: "0"},
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
package version
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/cmd/migrate/migration"
|
||||
common "go-admin/common/models"
|
||||
)
|
||||
|
||||
func init() {
|
||||
_, fileName, _, _ := runtime.Caller(0)
|
||||
migration.Migrate.SetVersion(migration.GetFilename(fileName), _1600089797118Migrate)
|
||||
}
|
||||
|
||||
func _1600089797118Migrate(db *gorm.DB, version string) error {
|
||||
return db.Transaction(func(tx *gorm.DB) error {
|
||||
f := &models.SysFileDir{
|
||||
Label: "根目录",
|
||||
PId: 0,
|
||||
Sort: 0,
|
||||
Path: "",
|
||||
CreateBy: "1",
|
||||
UpdateBy: "1",
|
||||
}
|
||||
err := tx.Create(f).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Create(&common.Migration{
|
||||
Version: version,
|
||||
}).Error
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package version
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-admin/app/admin/models"
|
||||
"go-admin/app/admin/models/system"
|
||||
"go-admin/cmd/migrate/migration"
|
||||
common "go-admin/common/models"
|
||||
)
|
||||
|
||||
func init() {
|
||||
_, fileName, _, _ := runtime.Caller(0)
|
||||
migration.Migrate.SetVersion(migration.GetFilename(fileName), _1602644950000Test)
|
||||
}
|
||||
|
||||
func _1602644950000Test(db *gorm.DB, version string) error {
|
||||
return db.Transaction(func(tx *gorm.DB) error {
|
||||
if tx.Migrator().HasColumn(&system.SysConfig{}, "config_id") {
|
||||
err := tx.Migrator().RenameColumn(&system.SysConfig{}, "config_id", "id")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
list2 := []models.CasbinRule{
|
||||
{PType: "p", V0: "admin", V1: "/api/v1/config", V2: "GET"},
|
||||
}
|
||||
err := tx.Create(list2).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
menu := models.Menu{MenuId: 86, Path: "/api/v1/config"}
|
||||
err = tx.Model(&menu).Where("menu_id = ?", 86).Update("Path", "/api/v1/config").Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return tx.Create(&common.Migration{
|
||||
Version: version,
|
||||
}).Error
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package version
|
||||
|
||||
import (
|
||||
"go-admin/app/admin/models"
|
||||
//"go-admin/app/admin/models"
|
||||
"gorm.io/gorm"
|
||||
"runtime"
|
||||
|
||||
"go-admin/cmd/migrate/migration"
|
||||
common "go-admin/common/models"
|
||||
)
|
||||
|
||||
func init() {
|
||||
_, fileName, _, _ := runtime.Caller(0)
|
||||
migration.Migrate.SetVersion(migration.GetFilename(fileName), _1603465014697Test)
|
||||
}
|
||||
|
||||
func _1603465014697Test(db *gorm.DB, version string) error {
|
||||
return db.Transaction(func(tx *gorm.DB) error {
|
||||
err := tx.Debug().Model(&models.Menu{}).Where("path = ?", "/api/v1/syscategoryList").Update("path", "/api/v1/syscategory").Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Create(&common.Migration{
|
||||
Version: version,
|
||||
}).Error
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package version
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-admin/app/admin/models/system"
|
||||
"go-admin/cmd/migrate/migration"
|
||||
common "go-admin/common/models"
|
||||
|
||||
"runtime"
|
||||
)
|
||||
|
||||
func init() {
|
||||
_, fileName, _, _ := runtime.Caller(0)
|
||||
migration.Migrate.SetVersion(migration.GetFilename(fileName), _1603516925109Test)
|
||||
}
|
||||
|
||||
func _1603516925109Test(db *gorm.DB, version string) error {
|
||||
return db.Transaction(func(tx *gorm.DB) error {
|
||||
_ = tx.Migrator().RenameTable("sys_operlog", "sys_opera_log")
|
||||
_ = tx.Migrator().RenameTable("sys_loginlog", "sys_login_log")
|
||||
|
||||
if tx.Migrator().HasColumn(&system.SysLoginLog{}, "info_id") {
|
||||
err := tx.Migrator().RenameColumn(&system.SysLoginLog{}, "info_id", "id")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if tx.Migrator().HasColumn(&system.SysOperaLog{}, "oper_id") {
|
||||
err := tx.Migrator().RenameColumn(&system.SysOperaLog{}, "oper_id", "id")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return tx.Create(&common.Migration{
|
||||
Version: version,
|
||||
}).Error
|
||||
})
|
||||
}
|
||||
+54
-18
@@ -1,20 +1,29 @@
|
||||
package migrate
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"text/template"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"go-admin/cmd/migrate/migration"
|
||||
_ "go-admin/cmd/migrate/migration/version"
|
||||
_ "go-admin/cmd/migrate/migration/version-local"
|
||||
"go-admin/common/database"
|
||||
"go-admin/common/global"
|
||||
"go-admin/common/models"
|
||||
"go-admin/pkg/logger"
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/config"
|
||||
)
|
||||
|
||||
var (
|
||||
configYml string
|
||||
exec bool
|
||||
generate bool
|
||||
goAdmin bool
|
||||
StartCmd = &cobra.Command{
|
||||
Use: "migrate",
|
||||
Short: "Initialize the database",
|
||||
@@ -27,28 +36,25 @@ var (
|
||||
|
||||
func init() {
|
||||
StartCmd.PersistentFlags().StringVarP(&configYml, "config", "c", "config/settings.yml", "Start server with provided configuration file")
|
||||
//StartCmd.PersistentFlags().BoolVarP(&exec, "exec", "e", false, "exec script")
|
||||
StartCmd.PersistentFlags().BoolVarP(&generate, "generate", "g", false, "generate migration file")
|
||||
StartCmd.PersistentFlags().BoolVarP(&goAdmin, "goAdmin", "a", false, "generate go-admin migration file")
|
||||
}
|
||||
|
||||
func run() {
|
||||
usage := `start init`
|
||||
fmt.Println(usage)
|
||||
//1. 读取配置
|
||||
config.Setup(configYml)
|
||||
//2. 设置日志
|
||||
logger.Setup()
|
||||
//3. 初始化数据库链接
|
||||
database.Setup(config.DatabaseConfig.Driver)
|
||||
//4. 数据库迁移
|
||||
fmt.Println("数据库迁移开始")
|
||||
_ = migrateModel()
|
||||
//fmt.Println("数据库结构初始化成功!")
|
||||
//5. 数据初始化完成
|
||||
//if err := models.InitDb(); err != nil {
|
||||
// global.Logger.Fatalf("数据库基础数据初始化失败!error: %v ", err)
|
||||
//}
|
||||
usage = `数据库基础数据初始化成功`
|
||||
fmt.Println(usage)
|
||||
|
||||
if !generate {
|
||||
//1. 读取配置
|
||||
config.Setup(configYml)
|
||||
//2. 设置日志
|
||||
global.Logger.Logger = logger.SetupLogger(config.LoggerConfig.Path, "bus")
|
||||
global.JobLogger.Logger = logger.SetupLogger(config.LoggerConfig.Path, "job")
|
||||
global.RequestLogger.Logger = logger.SetupLogger(config.LoggerConfig.Path, "request")
|
||||
_ = initDB()
|
||||
} else {
|
||||
_ = genFile()
|
||||
}
|
||||
}
|
||||
|
||||
func migrateModel() error {
|
||||
@@ -63,3 +69,33 @@ func migrateModel() error {
|
||||
migration.Migrate.Migrate()
|
||||
return err
|
||||
}
|
||||
func initDB() error {
|
||||
//3. 初始化数据库链接
|
||||
database.Setup(config.DatabaseConfig.Driver)
|
||||
//4. 数据库迁移
|
||||
fmt.Println("数据库迁移开始")
|
||||
_ = migrateModel()
|
||||
fmt.Println(`数据库基础数据初始化成功`)
|
||||
return nil
|
||||
}
|
||||
|
||||
func genFile() error {
|
||||
t1, err := template.ParseFiles("template/migrate.template")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
m := map[string]string{}
|
||||
m["GenerateTime"] = strconv.FormatInt(time.Now().UnixNano()/1e6, 10)
|
||||
m["Package"] = "version_local"
|
||||
if goAdmin {
|
||||
m["Package"] = "version"
|
||||
}
|
||||
var b1 bytes.Buffer
|
||||
err = t1.Execute(&b1, m)
|
||||
if goAdmin {
|
||||
tools.FileCreate(b1, "./cmd/migrate/migration/version/"+m["GenerateTime"]+"_migrate.go")
|
||||
} else {
|
||||
tools.FileCreate(b1, "./cmd/migrate/migration/version-local/"+m["GenerateTime"]+"_migrate.go")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -9,10 +9,7 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
configYml string
|
||||
port string
|
||||
mode string
|
||||
StartCmd = &cobra.Command{
|
||||
StartCmd = &cobra.Command{
|
||||
Use: "version",
|
||||
Short: "Get version info",
|
||||
Example: "go-admin version",
|
||||
|
||||
+33
-28
@@ -1,43 +1,48 @@
|
||||
package actions
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"github.com/gin-gonic/gin"
|
||||
dto2 "go-admin/common/dto"
|
||||
"go-admin/common/models"
|
||||
"gorm.io/gorm"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"go-admin/common/dto"
|
||||
"go-admin/common/log"
|
||||
"go-admin/common/models"
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
)
|
||||
|
||||
// CreateAction 通用新增动作
|
||||
func CreateAction(control dto2.Control) gin.HandlerFunc {
|
||||
func CreateAction(control dto.Control) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
db, err := tools.GetOrm(c)
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
msgID := tools.GenerateMsgIDFromContext(c)
|
||||
//新增操作
|
||||
req := control.Generate()
|
||||
var err error
|
||||
idb, exist := c.Get("db")
|
||||
if !exist {
|
||||
err = errors.New("db connect not exist")
|
||||
tools.HasError(err, "", 500)
|
||||
err = req.Bind(c)
|
||||
if err != nil {
|
||||
app.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
|
||||
return
|
||||
}
|
||||
switch idb.(type) {
|
||||
case *gorm.DB:
|
||||
//新增操作
|
||||
db := idb.(*gorm.DB)
|
||||
err = req.Bind(c)
|
||||
tools.HasError(err, "参数验证失败", 422)
|
||||
var object models.ActiveRecord
|
||||
object, err = req.GenerateM()
|
||||
tools.HasError(err, "模型生成失败", 422)
|
||||
object.SetCreateBy(tools.GetUserIdUint(c))
|
||||
err = db.WithContext(c).Create(object).Error
|
||||
tools.HasError(err, "创建失败", 500)
|
||||
app.OK(c, object.GetId(), "创建成功")
|
||||
c.Next()
|
||||
default:
|
||||
err = errors.New("db connect not exist")
|
||||
tools.HasError(err, "", 500)
|
||||
var object models.ActiveRecord
|
||||
object, err = req.GenerateM()
|
||||
if err != nil {
|
||||
app.Error(c, http.StatusInternalServerError, err, "模型生成失败")
|
||||
return
|
||||
}
|
||||
object.SetCreateBy(tools.GetUserIdUint(c))
|
||||
err = db.WithContext(c).Create(object).Error
|
||||
if err != nil {
|
||||
log.Errorf("MsgID[%s] Create error: %s", msgID, err)
|
||||
app.Error(c, http.StatusInternalServerError, err, "创建失败")
|
||||
return
|
||||
}
|
||||
app.OK(c, object.GetId(), "创建成功")
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
+44
-39
@@ -1,55 +1,60 @@
|
||||
package actions
|
||||
|
||||
import (
|
||||
"errors"
|
||||
dto2 "go-admin/common/dto"
|
||||
"go-admin/common/models"
|
||||
"go-admin/tools/app"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-admin/common/dto"
|
||||
"go-admin/common/log"
|
||||
"go-admin/common/models"
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
)
|
||||
|
||||
// DeleteAction 通用删除动作
|
||||
func DeleteAction(control dto2.Control) gin.HandlerFunc {
|
||||
func DeleteAction(control dto.Control) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
var err error
|
||||
idb, exist := c.Get("db")
|
||||
if !exist {
|
||||
err = errors.New("db connect not exist")
|
||||
tools.HasError(err, "", 500)
|
||||
db, err := tools.GetOrm(c)
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
return
|
||||
}
|
||||
switch idb.(type) {
|
||||
case *gorm.DB:
|
||||
//删除操作
|
||||
db := idb.(*gorm.DB)
|
||||
req := control.Generate()
|
||||
err = req.Bind(c)
|
||||
tools.HasError(err, "参数验证失败", 422)
|
||||
var object models.ActiveRecord
|
||||
object, err = req.GenerateM()
|
||||
tools.HasError(err, "模型生成失败", 500)
|
||||
|
||||
object.SetUpdateBy(tools.GetUserIdUint(c))
|
||||
|
||||
//数据权限检查
|
||||
p := getPermissionFromContext(c)
|
||||
|
||||
db = db.WithContext(c).Scopes(
|
||||
Permission(object.TableName(), p),
|
||||
).Where(req.GetId()).Delete(object)
|
||||
tools.HasError(db.Error, "删除失败", 500)
|
||||
if db.RowsAffected == 0 {
|
||||
err = errors.New("无权删除该数据")
|
||||
tools.HasError(err, "", 403)
|
||||
}
|
||||
app.OK(c, object.GetId(), "删除成功")
|
||||
c.Next()
|
||||
default:
|
||||
err = errors.New("db connect not exist")
|
||||
tools.HasError(err, "", 500)
|
||||
msgID := tools.GenerateMsgIDFromContext(c)
|
||||
//删除操作
|
||||
req := control.Generate()
|
||||
err = req.Bind(c)
|
||||
if err != nil {
|
||||
log.Errorf("MsgID[%s] Bind error: %s", msgID, err)
|
||||
app.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
|
||||
return
|
||||
}
|
||||
var object models.ActiveRecord
|
||||
object, err = req.GenerateM()
|
||||
if err != nil {
|
||||
app.Error(c, http.StatusInternalServerError, err, "模型生成失败")
|
||||
return
|
||||
}
|
||||
|
||||
object.SetUpdateBy(tools.GetUserIdUint(c))
|
||||
|
||||
//数据权限检查
|
||||
p := GetPermissionFromContext(c)
|
||||
|
||||
db = db.WithContext(c).Scopes(
|
||||
Permission(object.TableName(), p),
|
||||
).Where(req.GetId()).Delete(object)
|
||||
if db.Error != nil {
|
||||
log.Errorf("MsgID[%s] Delete error: %s", msgID, err)
|
||||
app.Error(c, http.StatusInternalServerError, err, "删除失败")
|
||||
return
|
||||
}
|
||||
if db.RowsAffected == 0 {
|
||||
app.Error(c, http.StatusForbidden, nil, "无权删除该数据")
|
||||
return
|
||||
}
|
||||
app.OK(c, object.GetId(), "删除成功")
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
+36
-36
@@ -2,57 +2,57 @@ package actions
|
||||
|
||||
import (
|
||||
"errors"
|
||||
dto2 "go-admin/common/dto"
|
||||
"go-admin/common/models"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-admin/common/dto"
|
||||
"go-admin/common/log"
|
||||
"go-admin/common/models"
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
)
|
||||
|
||||
// IndexAction 通用查询动作
|
||||
func IndexAction(m models.ActiveRecord, d dto2.Index, f func() interface{}) gin.HandlerFunc {
|
||||
func IndexAction(m models.ActiveRecord, d dto.Index, f func() interface{}) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
db, err := tools.GetOrm(c)
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
msgID := tools.GenerateMsgIDFromContext(c)
|
||||
list := f()
|
||||
object := m.Generate()
|
||||
req := d.Generate()
|
||||
var err error
|
||||
idb, exist := c.Get("db")
|
||||
if !exist {
|
||||
err = errors.New("db connect not exist")
|
||||
tools.HasError(err, "", 500)
|
||||
}
|
||||
var count int64
|
||||
switch idb.(type) {
|
||||
case *gorm.DB:
|
||||
//查询列表
|
||||
db := idb.(*gorm.DB)
|
||||
err = c.Bind(req)
|
||||
tools.HasError(err, "参数验证失败", 422)
|
||||
err = req.Bind(c)
|
||||
tools.HasError(err, "参数验证失败", 422)
|
||||
|
||||
//数据权限检查
|
||||
p := getPermissionFromContext(c)
|
||||
|
||||
err = db.WithContext(c).Model(object).
|
||||
Scopes(
|
||||
dto2.MakeCondition(req.GetNeedSearch()),
|
||||
dto2.Paginate(req.GetPageSize(), req.GetPageIndex()),
|
||||
Permission(object.TableName(), p),
|
||||
).
|
||||
Find(list).Limit(-1).Offset(-1).
|
||||
Count(&count).Error
|
||||
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
tools.HasError(err, "查询失败", 500)
|
||||
}
|
||||
app.PageOK(c, list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
|
||||
c.Next()
|
||||
default:
|
||||
err = errors.New("db connect not exist")
|
||||
tools.HasError(err, "", 500)
|
||||
//查询列表
|
||||
err = req.Bind(c)
|
||||
if err != nil {
|
||||
app.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
|
||||
return
|
||||
}
|
||||
|
||||
//数据权限检查
|
||||
p := GetPermissionFromContext(c)
|
||||
|
||||
err = db.WithContext(c).Model(object).
|
||||
Scopes(
|
||||
dto.MakeCondition(req.GetNeedSearch()),
|
||||
dto.Paginate(req.GetPageSize(), req.GetPageIndex()),
|
||||
Permission(object.TableName(), p),
|
||||
).
|
||||
Find(list).Limit(-1).Offset(-1).
|
||||
Count(&count).Error
|
||||
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
log.Errorf("MsgID[%s] Index error: %s", msgID, err)
|
||||
app.Error(c, http.StatusInternalServerError, err, "查询失败")
|
||||
return
|
||||
}
|
||||
app.PageOK(c, list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,15 +2,18 @@ package actions
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"go-admin/tools/config"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-admin/common/log"
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
"go-admin/tools/config"
|
||||
)
|
||||
|
||||
type dataPermission struct {
|
||||
type DataPermission struct {
|
||||
DataScope string
|
||||
UserId int
|
||||
DeptId int
|
||||
@@ -19,43 +22,31 @@ type dataPermission struct {
|
||||
|
||||
func PermissionAction() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
var err error
|
||||
idb, exist := c.Get("db")
|
||||
if !exist {
|
||||
err = errors.New("db connect not exist")
|
||||
tools.HasError(err, "", 500)
|
||||
}
|
||||
switch idb.(type) {
|
||||
case *gorm.DB:
|
||||
db := idb.(*gorm.DB)
|
||||
var p = new(dataPermission)
|
||||
if userId := tools.GetUserIdStr(c); userId != "" {
|
||||
p, err = newDataPermission(db, userId)
|
||||
if err != nil {
|
||||
c.JSON(500, gin.H{
|
||||
"code": 500,
|
||||
"msg": fmt.Sprintf("权限范围鉴定错误, error:%v", err),
|
||||
})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
}
|
||||
c.Set(PermissionKey, p)
|
||||
default:
|
||||
c.JSON(500, gin.H{
|
||||
"code": 500,
|
||||
"msg": "db connect not exist",
|
||||
})
|
||||
c.Abort()
|
||||
db, err := tools.GetOrm(c)
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
msgID := tools.GenerateMsgIDFromContext(c)
|
||||
var p = new(DataPermission)
|
||||
if userId := tools.GetUserIdStr(c); userId != "" {
|
||||
p, err = newDataPermission(db, userId)
|
||||
if err != nil {
|
||||
log.Errorf("MsgID[%s] PermissionAction error: %s", msgID, err)
|
||||
app.Error(c, http.StatusInternalServerError, err, "权限范围鉴定错误")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
}
|
||||
c.Set(PermissionKey, p)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func newDataPermission(tx *gorm.DB, userId interface{}) (*dataPermission, error) {
|
||||
func newDataPermission(tx *gorm.DB, userId interface{}) (*DataPermission, error) {
|
||||
var err error
|
||||
p := &dataPermission{}
|
||||
p := &DataPermission{}
|
||||
|
||||
err = tx.Table("sys_user").
|
||||
Select("sys_user.user_id", "sys_role.role_id", "sys_user.dept_id", "sys_role.data_scope").
|
||||
@@ -69,7 +60,7 @@ func newDataPermission(tx *gorm.DB, userId interface{}) (*dataPermission, error)
|
||||
return p, nil
|
||||
}
|
||||
|
||||
func Permission(tableName string, p *dataPermission) func(db *gorm.DB) *gorm.DB {
|
||||
func Permission(tableName string, p *DataPermission) func(db *gorm.DB) *gorm.DB {
|
||||
return func(db *gorm.DB) *gorm.DB {
|
||||
if !config.ApplicationConfig.EnableDP {
|
||||
return db
|
||||
@@ -89,13 +80,18 @@ func Permission(tableName string, p *dataPermission) func(db *gorm.DB) *gorm.DB
|
||||
}
|
||||
}
|
||||
|
||||
func getPermissionFromContext(c *gin.Context) *dataPermission {
|
||||
p := new(dataPermission)
|
||||
func getPermissionFromContext(c *gin.Context) *DataPermission {
|
||||
p := new(DataPermission)
|
||||
if pm, ok := c.Get(PermissionKey); ok {
|
||||
switch pm.(type) {
|
||||
case *dataPermission:
|
||||
p = pm.(*dataPermission)
|
||||
case *DataPermission:
|
||||
p = pm.(*DataPermission)
|
||||
}
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
// PermissionForNoAction 提供非action写法数据范围约束
|
||||
func GetPermissionFromContext(c *gin.Context) *DataPermission {
|
||||
return getPermissionFromContext(c)
|
||||
}
|
||||
+43
-38
@@ -1,53 +1,58 @@
|
||||
package actions
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"github.com/gin-gonic/gin"
|
||||
dto2 "go-admin/common/dto"
|
||||
"go-admin/common/models"
|
||||
"gorm.io/gorm"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"go-admin/common/dto"
|
||||
"go-admin/common/log"
|
||||
"go-admin/common/models"
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
)
|
||||
|
||||
// UpdateAction 通用更新动作
|
||||
func UpdateAction(control dto2.Control) gin.HandlerFunc {
|
||||
func UpdateAction(control dto.Control) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
db, err := tools.GetOrm(c)
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
msgID := tools.GenerateMsgIDFromContext(c)
|
||||
req := control.Generate()
|
||||
var err error
|
||||
idb, exist := c.Get("db")
|
||||
if !exist {
|
||||
err = errors.New("db connect not exist")
|
||||
tools.HasError(err, "", 500)
|
||||
//更新操作
|
||||
err = req.Bind(c)
|
||||
if err != nil {
|
||||
app.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
|
||||
return
|
||||
}
|
||||
switch idb.(type) {
|
||||
case *gorm.DB:
|
||||
//更新操作
|
||||
db := idb.(*gorm.DB)
|
||||
err = req.Bind(c)
|
||||
tools.HasError(err, "参数验证失败", 422)
|
||||
var object models.ActiveRecord
|
||||
object, err = req.GenerateM()
|
||||
tools.HasError(err, "参数验证失败", 422)
|
||||
object.SetUpdateBy(tools.GetUserIdUint(c))
|
||||
|
||||
//数据权限检查
|
||||
p := getPermissionFromContext(c)
|
||||
|
||||
db = db.WithContext(c).Scopes(
|
||||
Permission(object.TableName(), p),
|
||||
).Where(req.GetId()).Updates(object)
|
||||
tools.HasError(db.Error, "更新失败", 500)
|
||||
if db.RowsAffected == 0 {
|
||||
err = errors.New("无权更新该数据")
|
||||
tools.HasError(err, "", 403)
|
||||
}
|
||||
app.OK(c, object.GetId(), "更新成功")
|
||||
c.Next()
|
||||
default:
|
||||
err = errors.New("db connect not exist")
|
||||
tools.HasError(err, "", 500)
|
||||
var object models.ActiveRecord
|
||||
object, err = req.GenerateM()
|
||||
if err != nil {
|
||||
app.Error(c, http.StatusInternalServerError, err, "模型生成失败")
|
||||
return
|
||||
}
|
||||
object.SetUpdateBy(tools.GetUserIdUint(c))
|
||||
|
||||
//数据权限检查
|
||||
p := GetPermissionFromContext(c)
|
||||
|
||||
db = db.WithContext(c).Scopes(
|
||||
Permission(object.TableName(), p),
|
||||
).Where(req.GetId()).Updates(object)
|
||||
if db.Error != nil {
|
||||
log.Errorf("MsgID[%s] Update error: %s", msgID, err)
|
||||
app.Error(c, http.StatusInternalServerError, err, "更新失败")
|
||||
return
|
||||
}
|
||||
if db.RowsAffected == 0 {
|
||||
app.Error(c, http.StatusForbidden, nil, "无权更新该数据")
|
||||
return
|
||||
}
|
||||
app.OK(c, object.GetId(), "更新成功")
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
+49
-36
@@ -2,53 +2,66 @@ package actions
|
||||
|
||||
import (
|
||||
"errors"
|
||||
dto2 "go-admin/common/dto"
|
||||
"go-admin/common/models"
|
||||
"go-admin/tools/app"
|
||||
"gopkg.in/ffmt.v1"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"go-admin/common/dto"
|
||||
"go-admin/common/log"
|
||||
"go-admin/common/models"
|
||||
"go-admin/tools"
|
||||
"go-admin/tools/app"
|
||||
)
|
||||
|
||||
// ViewAction 通用详情动作
|
||||
func ViewAction(control dto2.Control) gin.HandlerFunc {
|
||||
func ViewAction(control dto.Control, f func() interface{}) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
var err error
|
||||
idb, exist := c.Get("db")
|
||||
if !exist {
|
||||
err = errors.New("db connect not exist")
|
||||
tools.HasError(err, "", 500)
|
||||
db, err := tools.GetOrm(c)
|
||||
if err != nil {
|
||||
log.Error(err)
|
||||
return
|
||||
}
|
||||
switch idb.(type) {
|
||||
case *gorm.DB:
|
||||
//查看详情
|
||||
db := idb.(*gorm.DB)
|
||||
req := control.Generate()
|
||||
err = req.Bind(c)
|
||||
tools.HasError(err, "参数验证失败", 422)
|
||||
var object models.ActiveRecord
|
||||
object, err = req.GenerateM()
|
||||
tools.HasError(err, "模型生成失败", 500)
|
||||
|
||||
//数据权限检查
|
||||
p := getPermissionFromContext(c)
|
||||
|
||||
ffmt.P(object)
|
||||
err = db.WithContext(c).Scopes(
|
||||
Permission(object.TableName(), p),
|
||||
).Where(req.GetId()).First(object).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
tools.HasError(err, "查看失败", 404)
|
||||
}
|
||||
tools.HasError(err, "查看失败", 500)
|
||||
app.OK(c, object, "查看成功")
|
||||
c.Next()
|
||||
default:
|
||||
err = errors.New("db connect not exist")
|
||||
tools.HasError(err, "", 500)
|
||||
msgID := tools.GenerateMsgIDFromContext(c)
|
||||
//查看详情
|
||||
req := control.Generate()
|
||||
err = req.Bind(c)
|
||||
if err != nil {
|
||||
app.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
|
||||
return
|
||||
}
|
||||
var object models.ActiveRecord
|
||||
object, err = req.GenerateM()
|
||||
if err != nil {
|
||||
app.Error(c, http.StatusInternalServerError, err, "模型生成失败")
|
||||
return
|
||||
}
|
||||
|
||||
var rsp interface{}
|
||||
if f != nil {
|
||||
rsp = f()
|
||||
} else {
|
||||
rsp, _ = req.GenerateM()
|
||||
}
|
||||
|
||||
//数据权限检查
|
||||
p := GetPermissionFromContext(c)
|
||||
|
||||
err = db.Model(object).WithContext(c).Scopes(
|
||||
Permission(object.TableName(), p),
|
||||
).Where(req.GetId()).First(rsp).Error
|
||||
|
||||
if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
app.Error(c, http.StatusNotFound, nil, "查看对象不存在或无权查看")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
log.Errorf("MsgID[%s] View error: %s", msgID, err)
|
||||
app.Error(c, http.StatusInternalServerError, err, "查看失败")
|
||||
return
|
||||
}
|
||||
app.OK(c, rsp, "查看成功")
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
package apis
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
"net/http"
|
||||
|
||||
"go-admin/common/models"
|
||||
"go-admin/tools"
|
||||
)
|
||||
|
||||
type Api struct {
|
||||
}
|
||||
|
||||
// GetOrm 获取Orm DB
|
||||
func (e *Api) GetOrm(c *gin.Context) (*gorm.DB, error) {
|
||||
return tools.GetOrm(c)
|
||||
}
|
||||
|
||||
// Error 通常错误数据处理
|
||||
func (e *Api) Error(c *gin.Context, code int, err error, msg string) {
|
||||
var res models.Response
|
||||
if err != nil {
|
||||
res.Msg = err.Error()
|
||||
}
|
||||
if msg != "" {
|
||||
res.Msg = msg
|
||||
}
|
||||
res.RequestId = tools.GenerateMsgIDFromContext(c)
|
||||
c.AbortWithStatusJSON(http.StatusOK, res.ReturnError(code))
|
||||
}
|
||||
|
||||
// OK 通常成功数据处理
|
||||
func (e *Api) OK(c *gin.Context, data interface{}, msg string) {
|
||||
var res models.Response
|
||||
res.Data = data
|
||||
if msg != "" {
|
||||
res.Msg = msg
|
||||
}
|
||||
res.RequestId = tools.GenerateMsgIDFromContext(c)
|
||||
c.AbortWithStatusJSON(http.StatusOK, res.ReturnOK())
|
||||
}
|
||||
|
||||
// PageOK 分页数据处理
|
||||
func (e *Api) PageOK(c *gin.Context, result interface{}, count int, pageIndex int, pageSize int, msg string) {
|
||||
var res models.Page
|
||||
res.List = result
|
||||
res.Count = count
|
||||
res.PageIndex = pageIndex
|
||||
res.PageSize = pageSize
|
||||
e.OK(c, res, msg)
|
||||
}
|
||||
|
||||
// Custom 兼容函数
|
||||
func (e *Api) Custom(c *gin.Context, data gin.H) {
|
||||
c.AbortWithStatusJSON(http.StatusOK, data)
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import (
|
||||
"database/sql"
|
||||
"net/http"
|
||||
|
||||
"go-admin/logger"
|
||||
"github.com/go-admin-team/go-admin-core/logger"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
|
||||
@@ -3,7 +3,7 @@ package config
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"go-admin/logger"
|
||||
"github.com/go-admin-team/go-admin-core/logger"
|
||||
)
|
||||
|
||||
type Conf interface {
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
// +build !sqlite3
|
||||
|
||||
package database
|
||||
|
||||
// Setup 配置数据库
|
||||
func Setup(driver string) {
|
||||
dbType := driver
|
||||
if dbType == "mysql" {
|
||||
@@ -7,12 +10,6 @@ func Setup(driver string) {
|
||||
db.Setup()
|
||||
}
|
||||
|
||||
//TODO: 如果需要sqlite3请开启下面注释
|
||||
//if dbType == "sqlite3" {
|
||||
// var db = new(SqLite)
|
||||
// db.Setup()
|
||||
//}
|
||||
|
||||
if dbType == "postgres" {
|
||||
var db = new(PgSql)
|
||||
db.Setup()
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
// +build sqlite3
|
||||
|
||||
package database
|
||||
|
||||
func Setup(driver string) {
|
||||
dbType := driver
|
||||
if dbType == "mysql" {
|
||||
var db = new(Mysql)
|
||||
db.Setup()
|
||||
}
|
||||
|
||||
if dbType == "sqlite3" {
|
||||
var db = new(SqLite)
|
||||
db.Setup()
|
||||
}
|
||||
|
||||
if dbType == "postgres" {
|
||||
var db = new(PgSql)
|
||||
db.Setup()
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package database
|
||||
|
||||
import "gorm.io/gorm"
|
||||
|
||||
// Database 数据库配置
|
||||
type Database interface {
|
||||
Setup()
|
||||
Open(conn string, cfg *gorm.Config) (db *gorm.DB, err error)
|
||||
|
||||
@@ -2,10 +2,10 @@ package database
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"log"
|
||||
"os"
|
||||
. "log"
|
||||
"time"
|
||||
|
||||
goAdminLogger "github.com/go-admin-team/go-admin-core/logger"
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
@@ -13,19 +13,22 @@ import (
|
||||
|
||||
"go-admin/common/config"
|
||||
"go-admin/common/global"
|
||||
"go-admin/common/log"
|
||||
"go-admin/tools"
|
||||
toolsConfig "go-admin/tools/config"
|
||||
)
|
||||
|
||||
// Mysql mysql配置结构体
|
||||
type Mysql struct {
|
||||
}
|
||||
|
||||
// Setup 配置步骤
|
||||
func (e *Mysql) Setup() {
|
||||
global.Source = e.GetConnect()
|
||||
global.Logger.Info(tools.Green(global.Source))
|
||||
log.Info(tools.Green(global.Source))
|
||||
db, err := sql.Open("mysql", global.Source)
|
||||
if err != nil {
|
||||
global.Logger.Fatal(tools.Red(e.GetDriver()+" connect error :"), err)
|
||||
log.Fatal(tools.Red(e.GetDriver()+" connect error :"), err)
|
||||
}
|
||||
global.Cfg.SetDb(&config.DBConfig{
|
||||
Driver: "mysql",
|
||||
@@ -37,34 +40,38 @@ func (e *Mysql) Setup() {
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
global.Logger.Fatal(tools.Red(e.GetDriver()+" connect error :"), err)
|
||||
log.Fatal(tools.Red(e.GetDriver()+" connect error :"), err)
|
||||
} else {
|
||||
global.Logger.Info(tools.Green(e.GetDriver() + " connect success !"))
|
||||
log.Info(tools.Green(e.GetDriver() + " connect success !"))
|
||||
}
|
||||
|
||||
if global.Eloquent.Error != nil {
|
||||
global.Logger.Fatal(tools.Red(" database error :"), global.Eloquent.Error)
|
||||
log.Fatal(tools.Red(" database error :"), global.Eloquent.Error)
|
||||
}
|
||||
|
||||
if toolsConfig.LoggerConfig.EnabledDB {
|
||||
global.Eloquent.Logger = logger.New(log.New(os.Stdout, "\r\n", log.LstdFlags), logger.Config{
|
||||
SlowThreshold: time.Second,
|
||||
Colorful: true,
|
||||
LogLevel: logger.Info,
|
||||
})
|
||||
global.Eloquent.Logger = logger.New(
|
||||
New(goAdminLogger.DefaultLogger.Options().Out, "\r\n", LstdFlags),
|
||||
logger.Config{
|
||||
SlowThreshold: time.Second,
|
||||
Colorful: true,
|
||||
LogLevel: logger.LogLevel(
|
||||
goAdminLogger.DefaultLogger.Options().Level.LevelForGorm()),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 打开数据库连接
|
||||
// Open 打开数据库连接
|
||||
func (e *Mysql) Open(db *sql.DB, cfg *gorm.Config) (*gorm.DB, error) {
|
||||
return gorm.Open(mysql.New(mysql.Config{Conn: db}), cfg)
|
||||
}
|
||||
|
||||
// 获取数据库连接
|
||||
// GetConnect 获取数据库连接
|
||||
func (e *Mysql) GetConnect() string {
|
||||
return toolsConfig.DatabaseConfig.Source
|
||||
}
|
||||
|
||||
// GetDriver 获取连接
|
||||
func (e *Mysql) GetDriver() string {
|
||||
return toolsConfig.DatabaseConfig.Driver
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user