修复漏洞,重构初始化功能,优化媒体库 (#1024)

* 媒体库增加 普通上传、压缩上传按钮,方便媒体库直接上传图片

* 增加数据类型切换后的的校验,避免使用错误的查询条件和字典条件。

* refactor: 重构初始化逻辑

* 媒体库功能丰富

* 修复注入漏洞和路径穿越

* 修复自动化接口获取数据库表失败后未能终止的bug

* 微调媒体库样式

Co-authored-by: bypanghu <bypanghu@163.com>
Co-authored-by: tesun <36953434+tesun@users.noreply.github.com>
Co-authored-by: pnck <hio131@gmail.com>
Co-authored-by: task <121913992@qq.com>
This commit is contained in:
奇淼(piexlmax
2022-04-12 17:57:11 +08:00
committed by GitHub
co-authored by bypanghu tesun pnck task
parent fe539baa34
commit 6fb6ac2d6c
40 changed files with 1366 additions and 792 deletions
+45 -17
View File
@@ -1,22 +1,48 @@
package system
import (
"github.com/flipped-aurora/gin-vue-admin/server/global"
"github.com/flipped-aurora/gin-vue-admin/server/model/system"
"context"
sysModel "github.com/flipped-aurora/gin-vue-admin/server/model/system"
"github.com/flipped-aurora/gin-vue-admin/server/service/system"
"github.com/pkg/errors"
"gorm.io/gorm"
)
var Api = new(api)
type initApi struct{}
type api struct{}
const initOrderApi = system.InitOrderSystem + 1
func (a *api) TableName() string {
return "sys_apis"
// auto run
func init() {
system.RegisterInit(initOrderApi, &initApi{})
}
func (a *api) Initialize() error {
entities := []system.SysApi{
func (i initApi) InitializerName() string {
return sysModel.SysApi{}.TableName()
}
func (i *initApi) MigrateTable(ctx context.Context) (context.Context, error) {
db, ok := ctx.Value("db").(*gorm.DB)
if !ok {
return ctx, system.ErrMissingDBContext
}
return ctx, db.AutoMigrate(&sysModel.SysApi{})
}
func (i *initApi) TableCreated(ctx context.Context) bool {
db, ok := ctx.Value("db").(*gorm.DB)
if !ok {
return false
}
return db.Migrator().HasTable(&sysModel.SysApi{})
}
func (i *initApi) InitializeData(ctx context.Context) (context.Context, error) {
db, ok := ctx.Value("db").(*gorm.DB)
if !ok {
return ctx, system.ErrMissingDBContext
}
entities := []sysModel.SysApi{
{ApiGroup: "base", Method: "POST", Path: "/base/login", Description: "用户登录(必选)"},
{ApiGroup: "jwt", Method: "POST", Path: "/jwt/jsonInBlacklist", Description: "jwt加入黑名单(退出,必选)"},
@@ -94,10 +120,6 @@ func (a *api) Initialize() error {
{ApiGroup: "代码生成器历史", Method: "POST", Path: "/autoCode/getSysHistory", Description: "查询回滚记录"},
{ApiGroup: "代码生成器历史", Method: "POST", Path: "/autoCode/delSysHistory", Description: "删除回滚记录"},
{ApiGroup: "系统字典详情", Method: "PUT", Path: "/sysDictionaryDetail/updateSysDictionaryDetail", Description: "更新字典内容"},
{ApiGroup: "系统字典详情", Method: "POST", Path: "/sysDictionaryDetail/createSysDictionaryDetail", Description: "新增字典内容"},
{ApiGroup: "系统字典详情", Method: "DELETE", Path: "/sysDictionaryDetail/deleteSysDictionaryDetail", Description: "删除字典内容"},
@@ -132,14 +154,20 @@ func (a *api) Initialize() error {
{ApiGroup: "按钮权限", Method: "POST", Path: "/authorityBtn/getAuthorityBtn", Description: "获取已有按钮权限"},
{ApiGroup: "按钮权限", Method: "POST", Path: "/authorityBtn/canRemoveAuthorityBtn", Description: "删除按钮"},
}
if err := global.GVA_DB.Create(&entities).Error; err != nil {
return errors.Wrap(err, a.TableName()+"表数据初始化失败!")
if err := db.Create(&entities).Error; err != nil {
return ctx, errors.Wrap(err, sysModel.SysApi{}.TableName()+"表数据初始化失败!")
}
return nil
next := context.WithValue(ctx, i.InitializerName(), entities)
return next, nil
}
func (a *api) CheckDataExist() bool {
if errors.Is(global.GVA_DB.Where("path = ? AND method = ?", "/excel/downloadTemplate", "GET").First(&system.SysApi{}).Error, gorm.ErrRecordNotFound) {
func (i *initApi) DataInserted(ctx context.Context) bool {
db, ok := ctx.Value("db").(*gorm.DB)
if !ok {
return false
}
if errors.Is(db.Where("path = ? AND method = ?", "/authorityBtn/canRemoveAuthorityBtn", "POST").
First(&sysModel.SysApi{}).Error, gorm.ErrRecordNotFound) {
return false
}
return true
+65 -80
View File
@@ -1,97 +1,82 @@
package system
import (
"reflect"
"github.com/flipped-aurora/gin-vue-admin/server/global"
"github.com/flipped-aurora/gin-vue-admin/server/model/system"
"context"
sysModel "github.com/flipped-aurora/gin-vue-admin/server/model/system"
"github.com/flipped-aurora/gin-vue-admin/server/service/system"
"github.com/pkg/errors"
"gorm.io/gorm"
"gorm.io/gorm/schema"
)
var AuthoritiesMenus = new(authoritiesMenus)
const initOrderMenuAuthority = initOrderMenu + initOrderAuthority
type authoritiesMenus struct{}
type initMenuAuthority struct{}
func (a *authoritiesMenus) TableName() string {
var entity AuthorityMenus
return entity.TableName()
// auto run
func init() {
system.RegisterInit(initOrderMenuAuthority, &initMenuAuthority{})
}
func (a *authoritiesMenus) Initialize() error {
entities := []AuthorityMenus{
{BaseMenuId: 1, AuthorityId: "888"},
{BaseMenuId: 2, AuthorityId: "888"},
{BaseMenuId: 3, AuthorityId: "888"},
{BaseMenuId: 4, AuthorityId: "888"},
{BaseMenuId: 5, AuthorityId: "888"},
{BaseMenuId: 6, AuthorityId: "888"},
{BaseMenuId: 7, AuthorityId: "888"},
{BaseMenuId: 8, AuthorityId: "888"},
{BaseMenuId: 9, AuthorityId: "888"},
{BaseMenuId: 10, AuthorityId: "888"},
{BaseMenuId: 11, AuthorityId: "888"},
{BaseMenuId: 12, AuthorityId: "888"},
{BaseMenuId: 13, AuthorityId: "888"},
{BaseMenuId: 14, AuthorityId: "888"},
{BaseMenuId: 15, AuthorityId: "888"},
{BaseMenuId: 16, AuthorityId: "888"},
{BaseMenuId: 17, AuthorityId: "888"},
{BaseMenuId: 18, AuthorityId: "888"},
{BaseMenuId: 19, AuthorityId: "888"},
{BaseMenuId: 20, AuthorityId: "888"},
{BaseMenuId: 22, AuthorityId: "888"},
{BaseMenuId: 23, AuthorityId: "888"},
{BaseMenuId: 24, AuthorityId: "888"},
{BaseMenuId: 25, AuthorityId: "888"},
{BaseMenuId: 26, AuthorityId: "888"},
{BaseMenuId: 1, AuthorityId: "8881"},
{BaseMenuId: 2, AuthorityId: "8881"},
{BaseMenuId: 8, AuthorityId: "8881"},
{BaseMenuId: 1, AuthorityId: "9528"},
{BaseMenuId: 2, AuthorityId: "9528"},
{BaseMenuId: 3, AuthorityId: "9528"},
{BaseMenuId: 4, AuthorityId: "9528"},
{BaseMenuId: 5, AuthorityId: "9528"},
{BaseMenuId: 6, AuthorityId: "9528"},
{BaseMenuId: 7, AuthorityId: "9528"},
{BaseMenuId: 8, AuthorityId: "9528"},
{BaseMenuId: 9, AuthorityId: "9528"},
{BaseMenuId: 10, AuthorityId: "9528"},
{BaseMenuId: 11, AuthorityId: "9528"},
{BaseMenuId: 12, AuthorityId: "9528"},
{BaseMenuId: 14, AuthorityId: "9528"},
{BaseMenuId: 15, AuthorityId: "9528"},
{BaseMenuId: 16, AuthorityId: "9528"},
{BaseMenuId: 17, AuthorityId: "9528"},
}
if err := global.GVA_DB.Create(&entities).Error; err != nil {
return errors.Wrap(err, a.TableName()+"表数据初始化失败!")
}
return nil
func (i *initMenuAuthority) MigrateTable(ctx context.Context) (context.Context, error) {
return ctx, nil // do nothing
}
func (a *authoritiesMenus) CheckDataExist() bool {
if errors.Is(global.GVA_DB.Where("sys_base_menu_id = ? AND sys_authority_authority_id = ?", 17, "9528").First(&AuthorityMenus{}).Error, gorm.ErrRecordNotFound) { // 判断是否存在数据
func (i *initMenuAuthority) TableCreated(ctx context.Context) bool {
return false // always replace
}
func (i initMenuAuthority) InitializerName() string {
return "sys_menu_authorities"
}
func (i *initMenuAuthority) InitializeData(ctx context.Context) (next context.Context, err error) {
db, ok := ctx.Value("db").(*gorm.DB)
if !ok {
return ctx, system.ErrMissingDBContext
}
authorities, ok := ctx.Value(initAuthority{}.InitializerName()).([]sysModel.SysAuthority)
if !ok {
return ctx, errors.Wrap(system.ErrMissingDependentContext, "创建 [菜单-权限] 关联失败, 未找到权限表初始化数据")
}
menus, ok := ctx.Value(initMenu{}.InitializerName()).([]sysModel.SysBaseMenu)
if !ok {
return next, errors.Wrap(errors.New(""), "创建 [菜单-权限] 关联失败, 未找到菜单表初始化数据")
}
next = ctx
// 888
if err = db.Model(&authorities[0]).Association("SysBaseMenus").Replace(menus[:20]); err != nil {
return next, err
}
if err = db.Model(&authorities[0]).Association("SysBaseMenus").Append(menus[21:]); err != nil {
return next, err
}
// 8881
menu8881 := menus[:2]
menu8881 = append(menu8881, menus[7])
if err = db.Model(&authorities[1]).Association("SysBaseMenus").Replace(menu8881); err != nil {
return next, err
}
// 9528
if err = db.Model(&authorities[2]).Association("SysBaseMenus").Replace(menus[:12]); err != nil {
return next, err
}
if err = db.Model(&authorities[2]).Association("SysBaseMenus").Append(menus[13:17]); err != nil {
return next, err
}
return next, nil
}
func (i *initMenuAuthority) DataInserted(ctx context.Context) bool {
db, ok := ctx.Value("db").(*gorm.DB)
if !ok {
return false
}
return true
}
type AuthorityMenus struct {
AuthorityId string `gorm:"column:sys_authority_authority_id"`
BaseMenuId uint `gorm:"column:sys_base_menu_id"`
}
func (a *AuthorityMenus) TableName() string {
var entity system.SysAuthority
types := reflect.TypeOf(entity)
if s, o := types.FieldByName("SysBaseMenus"); o {
m1 := schema.ParseTagSetting(s.Tag.Get("gorm"), ";")
return m1["MANY2MANY"]
var count int64
if err := db.Model(&sysModel.SysAuthority{}).
Where("authority_id = ?", "9528").Preload("SysBaseMenus").Count(&count); err != nil {
return count == 16
}
return ""
return false
}
+65 -13
View File
@@ -1,34 +1,86 @@
package system
import (
"github.com/flipped-aurora/gin-vue-admin/server/global"
"github.com/flipped-aurora/gin-vue-admin/server/model/system"
"context"
sysModel "github.com/flipped-aurora/gin-vue-admin/server/model/system"
"github.com/flipped-aurora/gin-vue-admin/server/service/system"
"github.com/pkg/errors"
"gorm.io/gorm"
)
var Authority = new(authority)
const initOrderAuthority = initOrderCasbin + 1
type authority struct{}
type initAuthority struct{}
func (a *authority) TableName() string {
return "sys_authorities"
// auto run
func init() {
system.RegisterInit(initOrderAuthority, &initAuthority{})
}
func (a *authority) Initialize() error {
entities := []system.SysAuthority{
func (i *initAuthority) MigrateTable(ctx context.Context) (context.Context, error) {
db, ok := ctx.Value("db").(*gorm.DB)
if !ok {
return ctx, system.ErrMissingDBContext
}
return ctx, db.AutoMigrate(&sysModel.SysAuthority{})
}
func (i *initAuthority) TableCreated(ctx context.Context) bool {
db, ok := ctx.Value("db").(*gorm.DB)
if !ok {
return false
}
return db.Migrator().HasTable(&sysModel.SysAuthority{})
}
func (i initAuthority) InitializerName() string {
return sysModel.SysAuthority{}.TableName()
}
func (i *initAuthority) InitializeData(ctx context.Context) (context.Context, error) {
db, ok := ctx.Value("db").(*gorm.DB)
if !ok {
return ctx, system.ErrMissingDBContext
}
entities := []sysModel.SysAuthority{
{AuthorityId: "888", AuthorityName: "普通用户", ParentId: "0", DefaultRouter: "dashboard"},
{AuthorityId: "9528", AuthorityName: "测试角色", ParentId: "0", DefaultRouter: "dashboard"},
{AuthorityId: "8881", AuthorityName: "普通用户子角色", ParentId: "888", DefaultRouter: "dashboard"},
}
if err := global.GVA_DB.Create(&entities).Error; err != nil {
return errors.Wrapf(err, "%s表数据初始化失败!", a.TableName())
if err := db.Create(&entities).Error; err != nil {
return ctx, errors.Wrapf(err, "%s表数据初始化失败!", sysModel.SysAuthority{}.TableName())
}
return nil
// data authority
if err := db.Model(&entities[0]).Association("DataAuthorityId").Replace(
[]*sysModel.SysAuthority{
{AuthorityId: "888"},
{AuthorityId: "9528"},
{AuthorityId: "8881"},
}); err != nil {
return ctx, errors.Wrapf(err, "%s表数据初始化失败!",
db.Model(&entities[0]).Association("DataAuthorityId").Relationship.JoinTable.Name)
}
if err := db.Model(&entities[1]).Association("DataAuthorityId").Replace(
[]*sysModel.SysAuthority{
{AuthorityId: "9528"},
{AuthorityId: "8881"},
}); err != nil {
return ctx, errors.Wrapf(err, "%s表数据初始化失败!",
db.Model(&entities[1]).Association("DataAuthorityId").Relationship.JoinTable.Name)
}
next := context.WithValue(ctx, i.InitializerName(), entities)
return next, nil
}
func (a *authority) CheckDataExist() bool {
if errors.Is(global.GVA_DB.Where("authority_id = ?", "8881").First(&system.SysAuthority{}).Error, gorm.ErrRecordNotFound) { // 判断是否存在数据
func (i *initAuthority) DataInserted(ctx context.Context) bool {
db, ok := ctx.Value("db").(*gorm.DB)
if !ok {
return false
}
if errors.Is(db.Where("authority_id = ?", "8881").
First(&sysModel.SysAuthority{}).Error, gorm.ErrRecordNotFound) { // 判断是否存在数据
return false
}
return true
+42 -10
View File
@@ -1,22 +1,48 @@
package system
import (
"context"
adapter "github.com/casbin/gorm-adapter/v3"
"github.com/flipped-aurora/gin-vue-admin/server/global"
"github.com/flipped-aurora/gin-vue-admin/server/service/system"
"github.com/pkg/errors"
"gorm.io/gorm"
)
var Casbin = new(casbin)
const initOrderCasbin = initOrderApi + 1
type casbin struct{}
type initCasbin struct{}
func (c *casbin) TableName() string {
// auto run
func init() {
system.RegisterInit(initOrderCasbin, &initCasbin{})
}
func (i *initCasbin) MigrateTable(ctx context.Context) (context.Context, error) {
db, ok := ctx.Value("db").(*gorm.DB)
if !ok {
return ctx, system.ErrMissingDBContext
}
return ctx, db.AutoMigrate(&adapter.CasbinRule{})
}
func (i *initCasbin) TableCreated(ctx context.Context) bool {
db, ok := ctx.Value("db").(*gorm.DB)
if !ok {
return false
}
return db.Migrator().HasTable(&adapter.CasbinRule{})
}
func (i initCasbin) InitializerName() string {
var entity adapter.CasbinRule
return entity.TableName()
}
func (c *casbin) Initialize() error {
func (i *initCasbin) InitializeData(ctx context.Context) (context.Context, error) {
db, ok := ctx.Value("db").(*gorm.DB)
if !ok {
return ctx, system.ErrMissingDBContext
}
entities := []adapter.CasbinRule{
{PType: "p", V0: "888", V1: "/base/login", V2: "POST"},
{PType: "p", V0: "888", V1: "/user/admin_register", V2: "POST"},
@@ -208,14 +234,20 @@ func (c *casbin) Initialize() error {
{PType: "p", V0: "9528", V1: "/autoCode/createTemp", V2: "POST"},
{PType: "p", V0: "9528", V1: "/user/getUserInfo", V2: "GET"},
}
if err := global.GVA_DB.Create(&entities).Error; err != nil {
return errors.Wrap(err, c.TableName()+"表数据初始化失败!")
if err := db.Create(&entities).Error; err != nil {
return ctx, errors.Wrap(err, "Casbin 表 ("+i.InitializerName()+") 数据初始化失败!")
}
return nil
next := context.WithValue(ctx, i.InitializerName(), entities)
return next, nil
}
func (c *casbin) CheckDataExist() bool {
if errors.Is(global.GVA_DB.Where(adapter.CasbinRule{PType: "p", V0: "9528", V1: "GET", V2: "/user/getUserInfo"}).First(&adapter.CasbinRule{}).Error, gorm.ErrRecordNotFound) { // 判断是否存在数据
func (i *initCasbin) DataInserted(ctx context.Context) bool {
db, ok := ctx.Value("db").(*gorm.DB)
if !ok {
return false
}
if errors.Is(db.Where(adapter.CasbinRule{PType: "p", V0: "9528", V1: "GET", V2: "/user/getUserInfo"}).
First(&adapter.CasbinRule{}).Error, gorm.ErrRecordNotFound) { // 判断是否存在数据
return false
}
return true
-57
View File
@@ -1,57 +0,0 @@
package system
import (
"reflect"
"github.com/flipped-aurora/gin-vue-admin/server/global"
"github.com/flipped-aurora/gin-vue-admin/server/model/system"
"github.com/pkg/errors"
"gorm.io/gorm"
"gorm.io/gorm/schema"
)
var DataAuthorities = new(dataAuthorities)
type dataAuthorities struct{}
func (a *dataAuthorities) TableName() string {
var entity AuthoritiesResources
return entity.TableName()
}
func (a *dataAuthorities) Initialize() error {
entities := []AuthoritiesResources{
{AuthorityId: "888", ResourcesId: "888"},
{AuthorityId: "888", ResourcesId: "8881"},
{AuthorityId: "888", ResourcesId: "9528"},
{AuthorityId: "9528", ResourcesId: "8881"},
{AuthorityId: "9528", ResourcesId: "9528"},
}
if err := global.GVA_DB.Create(&entities).Error; err != nil {
return errors.Wrap(err, a.TableName()+"表数据初始化失败!")
}
return nil
}
func (a *dataAuthorities) CheckDataExist() bool {
if errors.Is(global.GVA_DB.Where("sys_authority_authority_id = ? AND data_authority_id_authority_id = ?", "9528", "9528").First(&AuthoritiesResources{}).Error, gorm.ErrRecordNotFound) { // 判断是否存在数据
return false
}
return true
}
// AuthoritiesResources 角色资源表
type AuthoritiesResources struct {
AuthorityId string `gorm:"column:sys_authority_authority_id"`
ResourcesId string `gorm:"column:data_authority_id_authority_id"`
}
func (a *AuthoritiesResources) TableName() string {
var entity system.SysAuthority
types := reflect.TypeOf(entity)
if s, o := types.FieldByName("DataAuthorityId"); o {
m1 := schema.ParseTagSetting(s.Tag.Get("gorm"), ";")
return m1["MANY2MANY"]
}
return ""
}
+53 -22
View File
@@ -1,39 +1,70 @@
package system
import (
"github.com/flipped-aurora/gin-vue-admin/server/global"
"github.com/flipped-aurora/gin-vue-admin/server/model/system"
"context"
sysModel "github.com/flipped-aurora/gin-vue-admin/server/model/system"
"github.com/flipped-aurora/gin-vue-admin/server/service/system"
"github.com/pkg/errors"
"gorm.io/gorm"
)
var Dictionary = new(dictionary)
const initOrderDict = initOrderCasbin + 1
type dictionary struct{}
type initDict struct{}
func (d *dictionary) TableName() string {
return "sys_dictionaries"
// auto run
func init() {
system.RegisterInit(initOrderDict, &initDict{})
}
func (d *dictionary) Initialize() error {
status := new(bool)
*status = true
entities := []system.SysDictionary{
{GVA_MODEL: global.GVA_MODEL{ID: 1}, Name: "性别", Type: "gender", Status: status, Desc: "性别字典"},
{GVA_MODEL: global.GVA_MODEL{ID: 2}, Name: "数据库int类型", Type: "int", Status: status, Desc: "int类型对应的数据库类型"},
{GVA_MODEL: global.GVA_MODEL{ID: 3}, Name: "数据库时间日期类型", Type: "time.Time", Status: status, Desc: "数据库时间日期类型"},
{GVA_MODEL: global.GVA_MODEL{ID: 4}, Name: "数据库浮点型", Type: "float64", Status: status, Desc: "数据库浮点型"},
{GVA_MODEL: global.GVA_MODEL{ID: 5}, Name: "数据库字符串", Type: "string", Status: status, Desc: "数据库字符串"},
{GVA_MODEL: global.GVA_MODEL{ID: 6}, Name: "数据库bool类型", Type: "bool", Status: status, Desc: "数据库bool类型"},
func (i *initDict) MigrateTable(ctx context.Context) (context.Context, error) {
db, ok := ctx.Value("db").(*gorm.DB)
if !ok {
return ctx, system.ErrMissingDBContext
}
if err := global.GVA_DB.Create(&entities).Error; err != nil {
return errors.Wrap(err, d.TableName()+"表数据初始化失败!")
}
return nil
return ctx, db.AutoMigrate(&sysModel.SysDictionary{})
}
func (d *dictionary) CheckDataExist() bool {
if errors.Is(global.GVA_DB.Where("type = ?", "bool").First(&system.SysDictionary{}).Error, gorm.ErrRecordNotFound) { // 判断是否存在数据
func (i *initDict) TableCreated(ctx context.Context) bool {
db, ok := ctx.Value("db").(*gorm.DB)
if !ok {
return false
}
return db.Migrator().HasTable(&sysModel.SysDictionary{})
}
func (i initDict) InitializerName() string {
return sysModel.SysDictionary{}.TableName()
}
func (i *initDict) InitializeData(ctx context.Context) (next context.Context, err error) {
db, ok := ctx.Value("db").(*gorm.DB)
if !ok {
return ctx, system.ErrMissingDBContext
}
True := true
entities := []sysModel.SysDictionary{
{Name: "性别", Type: "gender", Status: &True, Desc: "性别字典"},
{Name: "数据库int类型", Type: "int", Status: &True, Desc: "int类型对应的数据库类型"},
{Name: "数据库时间日期类型", Type: "time.Time", Status: &True, Desc: "数据库时间日期类型"},
{Name: "数据库浮点型", Type: "float64", Status: &True, Desc: "数据库浮点型"},
{Name: "数据库字符串", Type: "string", Status: &True, Desc: "数据库字符串"},
{Name: "数据库bool类型", Type: "bool", Status: &True, Desc: "数据库bool类型"},
}
if err = db.Create(&entities).Error; err != nil {
return ctx, errors.Wrap(err, sysModel.SysDictionary{}.TableName()+"表数据初始化失败!")
}
next = context.WithValue(ctx, i.InitializerName(), entities)
return next, nil
}
func (i *initDict) DataInserted(ctx context.Context) bool {
db, ok := ctx.Value("db").(*gorm.DB)
if !ok {
return false
}
if errors.Is(db.Where("type = ?", "bool").First(&sysModel.SysDictionary{}).Error, gorm.ErrRecordNotFound) { // 判断是否存在数据
return false
}
return true
+96 -42
View File
@@ -1,59 +1,113 @@
package system
import (
"github.com/flipped-aurora/gin-vue-admin/server/global"
"github.com/flipped-aurora/gin-vue-admin/server/model/system"
"context"
"fmt"
sysModel "github.com/flipped-aurora/gin-vue-admin/server/model/system"
"github.com/flipped-aurora/gin-vue-admin/server/service/system"
"github.com/pkg/errors"
"gorm.io/gorm"
)
var DictionaryDetail = new(dictionaryDetail)
const initOrderDictDetail = initOrderDict + 1
type dictionaryDetail struct{}
type initDictDetail struct{}
func (d *dictionaryDetail) TableName() string {
return "sys_dictionary_details"
// auto run
func init() {
system.RegisterInit(initOrderDictDetail, &initDictDetail{})
}
func (d *dictionaryDetail) Initialize() error {
status := new(bool)
*status = true
entities := []system.SysDictionaryDetail{
{Label: "男", Value: 1, Status: status, Sort: 1, SysDictionaryID: 1},
{Label: "女", Value: 2, Status: status, Sort: 2, SysDictionaryID: 1},
{Label: "smallint", Value: 1, Status: status, Sort: 1, SysDictionaryID: 2},
{Label: "mediumint", Value: 2, Status: status, Sort: 2, SysDictionaryID: 2},
{Label: "int", Value: 3, Status: status, Sort: 3, SysDictionaryID: 2},
{Label: "bigint", Value: 4, Status: status, Sort: 4, SysDictionaryID: 2},
{Label: "date", Status: status, SysDictionaryID: 3},
{Label: "time", Value: 1, Status: status, Sort: 1, SysDictionaryID: 3},
{Label: "year", Value: 2, Status: status, Sort: 2, SysDictionaryID: 3},
{Label: "datetime", Value: 3, Status: status, Sort: 3, SysDictionaryID: 3},
{Label: "timestamp", Value: 5, Status: status, Sort: 5, SysDictionaryID: 3},
{Label: "float", Status: status, SysDictionaryID: 4},
{Label: "double", Value: 1, Status: status, Sort: 1, SysDictionaryID: 4},
{Label: "decimal", Value: 2, Status: status, Sort: 2, SysDictionaryID: 4},
{Label: "char", Status: status, SysDictionaryID: 5},
{Label: "varchar", Value: 1, Status: status, Sort: 1, SysDictionaryID: 5},
{Label: "tinyblob", Value: 2, Status: status, Sort: 2, SysDictionaryID: 5},
{Label: "tinytext", Value: 3, Status: status, Sort: 3, SysDictionaryID: 5},
{Label: "text", Value: 4, Status: status, Sort: 4, SysDictionaryID: 5},
{Label: "blob", Value: 5, Status: status, Sort: 5, SysDictionaryID: 5},
{Label: "mediumblob", Value: 6, Status: status, Sort: 6, SysDictionaryID: 5},
{Label: "mediumtext", Value: 7, Status: status, Sort: 7, SysDictionaryID: 5},
{Label: "longblob", Value: 8, Status: status, Sort: 8, SysDictionaryID: 5},
{Label: "longtext", Value: 9, Status: status, Sort: 9, SysDictionaryID: 5},
{Label: "tinyint", Status: status, SysDictionaryID: 6},
func (i *initDictDetail) MigrateTable(ctx context.Context) (context.Context, error) {
db, ok := ctx.Value("db").(*gorm.DB)
if !ok {
return ctx, system.ErrMissingDBContext
}
if err := global.GVA_DB.Create(&entities).Error; err != nil {
return errors.Wrap(err, d.TableName()+"表数据初始化失败!")
}
return nil
return ctx, db.AutoMigrate(&sysModel.SysDictionaryDetail{})
}
func (d *dictionaryDetail) CheckDataExist() bool {
if errors.Is(global.GVA_DB.Where("id = ?", 23).First(&system.SysDictionaryDetail{}).Error, gorm.ErrRecordNotFound) { // 判断是否存在数据
func (i *initDictDetail) TableCreated(ctx context.Context) bool {
db, ok := ctx.Value("db").(*gorm.DB)
if !ok {
return false
}
return true
return db.Migrator().HasTable(&sysModel.SysDictionaryDetail{})
}
func (i initDictDetail) InitializerName() string {
return sysModel.SysDictionaryDetail{}.TableName()
}
func (i *initDictDetail) InitializeData(ctx context.Context) (context.Context, error) {
db, ok := ctx.Value("db").(*gorm.DB)
if !ok {
return ctx, system.ErrMissingDBContext
}
dicts, ok := ctx.Value(initDict{}.InitializerName()).([]sysModel.SysDictionary)
if !ok {
return ctx, errors.Wrap(system.ErrMissingDependentContext,
fmt.Sprintf("未找到 %s 表初始化数据", sysModel.SysDictionary{}.TableName()))
}
True := true
dicts[0].SysDictionaryDetails = []sysModel.SysDictionaryDetail{
{Label: "男", Value: 1, Status: &True, Sort: 1},
{Label: "女", Value: 2, Status: &True, Sort: 2},
}
dicts[1].SysDictionaryDetails = []sysModel.SysDictionaryDetail{
{Label: "smallint", Value: 1, Status: &True, Sort: 1},
{Label: "mediumint", Value: 2, Status: &True, Sort: 2},
{Label: "int", Value: 3, Status: &True, Sort: 3},
{Label: "bigint", Value: 4, Status: &True, Sort: 4},
}
dicts[2].SysDictionaryDetails = []sysModel.SysDictionaryDetail{
{Label: "date", Status: &True},
{Label: "time", Value: 1, Status: &True, Sort: 1},
{Label: "year", Value: 2, Status: &True, Sort: 2},
{Label: "datetime", Value: 3, Status: &True, Sort: 3},
{Label: "timestamp", Value: 5, Status: &True, Sort: 5},
}
dicts[3].SysDictionaryDetails = []sysModel.SysDictionaryDetail{
{Label: "float", Status: &True},
{Label: "double", Value: 1, Status: &True, Sort: 1},
{Label: "decimal", Value: 2, Status: &True, Sort: 2},
}
dicts[4].SysDictionaryDetails = []sysModel.SysDictionaryDetail{
{Label: "char", Status: &True},
{Label: "varchar", Value: 1, Status: &True, Sort: 1},
{Label: "tinyblob", Value: 2, Status: &True, Sort: 2},
{Label: "tinytext", Value: 3, Status: &True, Sort: 3},
{Label: "text", Value: 4, Status: &True, Sort: 4},
{Label: "blob", Value: 5, Status: &True, Sort: 5},
{Label: "mediumblob", Value: 6, Status: &True, Sort: 6},
{Label: "mediumtext", Value: 7, Status: &True, Sort: 7},
{Label: "longblob", Value: 8, Status: &True, Sort: 8},
{Label: "longtext", Value: 9, Status: &True, Sort: 9},
}
dicts[5].SysDictionaryDetails = []sysModel.SysDictionaryDetail{
{Label: "tinyint", Status: &True},
}
for _, dict := range dicts {
if err := db.Model(&dict).Association("SysDictionaryDetails").
Replace(dict.SysDictionaryDetails); err != nil {
return ctx, errors.Wrap(err, sysModel.SysDictionaryDetail{}.TableName()+"表数据初始化失败!")
}
}
return ctx, nil
}
func (i *initDictDetail) DataInserted(ctx context.Context) bool {
db, ok := ctx.Value("db").(*gorm.DB)
if !ok {
return false
}
var dict sysModel.SysDictionary
if err := db.Preload("SysDictionaryDetails").
First(&dict, &sysModel.SysDictionary{Name: "数据库bool类型"}).Error; err != nil {
return false
}
return len(dict.SysDictionaryDetails) > 0 && dict.SysDictionaryDetails[0].Label == "tinyint"
}
+81 -41
View File
@@ -1,57 +1,97 @@
package system
import (
"github.com/flipped-aurora/gin-vue-admin/server/global"
"github.com/flipped-aurora/gin-vue-admin/server/model/system"
"context"
. "github.com/flipped-aurora/gin-vue-admin/server/model/system"
"github.com/flipped-aurora/gin-vue-admin/server/service/system"
"github.com/pkg/errors"
"gorm.io/gorm"
)
var BaseMenu = new(menu)
const initOrderMenu = initOrderAuthority + 1
type menu struct{}
type initMenu struct{}
func (m *menu) TableName() string {
return "sys_base_menus"
// auto run
func init() {
system.RegisterInit(initOrderMenu, &initMenu{})
}
func (m *menu) Initialize() error {
entities := []system.SysBaseMenu{
{GVA_MODEL: global.GVA_MODEL{ID: 1}, MenuLevel: 0, Hidden: false, ParentId: "0", Path: "dashboard", Name: "dashboard", Component: "view/dashboard/index.vue", Sort: 1, Meta: system.Meta{Title: "仪表盘", Icon: "odometer"}},
{GVA_MODEL: global.GVA_MODEL{ID: 2}, MenuLevel: 0, Hidden: false, ParentId: "0", Path: "about", Name: "about", Component: "view/about/index.vue", Sort: 7, Meta: system.Meta{Title: "关于我们", Icon: "info-filled"}},
{GVA_MODEL: global.GVA_MODEL{ID: 3}, MenuLevel: 0, Hidden: false, ParentId: "0", Path: "admin", Name: "superAdmin", Component: "view/superAdmin/index.vue", Sort: 3, Meta: system.Meta{Title: "超级管理员", Icon: "user"}},
{GVA_MODEL: global.GVA_MODEL{ID: 4}, MenuLevel: 0, Hidden: false, ParentId: "3", Path: "authority", Name: "authority", Component: "view/superAdmin/authority/authority.vue", Sort: 1, Meta: system.Meta{Title: "角色管理", Icon: "avatar"}},
{GVA_MODEL: global.GVA_MODEL{ID: 5}, MenuLevel: 0, Hidden: false, ParentId: "3", Path: "menu", Name: "menu", Component: "view/superAdmin/menu/menu.vue", Sort: 2, Meta: system.Meta{Title: "菜单管理", Icon: "tickets", KeepAlive: true}},
{GVA_MODEL: global.GVA_MODEL{ID: 6}, MenuLevel: 0, Hidden: false, ParentId: "3", Path: "api", Name: "api", Component: "view/superAdmin/api/api.vue", Sort: 3, Meta: system.Meta{Title: "api管理", Icon: "platform", KeepAlive: true}},
{GVA_MODEL: global.GVA_MODEL{ID: 7}, MenuLevel: 0, Hidden: false, ParentId: "3", Path: "user", Name: "user", Component: "view/superAdmin/user/user.vue", Sort: 4, Meta: system.Meta{Title: "用户管理", Icon: "coordinate"}},
{GVA_MODEL: global.GVA_MODEL{ID: 8}, MenuLevel: 0, Hidden: true, ParentId: "0", Path: "person", Name: "person", Component: "view/person/person.vue", Sort: 4, Meta: system.Meta{Title: "个人信息", Icon: "message"}},
{GVA_MODEL: global.GVA_MODEL{ID: 9}, MenuLevel: 0, Hidden: false, ParentId: "0", Path: "example", Name: "example", Component: "view/example/index.vue", Sort: 6, Meta: system.Meta{Title: "示例文件", Icon: "management"}},
{GVA_MODEL: global.GVA_MODEL{ID: 10}, MenuLevel: 0, Hidden: false, ParentId: "9", Path: "excel", Name: "excel", Component: "view/example/excel/excel.vue", Sort: 4, Meta: system.Meta{Title: "excel导入导出", Icon: "takeaway-box"}},
{GVA_MODEL: global.GVA_MODEL{ID: 11}, MenuLevel: 0, Hidden: false, ParentId: "9", Path: "upload", Name: "upload", Component: "view/example/upload/upload.vue", Sort: 5, Meta: system.Meta{Title: "媒体库(上传下载)", Icon: "upload"}},
{GVA_MODEL: global.GVA_MODEL{ID: 12}, MenuLevel: 0, Hidden: false, ParentId: "9", Path: "breakpoint", Name: "breakpoint", Component: "view/example/breakpoint/breakpoint.vue", Sort: 6, Meta: system.Meta{Title: "断点续传", Icon: "upload-filled"}},
{GVA_MODEL: global.GVA_MODEL{ID: 13}, MenuLevel: 0, Hidden: false, ParentId: "9", Path: "customer", Name: "customer", Component: "view/example/customer/customer.vue", Sort: 7, Meta: system.Meta{Title: "客户列表(资源示例)", Icon: "avatar"}},
{GVA_MODEL: global.GVA_MODEL{ID: 14}, MenuLevel: 0, Hidden: false, ParentId: "0", Path: "systemTools", Name: "systemTools", Component: "view/systemTools/index.vue", Sort: 5, Meta: system.Meta{Title: "系统工具", Icon: "tools"}},
{GVA_MODEL: global.GVA_MODEL{ID: 15}, MenuLevel: 0, Hidden: false, ParentId: "14", Path: "autoCode", Name: "autoCode", Component: "view/systemTools/autoCode/index.vue", Sort: 1, Meta: system.Meta{Title: "代码生成器", Icon: "cpu", KeepAlive: true}},
{GVA_MODEL: global.GVA_MODEL{ID: 16}, MenuLevel: 0, Hidden: false, ParentId: "14", Path: "formCreate", Name: "formCreate", Component: "view/systemTools/formCreate/index.vue", Sort: 2, Meta: system.Meta{Title: "表单生成器", Icon: "magic-stick", KeepAlive: true}},
{GVA_MODEL: global.GVA_MODEL{ID: 17}, MenuLevel: 0, Hidden: false, ParentId: "14", Path: "system", Name: "system", Component: "view/systemTools/system/system.vue", Sort: 3, Meta: system.Meta{Title: "系统配置", Icon: "operation"}},
{GVA_MODEL: global.GVA_MODEL{ID: 18}, MenuLevel: 0, Hidden: false, ParentId: "3", Path: "dictionary", Name: "dictionary", Component: "view/superAdmin/dictionary/sysDictionary.vue", Sort: 5, Meta: system.Meta{Title: "字典管理", Icon: "notebook"}},
{GVA_MODEL: global.GVA_MODEL{ID: 19}, MenuLevel: 0, Hidden: true, ParentId: "3", Path: "dictionaryDetail/:id", Name: "dictionaryDetail", Component: "view/superAdmin/dictionary/sysDictionaryDetail.vue", Sort: 1, Meta: system.Meta{Title: "字典详情", Icon: "order"}},
{GVA_MODEL: global.GVA_MODEL{ID: 20}, MenuLevel: 0, Hidden: false, ParentId: "3", Path: "operation", Name: "operation", Component: "view/superAdmin/operation/sysOperationRecord.vue", Sort: 6, Meta: system.Meta{Title: "操作历史", Icon: "pie-chart"}},
{GVA_MODEL: global.GVA_MODEL{ID: 21}, MenuLevel: 0, Hidden: false, ParentId: "9", Path: "simpleUploader", Name: "simpleUploader", Component: "view/example/simpleUploader/simpleUploader", Sort: 6, Meta: system.Meta{Title: "断点续传(插件版)", Icon: "upload"}},
{GVA_MODEL: global.GVA_MODEL{ID: 22}, MenuLevel: 0, Hidden: false, ParentId: "0", Path: "https://www.gin-vue-admin.com", Name: "https://www.gin-vue-admin.com", Component: "/", Sort: 0, Meta: system.Meta{Title: "官方网站", Icon: "home-filled"}},
{GVA_MODEL: global.GVA_MODEL{ID: 23}, MenuLevel: 0, Hidden: false, ParentId: "0", Path: "state", Name: "state", Component: "view/system/state.vue", Sort: 6, Meta: system.Meta{Title: "服务器状态", Icon: "cloudy"}},
{GVA_MODEL: global.GVA_MODEL{ID: 24}, MenuLevel: 0, Hidden: false, ParentId: "14", Path: "autoCodeAdmin", Name: "autoCodeAdmin", Component: "view/systemTools/autoCodeAdmin/index.vue", Sort: 1, Meta: system.Meta{Title: "自动化代码管理", Icon: "magic-stick"}},
{GVA_MODEL: global.GVA_MODEL{ID: 25}, MenuLevel: 0, Hidden: true, ParentId: "14", Path: "autoCodeEdit/:id", Name: "autoCodeEdit", Component: "view/systemTools/autoCode/index.vue", Sort: 0, Meta: system.Meta{Title: "自动化代码(复用)", Icon: "magic-stick"}},
{GVA_MODEL: global.GVA_MODEL{ID: 26}, MenuLevel: 0, Hidden: false, ParentId: "14", Path: "autoPkg", Name: "autoPkg", Component: "view/systemTools/autoPkg/autoPkg.vue", Sort: 0, Meta: system.Meta{Title: "自动化package", Icon: "folder"}},
}
if err := global.GVA_DB.Create(&entities).Error; err != nil { // 创建 model.User 初始化数据
return errors.Wrap(err, m.TableName()+"表数据初始化失败!")
}
return nil
func (i initMenu) InitializerName() string {
return SysBaseMenu{}.TableName()
}
func (m *menu) CheckDataExist() bool {
if errors.Is(global.GVA_DB.Where("path = ?", "autoCodeEdit/:id").First(&system.SysBaseMenu{}).Error, gorm.ErrRecordNotFound) { // 判断是否存在数据
func (i *initMenu) MigrateTable(ctx context.Context) (context.Context, error) {
db, ok := ctx.Value("db").(*gorm.DB)
if !ok {
return ctx, system.ErrMissingDBContext
}
return ctx, db.AutoMigrate(
&SysBaseMenu{},
&SysBaseMenuParameter{},
&Meta{},
&SysBaseMenuBtn{},
)
}
func (i *initMenu) TableCreated(ctx context.Context) bool {
db, ok := ctx.Value("db").(*gorm.DB)
if !ok {
return false
}
m := db.Migrator()
return m.HasTable(&SysBaseMenu{}) &&
m.HasTable(&Meta{}) &&
m.HasTable(&SysBaseMenuParameter{}) &&
m.HasTable(&SysBaseMenuBtn{})
}
func (i *initMenu) InitializeData(ctx context.Context) (next context.Context, err error) {
db, ok := ctx.Value("db").(*gorm.DB)
if !ok {
return ctx, system.ErrMissingDBContext
}
entities := []SysBaseMenu{
{MenuLevel: 0, Hidden: false, ParentId: "0", Path: "dashboard", Name: "dashboard", Component: "view/dashboard/index.vue", Sort: 1, Meta: Meta{Title: "仪表盘", Icon: "odometer"}},
{MenuLevel: 0, Hidden: false, ParentId: "0", Path: "about", Name: "about", Component: "view/about/index.vue", Sort: 7, Meta: Meta{Title: "关于我们", Icon: "info-filled"}},
{MenuLevel: 0, Hidden: false, ParentId: "0", Path: "admin", Name: "superAdmin", Component: "view/superAdmin/index.vue", Sort: 3, Meta: Meta{Title: "超级管理员", Icon: "user"}},
{MenuLevel: 0, Hidden: false, ParentId: "3", Path: "authority", Name: "authority", Component: "view/superAdmin/authority/authority.vue", Sort: 1, Meta: Meta{Title: "角色管理", Icon: "avatar"}},
{MenuLevel: 0, Hidden: false, ParentId: "3", Path: "menu", Name: "menu", Component: "view/superAdmin/menu/menu.vue", Sort: 2, Meta: Meta{Title: "菜单管理", Icon: "tickets", KeepAlive: true}},
{MenuLevel: 0, Hidden: false, ParentId: "3", Path: "api", Name: "api", Component: "view/superAdmin/api/api.vue", Sort: 3, Meta: Meta{Title: "api管理", Icon: "platform", KeepAlive: true}},
{MenuLevel: 0, Hidden: false, ParentId: "3", Path: "user", Name: "user", Component: "view/superAdmin/user/user.vue", Sort: 4, Meta: Meta{Title: "用户管理", Icon: "coordinate"}},
{MenuLevel: 0, Hidden: true, ParentId: "0", Path: "person", Name: "person", Component: "view/person/person.vue", Sort: 4, Meta: Meta{Title: "个人信息", Icon: "message"}},
{MenuLevel: 0, Hidden: false, ParentId: "0", Path: "example", Name: "example", Component: "view/example/index.vue", Sort: 6, Meta: Meta{Title: "示例文件", Icon: "management"}},
{MenuLevel: 0, Hidden: false, ParentId: "9", Path: "excel", Name: "excel", Component: "view/example/excel/excel.vue", Sort: 4, Meta: Meta{Title: "excel导入导出", Icon: "takeaway-box"}},
{MenuLevel: 0, Hidden: false, ParentId: "9", Path: "upload", Name: "upload", Component: "view/example/upload/upload.vue", Sort: 5, Meta: Meta{Title: "媒体库(上传下载)", Icon: "upload"}},
{MenuLevel: 0, Hidden: false, ParentId: "9", Path: "breakpoint", Name: "breakpoint", Component: "view/example/breakpoint/breakpoint.vue", Sort: 6, Meta: Meta{Title: "断点续传", Icon: "upload-filled"}},
{MenuLevel: 0, Hidden: false, ParentId: "9", Path: "customer", Name: "customer", Component: "view/example/customer/customer.vue", Sort: 7, Meta: Meta{Title: "客户列表(资源示例)", Icon: "avatar"}},
{MenuLevel: 0, Hidden: false, ParentId: "0", Path: "systemTools", Name: "systemTools", Component: "view/systemTools/index.vue", Sort: 5, Meta: Meta{Title: "系统工具", Icon: "tools"}},
{MenuLevel: 0, Hidden: false, ParentId: "14", Path: "autoCode", Name: "autoCode", Component: "view/systemTools/autoCode/index.vue", Sort: 1, Meta: Meta{Title: "代码生成器", Icon: "cpu", KeepAlive: true}},
{MenuLevel: 0, Hidden: false, ParentId: "14", Path: "formCreate", Name: "formCreate", Component: "view/systemTools/formCreate/index.vue", Sort: 2, Meta: Meta{Title: "表单生成器", Icon: "magic-stick", KeepAlive: true}},
{MenuLevel: 0, Hidden: false, ParentId: "14", Path: "system", Name: "system", Component: "view/systemTools/system/system.vue", Sort: 3, Meta: Meta{Title: "系统配置", Icon: "operation"}},
{MenuLevel: 0, Hidden: false, ParentId: "3", Path: "dictionary", Name: "dictionary", Component: "view/superAdmin/dictionary/sysDictionary.vue", Sort: 5, Meta: Meta{Title: "字典管理", Icon: "notebook"}},
{MenuLevel: 0, Hidden: true, ParentId: "3", Path: "dictionaryDetail/:id", Name: "dictionaryDetail", Component: "view/superAdmin/dictionary/sysDictionaryDetail.vue", Sort: 1, Meta: Meta{Title: "字典详情", Icon: "order"}},
{MenuLevel: 0, Hidden: false, ParentId: "3", Path: "operation", Name: "operation", Component: "view/superAdmin/operation/sysOperationRecord.vue", Sort: 6, Meta: Meta{Title: "操作历史", Icon: "pie-chart"}},
{MenuLevel: 0, Hidden: false, ParentId: "9", Path: "simpleUploader", Name: "simpleUploader", Component: "view/example/simpleUploader/simpleUploader", Sort: 6, Meta: Meta{Title: "断点续传(插件版)", Icon: "upload"}},
{MenuLevel: 0, Hidden: false, ParentId: "0", Path: "https://www.gin-vue-admin.com", Name: "https://www.gin-vue-admin.com", Component: "/", Sort: 0, Meta: Meta{Title: "官方网站", Icon: "home-filled"}},
{MenuLevel: 0, Hidden: false, ParentId: "0", Path: "state", Name: "state", Component: "view/system/state.vue", Sort: 6, Meta: Meta{Title: "服务器状态", Icon: "cloudy"}},
{MenuLevel: 0, Hidden: false, ParentId: "14", Path: "autoCodeAdmin", Name: "autoCodeAdmin", Component: "view/systemTools/autoCodeAdmin/index.vue", Sort: 1, Meta: Meta{Title: "自动化代码管理", Icon: "magic-stick"}},
{MenuLevel: 0, Hidden: true, ParentId: "14", Path: "autoCodeEdit/:id", Name: "autoCodeEdit", Component: "view/systemTools/autoCode/index.vue", Sort: 0, Meta: Meta{Title: "自动化代码(复用)", Icon: "magic-stick"}},
{MenuLevel: 0, Hidden: false, ParentId: "14", Path: "autoPkg", Name: "autoPkg", Component: "view/systemTools/autoPkg/autoPkg.vue", Sort: 0, Meta: Meta{Title: "自动化package", Icon: "folder"}},
}
if err = db.Create(&entities).Error; err != nil {
return ctx, errors.Wrap(err, SysBaseMenu{}.TableName()+"表数据初始化失败!")
}
next = context.WithValue(ctx, i.InitializerName(), entities)
return next, nil
}
func (i *initMenu) DataInserted(ctx context.Context) bool {
db, ok := ctx.Value("db").(*gorm.DB)
if !ok {
return false
}
if errors.Is(db.Where("path = ?", "autoPkg").First(&SysBaseMenu{}).Error, gorm.ErrRecordNotFound) { // 判断是否存在数据
return false
}
return true
+57 -13
View File
@@ -1,35 +1,79 @@
package system
import (
"context"
"github.com/flipped-aurora/gin-vue-admin/server/global"
"github.com/flipped-aurora/gin-vue-admin/server/model/system"
sysModel "github.com/flipped-aurora/gin-vue-admin/server/model/system"
"github.com/flipped-aurora/gin-vue-admin/server/service/system"
"github.com/pkg/errors"
uuid "github.com/satori/go.uuid"
"gorm.io/gorm"
)
var User = new(user)
const initOrderUser = initOrderAuthority + 1
type user struct{}
type initUser struct{}
func (u *user) TableName() string {
return "sys_users"
// auto run
func init() {
system.RegisterInit(initOrderUser, &initUser{})
}
func (u *user) Initialize() error {
entities := []system.SysUser{
func (i *initUser) MigrateTable(ctx context.Context) (context.Context, error) {
db, ok := ctx.Value("db").(*gorm.DB)
if !ok {
return ctx, system.ErrMissingDBContext
}
return ctx, db.AutoMigrate(&sysModel.SysUser{})
}
func (i *initUser) TableCreated(ctx context.Context) bool {
db, ok := ctx.Value("db").(*gorm.DB)
if !ok {
return false
}
return db.Migrator().HasTable(&sysModel.SysUser{})
}
func (i initUser) InitializerName() string {
return sysModel.SysUser{}.TableName()
}
func (i *initUser) InitializeData(ctx context.Context) (next context.Context, err error) {
db, ok := ctx.Value("db").(*gorm.DB)
if !ok {
return ctx, system.ErrMissingDBContext
}
entities := []sysModel.SysUser{
{UUID: uuid.NewV4(), Username: "admin", Password: "e10adc3949ba59abbe56e057f20f883e", NickName: "超级管理员", HeaderImg: "https://qmplusimg.henrongyi.top/gva_header.jpg", AuthorityId: "888", Phone: "17611111111", Email: "333333333@qq.com"},
{UUID: uuid.NewV4(), Username: "a303176530", Password: "3ec063004a6f31642261936a379fde3d", NickName: "QMPlusUser", HeaderImg: "https:///qmplusimg.henrongyi.top/1572075907logo.png", AuthorityId: "9528", Phone: "17611111111", Email: "333333333@qq.com"},
}
if err := global.GVA_DB.Create(&entities).Error; err != nil {
return errors.Wrap(err, u.TableName()+"表数据初始化失败!")
if err = global.GVA_DB.Create(&entities).Error; err != nil {
return ctx, errors.Wrap(err, sysModel.SysUser{}.TableName()+"表数据初始化失败!")
}
return nil
next = context.WithValue(ctx, i.InitializerName(), entities)
authorityEntities, ok := ctx.Value(initAuthority{}.InitializerName()).([]sysModel.SysAuthority)
if !ok {
return next, errors.Wrap(system.ErrMissingDependentContext, "创建 [用户-权限] 关联失败, 未找到权限表初始化数据")
}
if err = db.Model(&entities[0]).Association("Authorities").Replace(authorityEntities); err != nil {
return next, err
}
if err = db.Model(&entities[1]).Association("Authorities").Replace(authorityEntities[:1]); err != nil {
return next, err
}
return next, err
}
func (u *user) CheckDataExist() bool {
if errors.Is(global.GVA_DB.Where("username = ?", "a303176530").First(&system.SysUser{}).Error, gorm.ErrRecordNotFound) { // 判断是否存在数据
func (i *initUser) DataInserted(ctx context.Context) bool {
db, ok := ctx.Value("db").(*gorm.DB)
if !ok {
return false
}
return true
var record sysModel.SysUser
if errors.Is(db.Where("username = ?", "a303176530").
Preload("Authorities").First(&record).Error, gorm.ErrRecordNotFound) { // 判断是否存在数据
return false
}
return len(record.Authorities) > 0 && record.Authorities[0].AuthorityId == "888"
}
-37
View File
@@ -1,37 +0,0 @@
package system
import (
"github.com/flipped-aurora/gin-vue-admin/server/global"
"github.com/flipped-aurora/gin-vue-admin/server/model/system"
"github.com/pkg/errors"
"gorm.io/gorm"
)
var UserAuthority = new(userAuthority)
type userAuthority struct{}
func (a *userAuthority) TableName() string {
var entity system.SysUseAuthority
return entity.TableName()
}
func (a *userAuthority) Initialize() error {
entities := []system.SysUseAuthority{
{SysUserId: 1, SysAuthorityAuthorityId: "888"},
{SysUserId: 1, SysAuthorityAuthorityId: "8881"},
{SysUserId: 1, SysAuthorityAuthorityId: "9528"},
{SysUserId: 2, SysAuthorityAuthorityId: "888"},
}
if err := global.GVA_DB.Create(&entities).Error; err != nil {
return errors.Wrap(err, a.TableName()+"表数据初始化失败!")
}
return nil
}
func (a *userAuthority) CheckDataExist() bool {
if errors.Is(global.GVA_DB.Where("sys_user_id = ? AND sys_authority_authority_id = ?", 2, "888").First(&system.SysUseAuthority{}).Error, gorm.ErrRecordNotFound) { // 判断是否存在数据
return false
}
return true
}
@@ -1,27 +1,49 @@
package system
import (
"context"
"fmt"
"github.com/flipped-aurora/gin-vue-admin/server/service/system"
"gorm.io/gorm"
"strings"
"github.com/flipped-aurora/gin-vue-admin/server/global"
"github.com/flipped-aurora/gin-vue-admin/server/model/system"
sysModel "github.com/flipped-aurora/gin-vue-admin/server/model/system"
"github.com/pkg/errors"
)
var ViewAuthorityMenuMysql = new(viewAuthorityMenuMysql)
const initOrderMenuViewMysql = initOrderMenuAuthority + 1
type viewAuthorityMenuMysql struct{}
type initMenuViewMysql struct{}
func (v *viewAuthorityMenuMysql) TableName() string {
var entity system.SysMenu
return entity.TableName()
// auto run
func init() {
system.RegisterInit(initOrderMenuViewMysql, &initMenuViewMysql{})
}
func (v *viewAuthorityMenuMysql) Initialize() error {
var entity AuthorityMenus
func (i initMenuViewMysql) InitializerName() string {
return fmt.Sprintf("mysql 视图<%s>", sysModel.SysMenu{}.TableName())
}
func (i *initMenuViewMysql) InitializeData(ctx context.Context) (context.Context, error) {
return ctx, nil
}
func (i *initMenuViewMysql) DataInserted(ctx context.Context) bool {
return true // ignore
}
func (v *initMenuViewMysql) MigrateTable(ctx context.Context) (context.Context, error) {
db, ok := ctx.Value("db").(*gorm.DB)
if !ok {
return ctx, system.ErrMissingDBContext
}
if s, ok := ctx.Value("dbtype").(string); !ok || s != "mysql" {
return ctx, nil // ignore
}
joinTableName := db.Model(&sysModel.SysAuthority{}).Association("SysBaseMenus").Relationship.JoinTable.Name
sql := `
CREATE ALGORITHM = UNDEFINED SQL SECURITY DEFINER VIEW @table_name AS
CREATE OR REPLACE ALGORITHM = UNDEFINED SQL SECURITY DEFINER VIEW @table_name AS
select @menus.id AS id,
@menus.path AS path,
@menus.icon AS icon,
@@ -43,18 +65,23 @@ func (v *viewAuthorityMenuMysql) Initialize() error {
from (@authorities_menus
join @menus on ((@authorities_menus.sys_base_menu_id = @menus.id)));
`
sql = strings.ReplaceAll(sql, "@table_name", v.TableName())
sql = strings.ReplaceAll(sql, "@menus", "sys_base_menus")
sql = strings.ReplaceAll(sql, "@authorities_menus", entity.TableName())
if err := global.GVA_DB.Exec(sql).Error; err != nil {
return errors.Wrap(err, v.TableName()+"视图创建失败!")
sql = strings.ReplaceAll(sql, "@table_name", sysModel.SysMenu{}.TableName())
sql = strings.ReplaceAll(sql, "@menus", sysModel.SysBaseMenu{}.TableName())
sql = strings.ReplaceAll(sql, "@authorities_menus", joinTableName)
if err := db.Exec(sql).Error; err != nil {
return ctx, errors.Wrap(err, sysModel.SysMenu{}.TableName()+"视图创建失败!")
}
return nil
return ctx, nil
}
func (v *viewAuthorityMenuMysql) CheckDataExist() bool {
err1 := global.GVA_DB.Find(&[]system.SysMenu{}).Error
err2 := errors.New(fmt.Sprintf("Error 1146: Table '%v.%v' doesn't exist", global.GVA_CONFIG.Mysql.Dbname, v.TableName()))
func (i *initMenuViewMysql) TableCreated(ctx context.Context) bool {
db, ok := ctx.Value("db").(*gorm.DB)
if !ok {
return false
}
err1 := db.Find(&[]sysModel.SysMenu{}).Error
err2 := errors.New(fmt.Sprintf("Error 1146: Table '%v.%v' doesn't exist",
global.GVA_CONFIG.Mysql.Dbname, sysModel.SysMenu{}.TableName()))
if errors.As(err1, &err2) {
return false
}
@@ -1,27 +1,50 @@
package system
import (
"context"
"fmt"
"github.com/flipped-aurora/gin-vue-admin/server/service/system"
"gorm.io/gorm"
"strings"
"github.com/flipped-aurora/gin-vue-admin/server/global"
"github.com/flipped-aurora/gin-vue-admin/server/model/system"
sysModel "github.com/flipped-aurora/gin-vue-admin/server/model/system"
"github.com/pkg/errors"
)
var ViewAuthorityMenuPostgres = new(viewAuthorityMenuPostgres)
const initOrderMenuViewPg = initOrderMenuAuthority + 1
type viewAuthorityMenuPostgres struct{}
type initMenuViewPg struct{}
func (a *viewAuthorityMenuPostgres) TableName() string {
var entity system.SysMenu
return entity.TableName()
// auto run
func init() {
system.RegisterInit(initOrderMenuViewPg, &initMenuViewPg{})
}
func (a *viewAuthorityMenuPostgres) Initialize() error {
var entity AuthorityMenus
func (i initMenuViewPg) InitializerName() string {
return fmt.Sprintf("postgresql 视图<%s>", sysModel.SysMenu{}.TableName())
}
func (i *initMenuViewPg) InitializeData(ctx context.Context) (context.Context, error) {
return ctx, nil
}
func (i *initMenuViewPg) DataInserted(ctx context.Context) bool {
return true // ignore
}
func (a *initMenuViewPg) MigrateTable(ctx context.Context) (context.Context, error) {
db, ok := ctx.Value("db").(*gorm.DB)
if !ok {
return ctx, system.ErrMissingDBContext
}
if s, ok := ctx.Value("dbtype").(string); !ok || s != "pgsql" {
return ctx, nil // ignore
}
joinTableName := db.Model(&sysModel.SysAuthority{}).Association("SysBaseMenus").Relationship.JoinTable.Name
sql := `
CREATE VIEW @table_name as
CREATE OR REPLACE VIEW @table_name as
select @menus.id as id,
@menus.path as path,
@menus.name as name,
@@ -41,18 +64,19 @@ func (a *viewAuthorityMenuPostgres) Initialize() error {
@authorities_menus.sys_base_menu_id as menu_id,
@authorities_menus.sys_authority_authority_id as authority_id
from (@authorities_menus join @menus on ((@authorities_menus.sys_base_menu_id = @menus.id)));`
sql = strings.ReplaceAll(sql, "@table_name", a.TableName())
sql = strings.ReplaceAll(sql, "@menus", "sys_base_menus")
sql = strings.ReplaceAll(sql, "@authorities_menus", entity.TableName())
sql = strings.ReplaceAll(sql, "@table_name", sysModel.SysMenu{}.TableName())
sql = strings.ReplaceAll(sql, "@menus", sysModel.SysBaseMenu{}.TableName())
sql = strings.ReplaceAll(sql, "@authorities_menus", joinTableName)
if err := global.GVA_DB.Exec(sql).Error; err != nil {
return errors.Wrap(err, a.TableName()+"视图创建失败!")
return ctx, errors.Wrap(err, sysModel.SysMenu{}.TableName()+"视图创建失败!")
}
return nil
return ctx, nil
}
func (a *viewAuthorityMenuPostgres) CheckDataExist() bool {
err1 := global.GVA_DB.Find(&[]system.SysMenu{}).Error
err2 := errors.New(fmt.Sprintf("Error 1146: Table '%v.%v' doesn't exist", global.GVA_CONFIG.Pgsql.Dbname, a.TableName()))
func (a *initMenuViewPg) TableCreated(ctx context.Context) bool {
err1 := global.GVA_DB.Find(&[]sysModel.SysMenu{}).Error
err2 := errors.New(fmt.Sprintf("Error 1146: Table '%v.%v' doesn't exist",
global.GVA_CONFIG.Pgsql.Dbname, sysModel.SysMenu{}.TableName()))
if errors.As(err1, &err2) {
return false
}