Compare commits

...
17 Commits
Author SHA1 Message Date
lwnmengjing 8557e1e160 Merge pull request #384 from go-admin-team/dev
admin中的公共中间件,提到common 495a9c5
2021-03-30 22:56:52 +08:00
linwenxiang dd16744676 refactor 🎨: admin中的公共中间件,提到common 2021-03-29 09:05:05 +08:00
linwenxiang 495a9c54aa refactor 🎨: admin中的公共中间件,提到common 2021-03-28 23:27:01 +08:00
wenjianzhang afab1ef7c9 docs📝 :修正readme 2021-03-26 15:08:15 +08:00
wenjianzhang 5e99363e9a docs📝 :修正readme 2021-03-26 15:06:12 +08:00
wenjianzhang 86c7c64a32 fix🐛 :修复角色数据权限更新失(#380) 2021-03-26 14:36:18 +08:00
wenjianzhang 44b9666302 fix🐛 :修复内容模块问题(#357)
fix🐛 :修复内容模块问题(#357)
2021-03-26 13:53:44 +08:00
wenjianzhang 91c9a2c7f9 fix🐛 :修复内容模块问题(#357) 2021-03-26 13:42:12 +08:00
wenjianzhang a65930b35b fix🐛 :修复已知bug (#377) 2021-03-26 09:03:21 +08:00
linwenxiang 9023b620fb Merge branch 'master' into dev 2021-03-25 22:28:24 +08:00
linwenxiang f188b34253 feat ✨: 使用runtime cache中的mq功能优化日志存储
perf 👌: 启用mq将日志存储从中间件中移除到消费者
2021-03-25 22:26:33 +08:00
wenjianzhang 8faf6c9aba docs📝 :更新readme 2021-03-25 19:14:42 +08:00
wenjianzhang 547a5eb8e4 fix🐛 :修复初始化Duplicate column name 'is_frontend' (#376) 2021-03-25 18:35:09 +08:00
linwenxiang 2459c877e0 Merge branch 'dev' 2021-03-25 14:47:12 +08:00
linwenxiang 93625a6d9f format 🥚:模版生成优化 2021-03-25 14:45:39 +08:00
linwenxiang 58b439f553 修复个人中心修改密码不生效问题 2021-03-25 11:34:30 +08:00
linwenxiang 78c67185fd 升级core依赖 2021-03-24 23:00:09 +08:00
42 changed files with 594 additions and 498 deletions
+1
View File
@@ -21,3 +21,4 @@ cmd/migrate/migration/version-local/*
# go sum
go.sum
config/settings.deva.yml
+117 -90
View File
@@ -23,6 +23,10 @@
- GORM-based database storage that can expand many types of databases
- Simple model mapping of configuration files to quickly get the desired configuration
- Form builder
- Multi command mode
- TODO: unit test
@@ -39,102 +43,90 @@
8. Operation log: system normal operation log record and query; system exception information log record and query.
9. Login log: The system login log record query contains login exceptions.
10. System interface: Automatically generate related api interface documents according to business code.
11. Multi command mode code generation: according to the data table structure to generate the corresponding business, all visual programming, basic business can be 0 code.
12. Form construction: Customize page style, drag and drop to achieve page layout.
13. Service monitoring: view the basic information of some servers.
## Configuration details
## 🗞 System architecture
1. Configuration file description
```yml
settings:
application:
# Project launch environment
env: dev
# When env: demo, prompts for request operations other than GET
envmsg: "谢谢您的参与,但为了大家更好的体验,所以本次提交就算了吧!"
# Host IP or domain name, default 0.0.0.0
host: 0.0.0.0
# Whether to initialize the database structure and basic data; true: required; false: not required
isinit: false
# JWT encrypted string
jwtsecret: 123abc
# log storage path
logpath: temp/logs/log.log
# application name
name: go-admin
# application port
port: 8000
readtimeout: 1
writertimeout: 2
database:
# database name
database: dbname
# database type
dbtype: mysql
# database host
host: 127.0.0.1
# database password
password: password
# database port
port: 3306
# database username
username: root
redis:
# redis addresss
addr: 0.0.0.0:6379
# db
db: 0
# password
password: password
# read timeout
readtimeout: 50
```
<p align="center">
<img src="https://gitee.com/mydearzwj/image/raw/d9f59ea603e3c8a3977491a1bfa8f122e1a80824/img/go-admin-system.png" width="936px" height="491px">
</p>
2. file path go-admin/config/settings.yml
## 📦 Local development
## 📦 evelopment
First start instructions
### Create development directory
```bash
# Get the code
git clone https://github.com/wenjianzhang/go-admin.git
mkdir goadmin
cd goadmin
```
# Enter working path
### Get code
> Key points: two projects must be placed in the same folder;
```bash
# Get backend code
git clone https://github.com/go-admin-team/go-admin.git
# Get front end code
git clone https://github.com/go-admin-team/go-admin-ui.git
```
### Start up instructions
#### Server startup instructions
```bash
# Enter the go-admin backend project
cd ./go-admin
# Build the project
# Compile project
go build
# Change setting
vi ./config/setting.yml (Note: Change isinit and database connection)
# Configuration
# file path go-admin/config/settings.yml
vi ./config/setting.yml
# 1. Database information in the configuration file
# Note: the corresponding configuration data under settings.database
# 2. Confirm database initialization parameters
# Note: If this is the first time settings.application.isinit is set, please set the current value to true, the system will automatically initialize the database structure and basic data information;
# 3. Confirm the log path
# 1. Modifying database information in configuration file
# settings.database Corresponding configuration data under
# 2. Confirm log path
```
#### Initialize the database and start the service
```
# The first configuration needs to initialize the database resource information
./go-admin migrate -c config/settings.yml
# Start the project or debug with the IDE
./go-admin
# Start the project, you can also debug with IDE
./go-admin server -c config/settings.yml
```
#### Using docker to compile and start
```shell
# Compile image
docker build -t go-admin .
# Start the container. The first go admin is the container name and the second go admin is the image name
docker run --name go-admin -p 8000:8000 -v /config/settings.yml:/config/settings.yml -d go-admin
# See also instructions in WIKI
```
Document generation
#### Document generation
```bash
swag init
go generate
```
If there is no `swag` command go get installed
```bash
go get -u github.com/swaggo/swag/cmd/swag
```
Cross compilation
#### Cross compiling
```bash
env GOOS=windows GOARCH=amd64 go build main.go
@@ -143,11 +135,56 @@ env GOOS=windows GOARCH=amd64 go build main.go
env GOOS=linux GOARCH=amd64 go build main.go
```
### UI interactive terminal startup description
## 🔗 Online Demo
```bash
# Installation dependency
npm install
# It is recommended that you do not use cnpm to install dependencies directly. There will be all kinds of weird bugs. The problem of slow download speed of NPM can be solved by the following operations
npm install --registry=https://registry.npm.taobao.org
# Start the service
npm run dev
```
## 🎬 Online Demo
> admin / 123456
Demo address:[http://www.zhangwj.com](http://www.zhangwj.com/#/login)
Demo:[http://www.go-admin.dev](http://www.go-admin.dev/#/login)
## 📨 Interaction
<table>
<tr>
<td><img src="https://raw.githubusercontent.com/wenjianzhang/image/master/img/wx.png" width="180px"></td>
<td><img src="https://raw.githubusercontent.com/wenjianzhang/image/master/img/qq.png" width="200px"></td>
<td><img src="https://raw.githubusercontent.com/wenjianzhang/image/master/img/qq2.png" width="200px"></td>
</tr>
<tr>
<td>WeChat</td>
<td>This QQ group is full</td>
<td><a target="_blank" href="https://shang.qq.com/wpa/qunwpa?idkey=0f2bf59f5f2edec6a4550c364242c0641f870aa328e468c4ee4b7dbfb392627b"><img border="0" src="https://pub.idqqimg.com/wpa/images/group.png" alt="go-admin技术交流乙号" title="go-admin技术交流乙号"></a></td>
</tr>
</table>
## 💎 Member
<a href="https://github.com/wenjianzhang"> <img src="https://avatars.githubusercontent.com/u/3890175?s=460&u=20eac63daef81588fbac611da676b99859319251&v=4" width="80px"></a>
<a href="https://github.com/lwnmengjing"> <img src="https://avatars.githubusercontent.com/u/12806223?s=400&u=a89272dce50100b77b4c0d5c81c718bf78ebb580&v=4" width="80px"></a>
<a href="https://github.com/chengxiao"> <img src="https://avatars.githubusercontent.com/u/1379545?s=460&u=557da5503d0ac4a8628df6b4075b17853d5edcd9&v=4" width="80px"></a>
<a href="https://github.com/bing127"> <img src="https://avatars.githubusercontent.com/u/31166183?s=460&u=c085bff88df10bb7676c8c0351ba9dcd031d1fb3&v=4" width="80px"></a>
## JetBrains Open source certificate support
The go admin project has always been developed in the GoLand integrated development environment of JetBrains company, based on the * * free JetBrains open source license (s) * * genuine free license. I would like to express my thanks.
<a href="https://www.jetbrains.com/?from=kubeadm-ha" target="_blank"><img src="https://raw.githubusercontent.com/panjf2000/illustrations/master/jetbrains/jetbrains-variant-4.png" width="250" align="middle"/></a>
## 🤝 Open source projects used
@@ -169,20 +206,10 @@ Demo address:[http://www.zhangwj.com](http://www.zhangwj.com/#/login)
## Version
#### 2020-03-15 New Features and Optimization
1. Add user avatar upload
2. Add user password modification
3. Operation log page adjustment
4. Optimize captcha background color
I saw a lot of friends who experience the wrong verification code, so I adjusted the contrast for everyone to experience!
## 🤝 Thanks
[chengxiao](https://github.com/chengxiao)
2. [chengxiao](https://github.com/chengxiao)
## License
@@ -191,4 +218,4 @@ I saw a lot of friends who experience the wrong verification code, so I adjusted
Copyright (c) 2020 wenjianzhang
[中文]qq technical exchange group: 74520518
[中文]qq technical exchange group: 74520518
+4 -6
View File
@@ -163,7 +163,7 @@ vi ./config/setting.yml
# 启动项目,也可以用IDE进行调试
./go-admin server -c config/settings.yml -p 8000
./go-admin server -c config/settings.yml
```
@@ -174,7 +174,8 @@ vi ./config/setting.yml
docker build -t go-admin .
# 启动容器,第一个go-admin是容器名字,第二个go-admin是镜像名称
docker run --name go-admin -p 8000:8000 -d go-admin
# -v 映射配置文件 本地路径:容器路径
docker run --name go-admin -p 8000:8000 -v /config/settings.yml:/config/settings.yml -d go-admin-server
```
@@ -182,10 +183,7 @@ docker run --name go-admin -p 8000:8000 -d go-admin
#### 文档生成
```bash
swag init
# 如果没有swag命令 go get安装一下即可
go get -u github.com/swaggo/swag/cmd/swag
go generate
```
#### 交叉编译
+2 -5
View File
@@ -326,16 +326,13 @@ func (e *SysUser) SysUserUpdatePwd(c *gin.Context) {
// 数据权限检查
p := actions.GetPermissionFromContext(c)
object := &system.SysUser{
UserId: p.UserId,
Password: pwd.Password,
}
serviceSysUser := service.SysUser{}
serviceSysUser.Orm = db
serviceSysUser.Log = log
err = serviceSysUser.UpdateSysUser(object, p)
err = serviceSysUser.UpdateSysUserPwd(user.GetUserId(c), pwd.OldPassword, pwd.NewPassword, p)
if err != nil {
log.Error(err)
e.Error(c, http.StatusForbidden, err, "密码修改失败")
return
}
e.OK(c, nil, "密码修改成功")
+31 -27
View File
@@ -1,6 +1,7 @@
package sys_dept
import (
"github.com/go-admin-team/go-admin-core/sdk/pkg"
"net/http"
"github.com/gin-gonic/gin"
@@ -254,30 +255,33 @@ func (e *SysDept) GetDeptTree(c *gin.Context) {
e.OK(c, list, "")
}
//func (e *SysDept) GetDeptTreeRoleSelect(c *gin.Context) {
// log := e.GetLogger(c)
// db, err := tools.GetOrm(c)
// if err != nil {
// log.Error(err)
// return
// }
//
// s := service.SysDept{}
// s.Orm = db
// s.MsgID = msgID
// id, err := tools.StringToInt(c.Param("roleId"))
// result, err := s.SetDeptLabel()
// if err != nil {
// log.Errorf("SetDeptLabel error, %s", msgID, err.Error())
// e.Error(c, http.StatusInternalServerError, err, "")
// }
// menuIds := make([]int, 0)
// if id != 0 {
// menuIds, err = s.GetRoleDeptId(id)
// tools.HasError(err, "抱歉未找到相关信息", -1)
// }
// e.OK(c, gin.H{
// "depts": result,
// "checkedKeys": menuIds,
// }, "")
//}
func (e *SysDept) GetDeptTreeRoleSelect(c *gin.Context) {
log := e.GetLogger(c)
db, err := e.GetOrm(c)
if err != nil {
log.Error(err)
return
}
s := service.SysDept{}
s.Orm = db
s.Log = log
id, err := pkg.StringToInt(c.Param("roleId"))
result, err := s.SetDeptLabel()
if err != nil {
log.Errorf("SetDeptLabel error, %s", err.Error())
e.Error(c, http.StatusInternalServerError, err, "")
}
menuIds := make([]int, 0)
if id != 0 {
menuIds, err = s.GetRoleDeptId(id)
if err != nil {
log.Errorf("抱歉未找到相关信息, %s", err.Error())
e.Error(c, http.StatusInternalServerError, err, "")
}
}
e.OK(c, gin.H{
"depts": result,
"checkedKeys": menuIds,
}, "")
}
+3 -3
View File
@@ -8,8 +8,8 @@ type SysCategory struct {
models.Model
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:状态"` //
Sort int `json:"sort" gorm:"type:int(4);comment:排序"` //
Status int `json:"status" gorm:"type:int(1);comment:状态"` //
Remark string `json:"remark" gorm:"type:varchar(255);comment:备注"` //
models.ControlBy
models.ModelTime
@@ -26,4 +26,4 @@ func (e *SysCategory) Generate() models.ActiveRecord {
func (e *SysCategory) GetId() interface{} {
return e.Id
}
}
+3 -6
View File
@@ -2,18 +2,15 @@ package models
import (
"go-admin/common/models"
"time"
)
type SysChinaAreaData struct {
models.Model
models.ControlBy
PId string `json:"pId" gorm:"type:int(11);comment:上级编码"`
Name string `json:"name" gorm:"type:varchar(128);comment:名称"`
CreateTime time.Time `json:"createTime" gorm:"type:timestamp;comment:CreateTime"`
UpdateTime time.Time `json:"updateTime" gorm:"type:timestamp;comment:UpdateTime"`
DeleteTime time.Time `json:"deleteTime" gorm:"type:timestamp;comment:DeleteTime"`
models.ControlBy
models.ModelTime
}
func (SysChinaAreaData) TableName() string {
@@ -27,4 +24,4 @@ func (e *SysChinaAreaData) Generate() models.ActiveRecord {
func (e *SysChinaAreaData) GetId() interface{} {
return e.Id
}
}
+7 -111
View File
@@ -5,22 +5,24 @@ import (
)
type SysContent struct {
Id int `json:"id" gorm:"type:int(11);primaryKey;autoIncrement"` // id
CateId string `json:"cateId" gorm:"type:int(11);comment:分类id"`
models.Model
CateId int `json:"cateId" gorm:"type:int(11);comment:分类id"`
Name string `json:"name" gorm:"type:varchar(255);comment:名称"`
Status string `json:"status" gorm:"type:int(1);comment:状态"`
Status int `json:"status" gorm:"type:int(1);comment:状态"`
Img string `json:"img" gorm:"type:varchar(255);comment:图片"`
Content string `json:"content" gorm:"type:text;comment:内容"`
Remark string `json:"remark" gorm:"type:varchar(255);comment:备注"`
Sort string `json:"sort" gorm:"type:int(4);comment:排序"`
Sort int `json:"sort" gorm:"type:int(4);comment:排序"`
models.ControlBy
models.ModelTime
}
// TableName
func (SysContent) TableName() string {
return "sys_content"
}
// Generate
func (e *SysContent) Generate() models.ActiveRecord {
o := *e
return &o
@@ -28,110 +30,4 @@ func (e *SysContent) Generate() models.ActiveRecord {
func (e *SysContent) GetId() interface{} {
return e.Id
}
//// 创建SysContent
//func (e *SysContent) Create() (SysContent, error) {
// var doc SysContent
// result := orm.Eloquent.Table(e.TableName()).Create(&e)
// if result.Error != nil {
// err := result.Error
// return doc, err
// }
// doc = *e
// return doc, nil
//}
//
//// 获取SysContent
//func (e *SysContent) Get() (SysContent, error) {
// var doc SysContent
// table := orm.Eloquent.Table(e.TableName())
//
// if e.Id != 0 {
// table = table.Where("id = ?", e.Id)
// }
//
// if e.CateId != "" {
// table = table.Where("cate_id = ?", e.CateId)
// }
//
// if e.Name != "" {
// table = table.Where("name like ?", "%"+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
//}
//
//// 获取SysContent带分页
//func (e *SysContent) GetPage(pageSize int, pageIndex int) ([]SysContent, int, error) {
// var doc []SysContent
//
// table := orm.Eloquent.Table(e.TableName())
//
// if e.CateId != "" {
// table = table.Where("cate_id = ?", e.CateId)
// }
//
// if e.Name != "" {
// table = table.Where("name like ?", "%"+e.Name+"%")
// }
//
// if e.Status != "" {
// table = table.Where("status = ?", e.Status)
// }
//
// // 数据权限控制(如果不需要数据权限请将此处去掉)
// dataPermission := new(system.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
//}
//
//// 更新SysContent
//func (e *SysContent) Update(id int) (update SysContent, 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).Where("id = ?", id).Updates(&e).Error; err != nil {
// return
// }
// return
//}
//
//// 删除SysContent
//func (e *SysContent) Delete(id int) (success bool, err error) {
// if err = orm.Eloquent.Table(e.TableName()).Where("id = ?", id).Delete(&SysContent{}).Error; err != nil {
// success = false
// return
// }
// success = true
// return
//}
//
////批量删除
//func (e *SysContent) BatchDelete(id []int) (Result bool, err error) {
// if err = orm.Eloquent.Table(e.TableName()).Where("id in (?)", id).Delete(&SysContent{}).Error; err != nil {
// return
// }
// Result = true
// return
//}
}
+37 -2
View File
@@ -1,9 +1,15 @@
package system
import (
"go-admin/common/models"
"encoding/json"
"errors"
"time"
"github.com/go-admin-team/go-admin-core/cache"
log "github.com/go-admin-team/go-admin-core/logger"
"github.com/go-admin-team/go-admin-core/sdk"
"go-admin/common/models"
)
type SysLoginLog struct {
@@ -35,3 +41,32 @@ func (e *SysLoginLog) Generate() models.ActiveRecord {
func (e *SysLoginLog) GetId() interface{} {
return e.Id
}
// SaveLoginLog 从队列中获取登录日志
func SaveLoginLog(message cache.Message) (err error) {
//准备db
db := sdk.Runtime.GetDbByKey(message.GetPrefix())
if db == nil {
err = errors.New("db not exist")
log.Errorf("host[%s]'s %s", message.GetPrefix(), err.Error())
return err
}
var rb []byte
rb, err = json.Marshal(message.GetValues())
if err != nil {
log.Errorf("json Marshal error, %s", err.Error())
return err
}
var l SysLoginLog
err = json.Unmarshal(rb, &l)
if err != nil {
log.Errorf("json Unmarshal error, %s", err.Error())
return err
}
err = db.Create(&l).Error
if err != nil {
log.Errorf("db create error, %s", err.Error())
return err
}
return nil
}
+42 -2
View File
@@ -1,9 +1,15 @@
package system
import (
"go-admin/common/models"
"encoding/json"
"errors"
"time"
"github.com/go-admin-team/go-admin-core/cache"
log "github.com/go-admin-team/go-admin-core/logger"
"github.com/go-admin-team/go-admin-core/sdk"
"go-admin/common/models"
)
type SysOperaLog struct {
@@ -43,3 +49,37 @@ func (e *SysOperaLog) Generate() models.ActiveRecord {
func (e *SysOperaLog) GetId() interface{} {
return e.Id
}
// SaveOperaLog 从队列中获取操作日志
func SaveOperaLog(message cache.Message) (err error) {
//准备db
db := sdk.Runtime.GetDbByKey(message.GetPrefix())
if db == nil {
err = errors.New("db not exist")
log.Errorf("host[%s]'s %s", message.GetPrefix(), err.Error())
return err
}
var rb []byte
rb, err = json.Marshal(message.GetValues())
if err != nil {
log.Errorf("json Marshal error, %s", err.Error())
return err
}
var l SysOperaLog
err = json.Unmarshal(rb, &l)
if err != nil {
log.Errorf("json Unmarshal error, %s", err.Error())
return err
}
if l.Title == "" {
m := &SysMenu{}
db.Model(m).Select("Title").Where("action = ?", l.Method).Where("path = ?", message.GetValues()["_fullPath"]).First(m)
l.Title = m.Title
}
err = db.Create(&l).Error
if err != nil {
log.Errorf("db create error, %s", err.Error())
return err
}
return nil
}
+8 -10
View File
@@ -1,19 +1,17 @@
package router
import (
"github.com/go-admin-team/go-admin-core/sdk"
"github.com/go-admin-team/go-admin-core/sdk/api"
"github.com/go-admin-team/go-admin-core/sdk/pkg"
"os"
"github.com/gin-gonic/gin"
log "github.com/go-admin-team/go-admin-core/logger"
"go-admin/app/admin/middleware"
"go-admin/app/admin/middleware/handler"
common "go-admin/common/middleware"
"github.com/go-admin-team/go-admin-core/sdk"
"github.com/go-admin-team/go-admin-core/sdk/api"
"github.com/go-admin-team/go-admin-core/sdk/config"
"github.com/go-admin-team/go-admin-core/sdk/pkg"
common "go-admin/common/middleware"
"go-admin/common/middleware/handler"
)
// InitRouter 路由初始化,不要怀疑,这里用到了
@@ -38,9 +36,9 @@ func InitRouter() {
r.Use(common.Sentinel()).
Use(common.RequestId(pkg.TrafficKey)).
Use(api.SetRequestLogger)
middleware.InitMiddleware(r)
common.InitMiddleware(r)
// the jwt middleware
authMiddleware, err := middleware.AuthInit()
authMiddleware, err := common.AuthInit()
if err != nil {
log.Fatalf("JWT Init Error, %s", err.Error())
}
+13 -11
View File
@@ -1,24 +1,24 @@
package router
import (
"go-admin/app/admin/apis/system/sys_menu"
//"go-admin/app/admin/models/tools"
middleware2 "go-admin/common/middleware"
"mime"
"github.com/gin-gonic/gin"
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
"github.com/go-admin-team/go-admin-core/sdk/pkg/ws"
ginSwagger "github.com/swaggo/gin-swagger"
"github.com/swaggo/gin-swagger/swaggerFiles"
"go-admin/app/admin/apis/monitor"
"go-admin/app/admin/apis/public"
"go-admin/app/admin/apis/system"
"go-admin/app/admin/apis/system/dict"
"go-admin/app/admin/apis/system/sys_dept"
"go-admin/app/admin/apis/system/sys_menu"
"go-admin/app/admin/apis/tools"
"go-admin/app/admin/middleware/handler"
"go-admin/common/middleware"
"go-admin/common/middleware/handler"
_ "go-admin/docs"
"github.com/gin-gonic/gin"
ginSwagger "github.com/swaggo/gin-swagger"
"github.com/swaggo/gin-swagger/swaggerFiles"
)
func InitSysRouter(r *gin.Engine, authMiddleware *jwt.GinJWTMiddleware) *gin.RouterGroup {
@@ -119,12 +119,14 @@ func sysCheckRoleRouterInit(r *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddle
func registerBaseRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
api := sys_menu.SysMenu{}
v1auth := v1.Group("").Use(authMiddleware.MiddlewareFunc()).Use(middleware2.AuthCheckRole())
api2 := sys_dept.SysDept{}
v1auth := v1.Group("").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
{
//v1auth.GET("/getinfo", system.GetInfo)
v1auth.GET("/roleMenuTreeselect/:roleId", api.GetMenuTreeSelect)
v1.GET("/menuTreeselect", api.GetMenuTreeSelect)
//v1auth.GET("/roleDeptTreeselect/:roleId", system.GetDeptTreeRoleselect)
v1auth.GET("/roleDeptTreeselect/:roleId", api2.GetDeptTreeRoleSelect)
//GetDeptTreeRoleselect)
v1auth.POST("/logout", handler.LogOut)
}
}
@@ -169,7 +171,7 @@ func registerBaseRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddlewar
func registerDictRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
dictApi := &dict.SysDictType{}
dataApi := &dict.SysDictData{}
dicts := v1.Group("/dict").Use(authMiddleware.MiddlewareFunc()).Use(middleware2.AuthCheckRole())
dicts := v1.Group("/dict").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
{
dicts.GET("/data", dataApi.GetSysDictDataList)
+8 -13
View File
@@ -12,8 +12,8 @@ import (
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:"状态"`
Status string `form:"status" search:"type:exact;column:status;table:sys_category" comment:"状态"`
CateId int `form:"cateId" search:"type:exact;column:cate_id;table:sys_category" comment:"分类id"`
}
func (m *SysCategorySearch) GetNeedSearch() interface{} {
@@ -35,16 +35,11 @@ func (m *SysCategorySearch) Generate() dto.Index {
}
type SysCategoryControl struct {
ID int `uri:"Id" comment:"标识"` // 标识
Name string `json:"name" comment:"名称"`
Img string `json:"img" comment:"图标"`
Sort string `json:"sort" comment:"排序"`
Status string `json:"status" comment:"状态"`
ID int `uri:"Id" comment:"标识"`
Name string `json:"name" comment:"名称"`
Img string `json:"img" comment:"图标"`
Sort int `json:"sort" comment:"排序"`
Status int `json:"status" comment:"状态"`
Remark string `json:"remark" comment:"备注"`
}
@@ -93,4 +88,4 @@ func (s *SysCategoryById) Generate() dto.Control {
func (s *SysCategoryById) GenerateM() (common.ActiveRecord, error) {
return &models.SysCategory{}, nil
}
}
+7 -5
View File
@@ -11,6 +11,8 @@ import (
type SysContentSearch 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 *SysContentSearch) GetNeedSearch() interface{} {
@@ -33,13 +35,13 @@ func (m *SysContentSearch) Generate() dto.Index {
type SysContentControl struct {
ID int `uri:"ID" comment:""` //
CateId string `json:"cateId" comment:""`
CateId int `json:"cateId" comment:""`
Name string `json:"name" comment:""`
Status string `json:"status" comment:""`
Status int `json:"status" comment:""`
Img string `json:"img" comment:""`
Content string `json:"content" comment:""`
Remark string `json:"remark" comment:""`
Sort string `json:"sort" comment:""`
Sort int `json:"sort" comment:""`
}
func (s *SysContentControl) Bind(ctx *gin.Context) error {
@@ -63,7 +65,7 @@ func (s *SysContentControl) Generate() dto.Control {
func (s *SysContentControl) GenerateM() (common.ActiveRecord, error) {
return &models.SysContent{
Id: s.ID,
Model: common.Model{s.ID},
CateId: s.CateId,
Name: s.Name,
Status: s.Status,
@@ -89,4 +91,4 @@ func (s *SysContentById) Generate() dto.Control {
func (s *SysContentById) GenerateM() (common.ActiveRecord, error) {
return &models.SysContent{}, nil
}
}
+2 -2
View File
@@ -50,7 +50,7 @@ type SysRoleControl struct {
Flag string `form:"flag" comment:"标记"` // 标记
Remark string `form:"remark" comment:"备注"` // 备注
Admin bool `form:"admin" comment:"是否管理员"`
DataScope string `form:"dataScope" comment:"是否管理员"`
DataScope string `form:"dataScope"`
MenuIds []int `json:"menuIds"`
}
@@ -123,4 +123,4 @@ type RoleDataScopeReq struct {
type DeptIdList struct {
DeptId int `json:"DeptId"`
}
}
+2 -1
View File
@@ -113,5 +113,6 @@ func (s *SysUserById) GenerateM() (common.ActiveRecord, error) {
// PassWord 密码
type PassWord struct {
Password string `json:"password"`
NewPassword string `json:"newPassword" binding:"required"`
OldPassword string `json:"oldPassword" binding:"required"`
}
+1 -4
View File
@@ -59,9 +59,6 @@ func (s *SysChinaAreaDataControl) Generate() (*models.SysChinaAreaData, error) {
Model: common.Model{Id: s.Id},
PId: s.PId,
Name: s.Name,
CreateTime: s.CreateTime,
UpdateTime: s.UpdateTime,
DeleteTime: s.DeleteTime,
}, nil
}
@@ -98,4 +95,4 @@ func (s *SysChinaAreaDataById) Bind(ctx *gin.Context) error {
func (s *SysChinaAreaDataById) SetUpdateBy(id int) {
}
}
+64 -63
View File
@@ -2,6 +2,7 @@ package service
import (
"errors"
log "github.com/go-admin-team/go-admin-core/logger"
"github.com/go-admin-team/go-admin-core/sdk/pkg"
"gorm.io/gorm"
@@ -220,66 +221,66 @@ func (e *SysDept) deptPageCall(deptlist *[]system.SysDept, menu system.SysDept)
return menu
}
//// GetRoleDeptId 获取角色的部门ID集合
//func (e *SysDept) GetRoleDeptId(roleId int) ([]int, error) {
// deptIds := make([]int, 0)
// deptList := make([]dto.DeptIdList, 0)
// if err := e.Orm.Table("sys_role_dept").
// Select("sys_role_dept.dept_id").
// Joins("LEFT JOIN sys_dept on sys_dept.dept_id=sys_role_dept.dept_id").
// Where("role_id = ? ", roleId).
// Where(" sys_role_dept.dept_id not in(select sys_dept.parent_id from sys_role_dept LEFT JOIN sys_dept on sys_dept.dept_id=sys_role_dept.dept_id where role_id =? )", roleId).
// Find(&deptList).Error; err != nil {
// return nil, err
// }
//
// for i := 0; i < len(deptList); i++ {
// deptIds = append(deptIds, deptList[i].DeptId)
// }
//
// return deptIds, nil
//}
//
//func (e *SysDept) SetDeptLabel() (m []dto.DeptLabel, err error) {
// list := make([]models.SysDept, 0)
// err = e.Orm.Find(&list).Error
// if err != nil {
// log.Error("find dept list error, %s", e.err)
// return
// }
//
// m = make([]dto.DeptLabel, 0)
// var item dto.DeptLabel
// for i := range list {
// if list[i].ParentId != 0 {
// continue
// }
// item = dto.DeptLabel{}
// item.Id = list[i].DeptId
// item.Label = list[i].DeptName
// deptInfo := digitDeptLabel(&list, item)
//
// m = append(m, deptInfo)
// }
// return
//}
//
//// digitDeptLabel
//func digitDeptLabel(deptList *[]models.SysDept, dept dto.DeptLabel) dto.DeptLabel {
// list := *deptList
//
// var mi dto.DeptLabel
// min := make([]dto.DeptLabel, 0)
// for j := 0; j < len(list); j++ {
//
// if dept.Id != list[j].ParentId {
// continue
// }
// mi = dto.DeptLabel{Id: list[j].DeptId, Label: list[j].DeptName, Children: []dto.DeptLabel{}}
// ms := digitDeptLabel(deptList, mi)
// min = append(min, ms)
//
// }
// dept.Children = min
// return dept
//}
// GetRoleDeptId 获取角色的部门ID集合
func (e *SysDept) GetRoleDeptId(roleId int) ([]int, error) {
deptIds := make([]int, 0)
deptList := make([]dto.DeptIdList, 0)
if err := e.Orm.Table("sys_role_dept").
Select("sys_role_dept.dept_id").
Joins("LEFT JOIN sys_dept on sys_dept.dept_id=sys_role_dept.dept_id").
Where("role_id = ? ", roleId).
Where(" sys_role_dept.dept_id not in(select sys_dept.parent_id from sys_role_dept LEFT JOIN sys_dept on sys_dept.dept_id=sys_role_dept.dept_id where role_id =? )", roleId).
Find(&deptList).Error; err != nil {
return nil, err
}
for i := 0; i < len(deptList); i++ {
deptIds = append(deptIds, deptList[i].DeptId)
}
return deptIds, nil
}
func (e *SysDept) SetDeptLabel() (m []dto.DeptLabel, err error) {
list := make([]system.SysDept, 0)
err = e.Orm.Find(&list).Error
if err != nil {
log.Error("find dept list error, %s", err.Error())
return
}
m = make([]dto.DeptLabel, 0)
var item dto.DeptLabel
for i := range list {
if list[i].ParentId != 0 {
continue
}
item = dto.DeptLabel{}
item.Id = list[i].DeptId
item.Label = list[i].DeptName
deptInfo := digitDeptLabel(&list, item)
m = append(m, deptInfo)
}
return
}
// digitDeptLabel
func digitDeptLabel(deptList *[]system.SysDept, dept dto.DeptLabel) dto.DeptLabel {
list := *deptList
var mi dto.DeptLabel
min := make([]dto.DeptLabel, 0)
for j := 0; j < len(list); j++ {
if dept.Id != list[j].ParentId {
continue
}
mi = dto.DeptLabel{Id: list[j].DeptId, Label: list[j].DeptName, Children: []dto.DeptLabel{}}
ms := digitDeptLabel(deptList, mi)
min = append(min, ms)
}
dept.Children = min
return dept
}
+2 -2
View File
@@ -197,7 +197,7 @@ func (e *SysRole) UpdateDataScope(c *system.SysRole) (err error) {
tx.Commit()
}
}()
err = tx.Model(&system.SysRole{}).Where("role_id = ?", c.RoleId).Select("data_scope, update_by").Updates(c).Error
err = tx.Model(&system.SysRole{}).Where("role_id = ?", c.RoleId).Select("data_scope", "update_by").Updates(c).Error
if err != nil {
return err
}
@@ -221,4 +221,4 @@ func (e *SysRole) UpdateDataScope(c *system.SysRole) (err error) {
}
}
return err
}
}
+31 -12
View File
@@ -3,6 +3,8 @@ package service
import (
"errors"
log "github.com/go-admin-team/go-admin-core/logger"
"github.com/go-admin-team/go-admin-core/sdk/pkg"
"gorm.io/gorm"
"go-admin/app/admin/models/system"
@@ -115,29 +117,46 @@ func (e *SysUser) RemoveSysUser(d cDto.Control, c common.ActiveRecord, p *action
}
// UpdateSysUserPwd 修改SysUser对象密码
func (e *SysUser) UpdateSysUserPwd(c *system.SysUser, p *actions.DataPermission) error {
func (e *SysUser) UpdateSysUserPwd(id int, oldPassword, newPassword string, p *actions.DataPermission) error {
var err error
if c.Password == "" {
if newPassword == "" {
return nil
}
c := &system.SysUser{}
err = c.Encrypt()
if err != nil {
return err
}
db := e.Orm.Model(c).
err = e.Orm.Model(c).
Scopes(
actions.Permission(c.TableName(), p),
).Where(c.GetId()).Updates(c)
if db.Error != nil {
).Where(id).Select("UserId", "Password", "Salt").First(c).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return errors.New("无权更新该数据")
}
e.Log.Errorf("db error: %s", err)
return err
}
var ok bool
ok, err = pkg.CompareHashAndPassword(c.Password, oldPassword)
if err != nil {
e.Log.Errorf("CompareHashAndPassword error, %s", err.Error())
return err
}
if !ok {
err = errors.New("incorrect Password")
e.Log.Warnf("user[%d] %s", id, err.Error())
return err
}
c.Password = newPassword
db := e.Orm.Model(c).Where(id).Select("Password", "Salt").Updates(c)
if err = db.Error; err != nil {
e.Log.Errorf("db error: %s", err)
return err
}
if db.RowsAffected == 0 {
return errors.New("无权更新该数据")
err = errors.New("set password error")
log.Warnf("db update error")
return err
}
return nil
}
+13 -5
View File
@@ -3,8 +3,6 @@ package api
import (
"context"
"fmt"
"github.com/go-admin-team/go-admin-core/sdk"
"github.com/go-admin-team/go-admin-core/sdk/pkg"
"log"
"net/http"
"os"
@@ -13,10 +11,13 @@ import (
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/config/source/file"
"github.com/go-admin-team/go-admin-core/sdk"
"github.com/go-admin-team/go-admin-core/sdk/config"
"github.com/go-admin-team/go-admin-core/sdk/pkg"
"github.com/go-admin-team/go-admin-core/sdk/pkg/logger"
"github.com/spf13/cobra"
"github.com/go-admin-team/go-admin-core/sdk/config"
"github.com/go-admin-team/go-admin-core/sdk/pkg/logger"
"go-admin/app/admin/models/system"
"go-admin/app/admin/router"
"go-admin/app/jobs"
"go-admin/common/database"
@@ -63,10 +64,17 @@ func setup() {
//3. 初始化数据库链接
database.Setup()
//4. 设置缓存
sdk.Runtime.SetCacheAdapter(config.CacheConfig.Setup())
cacheAdapter, err := config.CacheConfig.Setup()
if err != nil {
log.Fatalf("cache setup error, %s\n", err.Error())
}
sdk.Runtime.SetCacheAdapter(cacheAdapter)
usageStr := `starting api server...`
log.Println(usageStr)
//注册监听函数
sdk.Runtime.GetCacheAdapter().Register(global.LoginLog, system.SaveLoginLog)
sdk.Runtime.GetCacheAdapter().Register(global.OperateLog, system.SaveOperaLog)
}
func run() error {
@@ -3,6 +3,7 @@ package version
import (
"gorm.io/gorm"
"runtime"
"strings"
"go-admin/cmd/migrate/migration"
common "go-admin/common/models"
@@ -17,7 +18,7 @@ func _1615948084336Test(db *gorm.DB, version string) error {
return db.Transaction(func(tx *gorm.DB) error {
err := tx.Exec("alter table sys_config add is_frontend int default 1 null comment '是否前台参数' after config_type").Error
if err != nil {
if err != nil && !strings.Contains(err.Error(),"Duplicate column name 'is_frontend'") {
return err
}
@@ -25,4 +26,4 @@ func _1615948084336Test(db *gorm.DB, version string) error {
Version: version,
}).Error
})
}
}
+2 -2
View File
@@ -2,11 +2,11 @@ package global
const (
// go-admin Version Info
Version = "1.3.1rc.1"
Version = "1.3.2"
)
var (
Source string
Driver string
DBName string
)
)
+6
View File
@@ -0,0 +1,6 @@
package global
const (
LoginLog = "login_log_queue"
OperateLog = "operate_log_queue"
)
@@ -5,7 +5,7 @@ import (
"github.com/go-admin-team/go-admin-core/sdk/config"
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
"go-admin/app/admin/middleware/handler"
"go-admin/common/middleware/handler"
)
// AuthInit jwt验证new
@@ -4,6 +4,7 @@ import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/sdk"
"github.com/go-admin-team/go-admin-core/sdk/api"
"github.com/go-admin-team/go-admin-core/sdk/config"
"github.com/go-admin-team/go-admin-core/sdk/pkg"
@@ -14,15 +15,15 @@ import (
"github.com/mssola/user_agent"
"go-admin/app/admin/models/system"
"go-admin/app/admin/service"
"go-admin/common/global"
)
var store = base64Captcha.DefaultMemStore
func PayloadFunc(data interface{}) jwt.MapClaims {
if v, ok := data.(map[string]interface{}); ok {
u, _ := v["user"].(system.SysUser)
r, _ := v["role"].(system.SysRole)
u, _ := v["user"].(SysUser)
r, _ := v["role"].(SysRole)
return jwt.MapClaims{
jwt.IdentityKey: u.UserId,
jwt.RoleIdKey: r.RoleId,
@@ -68,7 +69,7 @@ func Authenticator(c *gin.Context) (interface{}, error) {
return nil, jwt.ErrFailedAuthentication
}
var loginVals system.Login
var loginVals Login
var status = "2"
var msg = "登录成功"
var username = ""
@@ -107,29 +108,35 @@ func Authenticator(c *gin.Context) (interface{}, error) {
// LoginLogToDB Write log to database
func LoginLogToDB(c *gin.Context, status string, msg string, username string) {
if !config.LoggerConfig.EnabledDB {
return
}
log := api.GetRequestLogger(c)
if config.LoggerConfig.EnabledDB {
var loginLog system.SysLoginLog
db, err := pkg.GetOrm(c)
l := make(map[string]interface{})
ua := user_agent.New(c.Request.UserAgent())
l["ipaddr"] = c.ClientIP()
l["loginLocation"] = pkg.GetLocation(c.ClientIP())
l["loginTime"] = pkg.GetCurrentTime()
l["status"] = status
l["remark"] = c.Request.UserAgent()
browserName, browserVersion := ua.Browser()
l["browser"] = browserName + " " + browserVersion
l["os"] = ua.OS()
l["platform"] = ua.Platform()
l["username"] = username
l["msg"] = msg
q := sdk.Runtime.GetCachePrefix(c.Request.Host)
message, err := sdk.Runtime.GetStreamMessage("", global.LoginLog, l)
if err != nil {
log.Errorf("GetStreamMessage error, %s", err.Error())
//日志报错错误,不中断请求
} else {
err = q.Append(message)
if err != nil {
log.Errorf("获取Orm失败, error:%s", err)
log.Errorf("Append message error, %s", err.Error())
}
ua := user_agent.New(c.Request.UserAgent())
loginLog.Ipaddr = c.ClientIP()
loginLog.Username = username
location := pkg.GetLocation(c.ClientIP())
loginLog.LoginLocation = location
loginLog.LoginTime = pkg.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()
serviceLoginLog := service.SysLoginLog{}
serviceLoginLog.Orm = db
_ = serviceLoginLog.InsertSysLoginLog(loginLog.Generate())
}
}
@@ -143,28 +150,27 @@ func LoginLogToDB(c *gin.Context, status string, msg string, username string) {
// @Router /logout [post]
// @Security Bearer
func LogOut(c *gin.Context) {
log := api.GetRequestLogger(c)
var loginLog system.SysLoginLog
ua := user_agent.New(c.Request.UserAgent())
loginLog.Ipaddr = c.ClientIP()
location := pkg.GetLocation(c.ClientIP())
loginLog.LoginLocation = location
loginLog.LoginTime = pkg.GetCurrentTime()
loginLog.Status = "2"
loginLog.Remark = c.Request.UserAgent()
browserName, browserVersion := ua.Browser()
loginLog.Browser = browserName + " " + browserVersion
loginLog.Os = ua.OS()
loginLog.Platform = ua.Platform()
loginLog.Username = user.GetUserName(c)
loginLog.Msg = "退出成功"
db, err := pkg.GetOrm(c)
if err != nil {
log.Errorf("获取Orm失败, error:%s", err)
}
serviceLoginLog := service.SysLoginLog{}
serviceLoginLog.Orm = db
_ = serviceLoginLog.InsertSysLoginLog(loginLog.Generate())
LoginLogToDB(c, "2", "退出成功", user.GetUserName(c))
//var loginLog system.SysLoginLog
//loginLog.Ipaddr = c.ClientIP()
//location := pkg.GetLocation(c.ClientIP())
//loginLog.LoginLocation = location
//loginLog.LoginTime = pkg.GetCurrentTime()
//loginLog.Status = "2"
//loginLog.Remark = c.Request.UserAgent()
//browserName, browserVersion := ua.Browser()
//loginLog.Browser = browserName + " " + browserVersion
//loginLog.Os = ua.OS()
//loginLog.Platform = ua.Platform()
//loginLog.Username = user.GetUserName(c)
//loginLog.Msg = "退出成功"
//db, err := pkg.GetOrm(c)
//if err != nil {
// log.Errorf("获取Orm失败, error:%s", err)
//}
//serviceLoginLog := service.SysLoginLog{}
//serviceLoginLog.Orm = db
//_ = serviceLoginLog.InsertSysLoginLog(loginLog.Generate())
c.JSON(http.StatusOK, gin.H{
"code": 200,
@@ -1,7 +1,6 @@
package system
package handler
import (
"fmt"
log "github.com/go-admin-team/go-admin-core/logger"
"github.com/go-admin-team/go-admin-core/sdk/pkg"
"gorm.io/gorm"
@@ -20,7 +19,6 @@ func (u *Login) GetUser(tx *gorm.DB) (user SysUser, role SysRole, err error) {
log.Errorf("get user error, %s", err.Error())
return
}
fmt.Println(user.Password, u.Password)
_, err = pkg.CompareHashAndPassword(user.Password, u.Password)
if err != nil {
log.Errorf("user login error, %s", err.Error())
+24
View File
@@ -0,0 +1,24 @@
package handler
import "go-admin/common/models"
type SysRole struct {
RoleId int `json:"roleId" gorm:"primaryKey;autoIncrement"` // 角色编码
RoleName string `json:"roleName" gorm:"size:128;"` // 角色名称
Status string `json:"status" gorm:"size:4;"` //
RoleKey string `json:"roleKey" gorm:"size:128;"` //角色代码
RoleSort int `json:"roleSort" gorm:""` //角色排序
Flag string `json:"flag" gorm:"size:128;"` //
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:"-"`
models.ControlBy
models.ModelTime
}
func (SysRole) TableName() string {
return "sys_role"
}
+40
View File
@@ -0,0 +1,40 @@
package handler
import (
"go-admin/common/models"
"gorm.io/gorm"
)
type SysUser struct {
models.ControlBy
models.ModelTime
UserId int `gorm:"primaryKey;autoIncrement;comment:编码" json:"userId"`
Username string `json:"username" gorm:"type:varchar(64);comment:用户名"`
Password string `json:"-" gorm:"type:varchar(128);comment:密码"`
NickName string `json:"nickName" gorm:"type:varchar(128);comment:昵称"`
Phone string `json:"phone" gorm:"type:varchar(11);comment:手机号"`
RoleId int `json:"roleId" gorm:"type:bigint(20);comment:角色ID"`
Salt string `json:"-" gorm:"type:varchar(255);comment:加盐"`
Avatar string `json:"avatar" gorm:"type:varchar(255);comment:头像"`
Sex string `json:"sex" gorm:"type:varchar(255);comment:性别"`
Email string `json:"email" gorm:"type:varchar(128);comment:邮箱"`
DeptId int `json:"deptId" gorm:"type:bigint(20);comment:部门"`
PostId int `json:"postId" gorm:"type:bigint(20);comment:岗位"`
Remark string `json:"remark" gorm:"type:varchar(255);comment:备注"`
Status string `json:"status" gorm:"type:varchar(4);comment:状态"`
DeptIds []int `json:"deptIds" gorm:"-"`
PostIds []int `json:"postIds" gorm:"-"`
RoleIds []int `json:"roleIds" gorm:"-"`
//Dept *SysDept `json:"dept"`
}
func (SysUser) TableName() string {
return "sys_user"
}
func (e *SysUser) AfterFind(_ *gorm.DB) error {
e.DeptIds = []int{e.DeptId}
e.PostIds = []int{e.PostId}
e.RoleIds = []int{e.RoleId}
return nil
}
@@ -2,13 +2,11 @@ package middleware
import (
"github.com/gin-gonic/gin"
"go-admin/common/middleware"
)
func InitMiddleware(r *gin.Engine) {
// 数据库链接
r.Use(middleware.WithContextDb)
r.Use(WithContextDb)
// 日志处理
r.Use(LoggerToFile())
// 自定义错误处理
@@ -2,21 +2,18 @@ package middleware
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/sdk"
"github.com/go-admin-team/go-admin-core/sdk/api"
"github.com/go-admin-team/go-admin-core/sdk/config"
"github.com/go-admin-team/go-admin-core/sdk/pkg"
"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
"github.com/go-admin-team/go-admin-core/sdk/pkg/response"
"go-admin/app/admin/models"
"go-admin/app/admin/models/system"
"go-admin/app/admin/service"
"go-admin/common/global"
)
// LoggerToFile 日志记录到文件
@@ -87,60 +84,49 @@ func LoggerToFile() gin.HandlerFunc {
// SetDBOperLog 写入操作日志表 fixme 该方法后续即将弃用
func SetDBOperLog(c *gin.Context, clientIP string, statusCode int, reqUri string, reqMethod string, latencyTime time.Duration, body string, result string, status int) {
log := api.GetRequestLogger(c)
db, err := pkg.GetOrm(c)
if err != nil {
log.Errorf("get db connection error, %s", err.Error())
response.Error(c, http.StatusInternalServerError, err, "数据库连接获取失败")
return
}
menu := models.Menu{}
menu.Path = reqUri
menu.Action = reqMethod
menuList, _ := menu.Get(db)
sysOperaLog := system.SysOperaLog{}
sysOperaLog.OperIp = clientIP
sysOperaLog.OperLocation = pkg.GetLocation(clientIP)
sysOperaLog.Status = pkg.IntToString(statusCode)
sysOperaLog.OperName = user.GetUserName(c)
sysOperaLog.RequestMethod = c.Request.Method
sysOperaLog.OperUrl = reqUri
sysOperaLog.OperParam = body
l := make(map[string]interface{})
l["_fullPath"] = c.FullPath()
l["operUrl"] = reqUri
l["method"] = reqMethod
l["operIp"] = clientIP
l["operLocation"] = pkg.GetLocation(clientIP)
l["operName"] = user.GetUserName(c)
l["requestMethod"] = c.Request.Method
l["operParam"] = body
l["operTime"] = time.Now()
if reqUri == "/login" {
sysOperaLog.BusinessType = "10"
sysOperaLog.Title = "用户登录"
sysOperaLog.OperName = "-"
l["businessType"] = "10"
l["title"] = "用户登录"
l["operName"] = "-"
} else if strings.Contains(reqUri, "/api/v1/logout") {
sysOperaLog.BusinessType = "11"
l["businessType"] = "11"
l["title"] = "退出登录"
} else if strings.Contains(reqUri, "/api/v1/getCaptcha") {
sysOperaLog.BusinessType = "12"
sysOperaLog.Title = "验证码"
l["businessType"] = "12"
l["title"] = "验证码"
} else {
if reqMethod == "POST" {
sysOperaLog.BusinessType = "1"
l["businessType"] = "1"
} else if reqMethod == "PUT" {
sysOperaLog.BusinessType = "2"
l["businessType"] = "2"
} else if reqMethod == "DELETE" {
sysOperaLog.BusinessType = "3"
l["businessType"] = "3"
}
}
sysOperaLog.Method = reqMethod
if len(menuList) > 0 {
sysOperaLog.Title = menuList[0].Title
}
sysOperaLog.CreateBy = user.GetUserId(c)
sysOperaLog.OperTime = pkg.GetCurrentTime()
sysOperaLog.LatencyTime = fmt.Sprintf("%v", latencyTime)
sysOperaLog.JsonResult = result
sysOperaLog.UserAgent = c.Request.UserAgent()
if status == 200 {
sysOperaLog.Status = "2"
if status == http.StatusOK {
l["status"] = "2"
} else {
sysOperaLog.Status = "1"
l["status"] = "1"
}
q := sdk.Runtime.GetCachePrefix(c.Request.Host)
message, err := sdk.Runtime.GetStreamMessage("", global.OperateLog, l)
if err != nil {
log.Errorf("GetStreamMessage error, %s", err.Error())
//日志报错错误,不中断请求
} else {
err = q.Append(message)
if err != nil {
log.Errorf("Append message error, %s", err.Error())
}
}
serviceOperaLog := service.SysOperaLog{}
serviceOperaLog.Orm = db
serviceOperaLog.Log = log
_ = serviceOperaLog.InsertSysOperaLog(&sysOperaLog)
}
+8 -1
View File
@@ -1866,8 +1866,15 @@ var doc = `{
"definitions": {
"dto.PassWord": {
"type": "object",
"required": [
"newPassword",
"oldPassword"
],
"properties": {
"password": {
"newPassword": {
"type": "string"
},
"oldPassword": {
"type": "string"
}
}
+8 -1
View File
@@ -1849,8 +1849,15 @@
"definitions": {
"dto.PassWord": {
"type": "object",
"required": [
"newPassword",
"oldPassword"
],
"properties": {
"password": {
"newPassword": {
"type": "string"
},
"oldPassword": {
"type": "string"
}
}
+6 -1
View File
@@ -1,8 +1,13 @@
definitions:
dto.PassWord:
properties:
password:
newPassword:
type: string
oldPassword:
type: string
required:
- newPassword
- oldPassword
type: object
dto.SysDeptById:
properties:
+1 -1
View File
@@ -8,7 +8,7 @@ require (
github.com/aliyun/aliyun-oss-go-sdk v0.0.0-20190307165228-86c17b95fcd5
github.com/casbin/casbin/v2 v2.25.1
github.com/gin-gonic/gin v1.6.3
github.com/go-admin-team/go-admin-core v1.3.1-0.20210324084642-7c164d76fc11
github.com/go-admin-team/go-admin-core v1.3.2-rc.0
github.com/google/uuid v1.2.0
github.com/mojocn/base64Captcha v1.3.1
github.com/mssola/user_agent v0.5.2
+1 -1
View File
@@ -18,4 +18,4 @@ import (
// @name Authorization
func main() {
cmd.Execute()
}
}
+5 -5
View File
@@ -33,7 +33,7 @@ func (m *{{.ClassName}}Search) Bind(ctx *gin.Context) error {
log := api.GetRequestLogger(ctx)
err := ctx.ShouldBind(m)
if err != nil {
log.Debugf("ShouldBind error: %s", err.Error())
log.Warnf("ShouldBind error: %s", err.Error())
}
return err
}
@@ -63,12 +63,12 @@ func (s *{{.ClassName}}Control) Bind(ctx *gin.Context) error {
log := api.GetRequestLogger(ctx)
err := ctx.ShouldBindUri(s)
if err != nil {
log.Debugf("ShouldBindUri error: %s", err.Error())
log.Warnf("ShouldBindUri error: %s", err.Error())
return err
}
err = ctx.ShouldBind(s)
if err != nil {
log.Debugf("ShouldBind error: %s", err.Error())
log.Warnf("ShouldBind error: %s", err.Error())
}
return err
}
@@ -111,12 +111,12 @@ func (s *{{.ClassName}}ById) Bind(ctx *gin.Context) error {
log := api.GetRequestLogger(ctx)
err := ctx.ShouldBindUri(s)
if err != nil {
log.Debugf("ShouldBindUri error: %s", err.Error())
log.Warnf("ShouldBindUri error: %s", err.Error())
return err
}
err = ctx.ShouldBind(s)
if err != nil {
log.Debugf("ShouldBind error: %s", err.Error())
log.Warnf("ShouldBind error: %s", err.Error())
}
return err
}
+1 -1
View File
@@ -147,7 +147,7 @@ func (e *{{.ClassName}}) Insert{{.ClassName}}(c *gin.Context) {
service{{.ClassName}} := service.{{.ClassName}}{}
service{{.ClassName}}.Orm = db
service{{.ClassName}}.Log = log
err = service{{.ClassName}}.Insert{{.ClassName}}(object.(*(models.{{.ClassName}})))
err = service{{.ClassName}}.Insert{{.ClassName}}(object.(*models.{{.ClassName}}))
if err != nil {
log.Errorf("Insert {{.ClassName}} error, %s", err.Error())
e.Error(c, http.StatusInternalServerError, err, "创建失败")