Compare commits
17 Commits
Author | SHA1 | Date |
---|---|---|
|
1430943c48 | |
|
4eef560649 | |
|
04053391ef | |
|
9a665704b1 | |
|
b8d5fce311 | |
|
ea7f75be62 | |
|
ea09631d4c | |
|
0cab1c6c61 | |
|
ac9411f525 | |
|
557f3db4ed | |
|
1d312c9741 | |
|
cb46385644 | |
|
79a9746447 | |
|
ef4ad92e35 | |
|
7098529421 | |
|
56d50536fc | |
|
c40bf36de3 |
|
@ -0,0 +1,189 @@
|
|||
package aeusadmin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"git.nobla.cn/golang/aeus-admin/models"
|
||||
"git.nobla.cn/golang/rest"
|
||||
"git.nobla.cn/golang/rest/types"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type (
|
||||
recorder struct {
|
||||
Domain string `json:"domain"`
|
||||
User string `json:"user"`
|
||||
Module string `json:"module"`
|
||||
Table string `json:"table"`
|
||||
Action string `json:"action"`
|
||||
PrimaryKey any `json:"primary_key"`
|
||||
Diffs []*types.DiffAttr `json:"diffs"`
|
||||
}
|
||||
)
|
||||
|
||||
type ActivityRecorder struct {
|
||||
db *gorm.DB
|
||||
ctx context.Context
|
||||
batchTimeout time.Duration
|
||||
BatchSize int
|
||||
ch chan *models.Activity
|
||||
}
|
||||
|
||||
func (s *ActivityRecorder) onAfterCreate(ctx context.Context, tx *gorm.DB, model any, diff []*types.DiffAttr) {
|
||||
v := ctx.Value(rest.RuntimeScopeKey)
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
runtimeScope, ok := v.(*types.RuntimeScope)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
data := &models.Activity{}
|
||||
data.Uid = runtimeScope.User
|
||||
data.Module = runtimeScope.ModuleName
|
||||
data.Table = runtimeScope.TableName
|
||||
data.Action = types.ScenarioCreate
|
||||
if buf, err := json.Marshal(diff); err == nil {
|
||||
data.Data = string(buf)
|
||||
}
|
||||
select {
|
||||
case s.ch <- data:
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ActivityRecorder) onAfterUpdate(ctx context.Context, tx *gorm.DB, model any, diff []*types.DiffAttr) {
|
||||
v := ctx.Value(rest.RuntimeScopeKey)
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
runtimeScope, ok := v.(*types.RuntimeScope)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
data := &models.Activity{}
|
||||
data.Uid = runtimeScope.User
|
||||
data.Module = runtimeScope.ModuleName
|
||||
data.Table = runtimeScope.TableName
|
||||
data.Action = types.ScenarioUpdate
|
||||
if diff == nil {
|
||||
diff = make([]*types.DiffAttr, 0)
|
||||
}
|
||||
diff = append(diff, &types.DiffAttr{
|
||||
Column: "primary_key",
|
||||
NewValue: runtimeScope.PrimaryKeyValue,
|
||||
})
|
||||
if buf, err := json.Marshal(diff); err == nil {
|
||||
data.Data = string(buf)
|
||||
}
|
||||
select {
|
||||
case s.ch <- data:
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ActivityRecorder) onAfterDelete(ctx context.Context, tx *gorm.DB, model any) {
|
||||
v := ctx.Value(rest.RuntimeScopeKey)
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
runtimeScope, ok := v.(*types.RuntimeScope)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
data := &models.Activity{}
|
||||
data.Uid = runtimeScope.User
|
||||
data.Module = runtimeScope.ModuleName
|
||||
data.Table = runtimeScope.TableName
|
||||
data.Action = types.ScenarioDelete
|
||||
diff := make([]*types.DiffAttr, 0, 1)
|
||||
diff = append(diff, &types.DiffAttr{
|
||||
Column: "primary_key",
|
||||
NewValue: runtimeScope.PrimaryKeyValue,
|
||||
})
|
||||
if buf, err := json.Marshal(diff); err == nil {
|
||||
data.Data = string(buf)
|
||||
}
|
||||
select {
|
||||
case s.ch <- data:
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ActivityRecorder) batchWrite(values []*models.Activity) {
|
||||
var (
|
||||
err error
|
||||
)
|
||||
if len(values) <= 0 {
|
||||
return
|
||||
}
|
||||
if err = s.db.Create(values).Error; err != nil {
|
||||
for _, row := range values {
|
||||
s.db.Create(row)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ActivityRecorder) writeLoop() {
|
||||
var (
|
||||
values []*models.Activity
|
||||
)
|
||||
timer := time.NewTimer(s.batchTimeout)
|
||||
defer func() {
|
||||
timer.Stop()
|
||||
if len(values) > 0 {
|
||||
s.batchWrite(values)
|
||||
}
|
||||
}()
|
||||
for {
|
||||
select {
|
||||
case <-s.ctx.Done():
|
||||
return
|
||||
case <-timer.C:
|
||||
if len(values) > 0 {
|
||||
s.batchWrite(values)
|
||||
values = nil
|
||||
}
|
||||
timer.Reset(s.batchTimeout)
|
||||
case msg, ok := <-s.ch:
|
||||
if ok {
|
||||
values = append(values, msg)
|
||||
if len(values) > s.BatchSize {
|
||||
s.batchWrite(values)
|
||||
values = nil
|
||||
timer.Reset(s.batchTimeout)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ActivityRecorder) Recoder(scenes ...string) {
|
||||
if len(scenes) == 0 {
|
||||
scenes = []string{types.ScenarioCreate, types.ScenarioUpdate, types.ScenarioDelete}
|
||||
}
|
||||
for _, str := range scenes {
|
||||
switch str {
|
||||
case types.ScenarioCreate:
|
||||
rest.OnAfterCreate(s.onAfterCreate)
|
||||
case types.ScenarioUpdate:
|
||||
rest.OnAfterUpdate(s.onAfterUpdate)
|
||||
case types.ScenarioDelete:
|
||||
rest.OnAfterDelete(s.onAfterDelete)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func NewActivityRecorder(ctx context.Context, db *gorm.DB) *ActivityRecorder {
|
||||
s := &ActivityRecorder{
|
||||
db: db,
|
||||
ctx: ctx,
|
||||
batchTimeout: time.Second,
|
||||
BatchSize: 50,
|
||||
ch: make(chan *models.Activity, 100),
|
||||
}
|
||||
go s.writeLoop()
|
||||
return s
|
||||
}
|
|
@ -1,58 +0,0 @@
|
|||
package defaults
|
||||
|
||||
import (
|
||||
"git.nobla.cn/golang/aeus-admin/models"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var (
|
||||
defaultRoles = []*models.Role{}
|
||||
defaultUsers = []*models.User{}
|
||||
)
|
||||
|
||||
func init() {
|
||||
adminRole := &models.Role{}
|
||||
adminRole.Name = "admin"
|
||||
adminRole.Label = "管理员"
|
||||
adminRole.Description = "管理员角色"
|
||||
defaultRoles = append(defaultRoles, adminRole)
|
||||
|
||||
adminUser := &models.User{}
|
||||
adminUser.Uid = "admin"
|
||||
adminUser.Username = "admin"
|
||||
adminUser.Password = "admin"
|
||||
adminUser.Role = "admin"
|
||||
adminUser.Admin = true
|
||||
|
||||
guestUser := &models.User{}
|
||||
guestUser.Uid = "guest"
|
||||
guestUser.Username = "guest"
|
||||
guestUser.Password = "guest"
|
||||
guestUser.Role = "admin"
|
||||
defaultUsers = append(defaultUsers, adminUser, guestUser)
|
||||
}
|
||||
|
||||
func Init(db *gorm.DB) (err error) {
|
||||
var (
|
||||
n int64
|
||||
)
|
||||
if db.Model(&models.Role{}).Count(&n); n == 0 {
|
||||
db.Create(defaultRoles)
|
||||
permissions := make([]*models.Permission, 0)
|
||||
db.Find(&permissions)
|
||||
for _, row := range defaultRoles {
|
||||
items := make([]*models.RolePermission, 0)
|
||||
for _, perm := range permissions {
|
||||
item := &models.RolePermission{}
|
||||
item.Role = row.Name
|
||||
item.PermissionId = perm.Id
|
||||
items = append(items, item)
|
||||
}
|
||||
db.Save(items)
|
||||
}
|
||||
}
|
||||
if db.Model(&models.User{}).Count(&n); n == 0 {
|
||||
db.Create(defaultUsers)
|
||||
}
|
||||
return
|
||||
}
|
|
@ -0,0 +1,81 @@
|
|||
package aeusadmin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"git.nobla.cn/golang/aeus-admin/internal/logic"
|
||||
"git.nobla.cn/golang/aeus/pkg/cache"
|
||||
"git.nobla.cn/golang/rest"
|
||||
"git.nobla.cn/golang/rest/types"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type Formatter struct {
|
||||
db *gorm.DB
|
||||
user *logic.User
|
||||
department *logic.Department
|
||||
role *logic.Role
|
||||
menu *logic.Menu
|
||||
}
|
||||
|
||||
func (f *Formatter) FormatUser(ctx context.Context, value, model any, scm *types.Schema) any {
|
||||
if values, err := f.user.GetLabels(ctx); err == nil {
|
||||
for _, row := range values {
|
||||
if row.Value == value {
|
||||
return fmt.Sprintf("%s(%s)", row.Label, row.Value)
|
||||
}
|
||||
}
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
func (f *Formatter) FormatDepartment(ctx context.Context, value, model any, scm *types.Schema) any {
|
||||
if values, err := f.department.GetLabels(ctx); err == nil {
|
||||
for _, row := range values {
|
||||
if row.Value == value {
|
||||
return row.Label
|
||||
}
|
||||
}
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
func (f *Formatter) FormatRole(ctx context.Context, value, model any, scm *types.Schema) any {
|
||||
if values, err := f.role.GetLabels(ctx); err == nil {
|
||||
for _, row := range values {
|
||||
if row.Value == value {
|
||||
return row.Label
|
||||
}
|
||||
}
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
func (f *Formatter) FormatMenu(ctx context.Context, value, model any, scm *types.Schema) any {
|
||||
if values, err := f.menu.GetLabels(ctx); err == nil {
|
||||
for _, row := range values {
|
||||
if row.Value == value {
|
||||
return row.Label
|
||||
}
|
||||
}
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
func (f *Formatter) Register() {
|
||||
rest.DefaultFormatter.Register("user", f.FormatUser)
|
||||
rest.DefaultFormatter.Register("department", f.FormatDepartment)
|
||||
rest.DefaultFormatter.Register("role", f.FormatRole)
|
||||
rest.DefaultFormatter.Register("menu", f.FormatMenu)
|
||||
}
|
||||
|
||||
func NewFormatter(db *gorm.DB, ch cache.Cache) *Formatter {
|
||||
return &Formatter{
|
||||
db: db,
|
||||
user: logic.NewUserLogic(db, ch),
|
||||
department: logic.NewDepartmentLogic(db, ch),
|
||||
role: logic.NewRoleLogic(db, ch),
|
||||
menu: logic.NewMenuLogic(db, ch),
|
||||
}
|
||||
}
|
20
go.mod
20
go.mod
|
@ -5,8 +5,8 @@ go 1.23.0
|
|||
toolchain go1.23.10
|
||||
|
||||
require (
|
||||
git.nobla.cn/golang/aeus v0.0.7
|
||||
git.nobla.cn/golang/rest v0.1.1
|
||||
git.nobla.cn/golang/aeus v0.0.11
|
||||
git.nobla.cn/golang/rest v0.1.4
|
||||
github.com/envoyproxy/protoc-gen-validate v1.2.1
|
||||
golang.org/x/text v0.23.0 // indirect
|
||||
google.golang.org/protobuf v1.36.6
|
||||
|
@ -16,12 +16,15 @@ require (
|
|||
|
||||
require (
|
||||
github.com/golang-jwt/jwt/v5 v5.2.2
|
||||
github.com/mssola/useragent v1.0.0
|
||||
golang.org/x/sync v0.12.0
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20250303144028-a0af3efb3deb
|
||||
google.golang.org/grpc v1.72.2
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
gorm.io/driver/postgres v1.6.0
|
||||
gorm.io/driver/sqlite v1.6.0
|
||||
)
|
||||
|
||||
replace git.nobla.cn/golang/aeus v0.0.7 => /Users/yavolte/Workspace/golang/aeus
|
||||
|
||||
require (
|
||||
filippo.io/edwards25519 v1.1.0 // indirect
|
||||
git.nobla.cn/golang/kos v0.1.32 // indirect
|
||||
|
@ -38,22 +41,27 @@ require (
|
|||
github.com/go-sql-driver/mysql v1.8.1 // indirect
|
||||
github.com/goccy/go-json v0.10.2 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/pgx/v5 v5.6.0 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||
github.com/jinzhu/now v1.1.5 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.2.7 // indirect
|
||||
github.com/kr/text v0.2.0 // indirect
|
||||
github.com/leodido/go-urn v1.4.0 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/mattn/go-sqlite3 v1.14.22 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.2.2 // indirect
|
||||
github.com/rogpeppe/go-internal v1.14.1 // indirect
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||
github.com/ugorji/go/codec v1.2.12 // indirect
|
||||
golang.org/x/arch v0.8.0 // indirect
|
||||
golang.org/x/crypto v0.36.0 // indirect
|
||||
golang.org/x/net v0.38.0 // indirect
|
||||
golang.org/x/sync v0.12.0 // indirect
|
||||
golang.org/x/sys v0.31.0 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20250303144028-a0af3efb3deb // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
|
|
32
go.sum
32
go.sum
|
@ -1,9 +1,11 @@
|
|||
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
|
||||
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
|
||||
git.nobla.cn/golang/aeus v0.0.11 h1:gbXIOVOQRDTIQTjw9wPVfNC9nXBaTJCABeDYmrHW2Oc=
|
||||
git.nobla.cn/golang/aeus v0.0.11/go.mod h1:oOEwqIp6AhKKqj6sLFO8x7IycOROYHCb/2/CjF4+9CU=
|
||||
git.nobla.cn/golang/kos v0.1.32 h1:sFVCA7vKc8dPUd0cxzwExOSPX2mmMh2IuwL6cYS1pBc=
|
||||
git.nobla.cn/golang/kos v0.1.32/go.mod h1:35Z070+5oB39WcVrh5DDlnVeftL/Ccmscw2MZFe9fUg=
|
||||
git.nobla.cn/golang/rest v0.1.1 h1:xsGO/1rDrjcmpeZWv7k1sjqACurBQy5l9wVZ430w0tQ=
|
||||
git.nobla.cn/golang/rest v0.1.1/go.mod h1:4viDk7VujDokpUeHQGbnSp2bkkVZEoIkWQIs/l/TTPQ=
|
||||
git.nobla.cn/golang/rest v0.1.4 h1:9/XscfNXI3aPESpy8CPtVl17VSMxU9BihhedeG+h8YY=
|
||||
git.nobla.cn/golang/rest v0.1.4/go.mod h1:4viDk7VujDokpUeHQGbnSp2bkkVZEoIkWQIs/l/TTPQ=
|
||||
github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0=
|
||||
github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4=
|
||||
github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM=
|
||||
|
@ -12,6 +14,7 @@ github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/
|
|||
github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w=
|
||||
github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg=
|
||||
github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY=
|
||||
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
|
@ -48,6 +51,14 @@ github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeN
|
|||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgx/v5 v5.6.0 h1:SWJzexBzPL5jb0GEsrPMLIsi/3jOo7RHlzTjcAeDrPY=
|
||||
github.com/jackc/pgx/v5 v5.6.0/go.mod h1:DNZ/vlrUnhWCoFGxHAG8U2ljioxukquj7utPDgtQdTw=
|
||||
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
|
||||
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
|
||||
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
|
||||
|
@ -58,19 +69,29 @@ github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa02
|
|||
github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM=
|
||||
github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
|
||||
github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=
|
||||
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
|
||||
github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
||||
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
|
||||
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
|
||||
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||
github.com/mssola/useragent v1.0.0 h1:WRlDpXyxHDNfvZaPEut5Biveq86Ze4o4EMffyMxmH5o=
|
||||
github.com/mssola/useragent v1.0.0/go.mod h1:hz9Cqz4RXusgg1EdI4Al0INR62kP7aPSRNHnpU+b85Y=
|
||||
github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM=
|
||||
github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
|
||||
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
|
@ -122,13 +143,18 @@ google.golang.org/grpc v1.72.2 h1:TdbGzwb82ty4OusHWepvFWGLgIbNo1/SUynEN0ssqv8=
|
|||
google.golang.org/grpc v1.72.2/go.mod h1:wH5Aktxcg25y1I3w7H69nHfXdOG3UiadoBtjh3izSDM=
|
||||
google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY=
|
||||
google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gorm.io/driver/mysql v1.6.0 h1:eNbLmNTpPpTOVZi8MMxCi2aaIm0ZpInbORNXDwyLGvg=
|
||||
gorm.io/driver/mysql v1.6.0/go.mod h1:D/oCC2GWK3M/dqoLxnOlaNKmXz8WNTfcS9y5ovaSqKo=
|
||||
gorm.io/driver/postgres v1.6.0 h1:2dxzU8xJ+ivvqTRph34QX+WrRaJlmfyPqXmoGVjMBa4=
|
||||
gorm.io/driver/postgres v1.6.0/go.mod h1:vUw0mrGgrTK+uPHEhAdV4sfFELrByKVGnaVRkXDhtWo=
|
||||
gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ=
|
||||
gorm.io/driver/sqlite v1.6.0/go.mod h1:AO9V1qIQddBESngQUKWL9yoH93HIeA1X6V633rBwyT8=
|
||||
gorm.io/gorm v1.30.0 h1:qbT5aPv1UH8gI99OsRlvDToLxW5zR7FzS9acZDOZcgs=
|
||||
gorm.io/gorm v1.30.0/go.mod h1:8Z33v652h4//uMA76KjeDH8mJXPm1QNCYrMeatR0DOE=
|
||||
nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=
|
||||
|
|
|
@ -19,6 +19,9 @@ func (t *ZH) Menu(model *rest.Model, label string) string {
|
|||
if _, ok := model.Value().Interface().(models.Role); ok {
|
||||
return "角色管理"
|
||||
}
|
||||
if _, ok := model.Value().Interface().(models.Login); ok {
|
||||
return "登录记录"
|
||||
}
|
||||
if _, ok := model.Value().Interface().(models.Permission); ok {
|
||||
return "权限管理"
|
||||
}
|
||||
|
@ -28,6 +31,12 @@ func (t *ZH) Menu(model *rest.Model, label string) string {
|
|||
if _, ok := model.Value().Interface().(models.RolePermission); ok {
|
||||
return "角色权限"
|
||||
}
|
||||
if _, ok := model.Value().Interface().(models.Setting); ok {
|
||||
return "参数设置"
|
||||
}
|
||||
if _, ok := model.Value().Interface().(models.Activity); ok {
|
||||
return "操作记录"
|
||||
}
|
||||
return label
|
||||
}
|
||||
|
||||
|
|
|
@ -0,0 +1,99 @@
|
|||
package logic
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"git.nobla.cn/golang/aeus-admin/models"
|
||||
"git.nobla.cn/golang/aeus-admin/pkg/dbcache"
|
||||
"git.nobla.cn/golang/aeus/pkg/cache"
|
||||
"git.nobla.cn/golang/rest"
|
||||
"git.nobla.cn/golang/rest/types"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type Department struct {
|
||||
db *gorm.DB
|
||||
cache cache.Cache
|
||||
sqlDependency *dbcache.SqlDependency
|
||||
}
|
||||
|
||||
func (u *Department) RecursiveDepartment(ctx context.Context, parent int64, level int, departments []*models.Department) []*types.TypeValue[int64] {
|
||||
var (
|
||||
child []*types.TypeValue[int64]
|
||||
)
|
||||
values := make([]*types.TypeValue[int64], 0, len(departments))
|
||||
for _, dept := range departments {
|
||||
if dept.ParentId == parent {
|
||||
if level == 0 {
|
||||
values = append(values, &types.TypeValue[int64]{
|
||||
Label: dept.Name,
|
||||
Value: dept.Id,
|
||||
})
|
||||
} else {
|
||||
values = append(values, &types.TypeValue[int64]{
|
||||
Label: strings.Repeat("--", level) + dept.Name,
|
||||
Value: dept.Id,
|
||||
})
|
||||
}
|
||||
child = u.RecursiveDepartment(ctx, dept.Id, level+1, departments)
|
||||
if len(child) > 0 {
|
||||
for _, row := range child {
|
||||
values = append(values, row)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return values
|
||||
}
|
||||
|
||||
// GetLevelLabels 获取层级标签
|
||||
func (u *Department) GetLevelLabels(ctx context.Context) (values []*types.TypeValue[int64], err error) {
|
||||
values, err = dbcache.TryCache(ctx, fmt.Sprintf("department:level:labels"), func(tx *gorm.DB) ([]*types.TypeValue[int64], error) {
|
||||
var values []*models.Department
|
||||
if err = tx.Find(&values).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return u.RecursiveDepartment(ctx, 0, 0, values), nil
|
||||
},
|
||||
dbcache.WithDB(u.db),
|
||||
dbcache.WithCache(u.cache),
|
||||
dbcache.WithDependency(u.sqlDependency),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
// GetLabels 获取用户标签
|
||||
func (u *Department) GetLabels(ctx context.Context) (values []*types.TypeValue[int64], err error) {
|
||||
values, err = dbcache.TryCache(ctx, fmt.Sprintf("department:labels"), func(tx *gorm.DB) ([]*types.TypeValue[int64], error) {
|
||||
return rest.ModelTypes[int64](ctx, tx, &models.Department{}, "", "name", "id")
|
||||
},
|
||||
dbcache.WithDB(u.db),
|
||||
dbcache.WithCache(u.cache),
|
||||
dbcache.WithDependency(u.sqlDependency),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
// GetDepartments 获取部门列表
|
||||
func (u *Department) GetDepartments(ctx context.Context) (values []*models.Department, err error) {
|
||||
values, err = dbcache.TryCache(ctx, fmt.Sprintf("department:list"), func(tx *gorm.DB) ([]*models.Department, error) {
|
||||
var items []*models.Department
|
||||
err = tx.Find(&items).Error
|
||||
return items, err
|
||||
},
|
||||
dbcache.WithDB(u.db),
|
||||
dbcache.WithCache(u.cache),
|
||||
dbcache.WithDependency(u.sqlDependency),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
func NewDepartmentLogic(db *gorm.DB, ch cache.Cache) *Department {
|
||||
return &Department{
|
||||
db: db,
|
||||
cache: ch,
|
||||
sqlDependency: dbcache.NewSqlDependency("SELECT MAX(`updated_at`) FROM `departments`"),
|
||||
}
|
||||
}
|
|
@ -0,0 +1,49 @@
|
|||
package logic
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"git.nobla.cn/golang/aeus-admin/models"
|
||||
"git.nobla.cn/golang/aeus-admin/pkg/dbcache"
|
||||
"git.nobla.cn/golang/aeus/pkg/cache"
|
||||
"git.nobla.cn/golang/rest"
|
||||
"git.nobla.cn/golang/rest/types"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type Menu struct {
|
||||
db *gorm.DB
|
||||
cache cache.Cache
|
||||
sqlDependency *dbcache.SqlDependency
|
||||
}
|
||||
|
||||
func (u *Menu) GetMenus(ctx context.Context) (values []*models.Menu, err error) {
|
||||
return dbcache.TryCache(ctx, "menus", func(tx *gorm.DB) ([]*models.Menu, error) {
|
||||
var items []*models.Menu
|
||||
err = tx.Order("`position`,`id` ASC").Find(&items).Error
|
||||
return items, err
|
||||
},
|
||||
dbcache.WithDB(u.db),
|
||||
dbcache.WithCache(u.cache),
|
||||
dbcache.WithDependency(u.sqlDependency),
|
||||
)
|
||||
}
|
||||
|
||||
func (u *Menu) GetLabels(ctx context.Context) (values []*types.TypeValue[string], err error) {
|
||||
return dbcache.TryCache(ctx, fmt.Sprintf("menu:labels"), func(tx *gorm.DB) ([]*types.TypeValue[string], error) {
|
||||
return rest.ModelTypes[string](ctx, tx, &models.Menu{}, "", "label", "name")
|
||||
},
|
||||
dbcache.WithDB(u.db),
|
||||
dbcache.WithCache(u.cache),
|
||||
dbcache.WithDependency(u.sqlDependency),
|
||||
)
|
||||
}
|
||||
|
||||
func NewMenuLogic(db *gorm.DB, ch cache.Cache) *Menu {
|
||||
return &Menu{
|
||||
db: db,
|
||||
cache: ch,
|
||||
sqlDependency: dbcache.NewSqlDependency("SELECT MAX(`updated_at`) FROM `menus`"),
|
||||
}
|
||||
}
|
|
@ -0,0 +1,65 @@
|
|||
package logic
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"git.nobla.cn/golang/aeus-admin/models"
|
||||
"git.nobla.cn/golang/aeus-admin/pkg/dbcache"
|
||||
"git.nobla.cn/golang/aeus/pkg/cache"
|
||||
"git.nobla.cn/golang/rest"
|
||||
"git.nobla.cn/golang/rest/types"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type Role struct {
|
||||
db *gorm.DB
|
||||
cache cache.Cache
|
||||
sqlDependency *dbcache.SqlDependency
|
||||
permissionSqlDependency *dbcache.SqlDependency
|
||||
}
|
||||
|
||||
func (u *Role) GetLabels(ctx context.Context) (values []*types.TypeValue[string], err error) {
|
||||
values, err = dbcache.TryCache(ctx, fmt.Sprintf("role:labels"), func(tx *gorm.DB) ([]*types.TypeValue[string], error) {
|
||||
return rest.ModelTypes[string](ctx, tx, &models.Role{}, "", "label", "name")
|
||||
},
|
||||
dbcache.WithDB(u.db),
|
||||
dbcache.WithCache(u.cache),
|
||||
dbcache.WithDependency(u.sqlDependency),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
func (u *Role) GetPermissions(ctx context.Context, role string) (values []*models.Permission, err error) {
|
||||
cacheKey := "role:permissions:"
|
||||
if role == "" {
|
||||
cacheKey += "all"
|
||||
} else {
|
||||
cacheKey += role
|
||||
}
|
||||
values, err = dbcache.TryCache(ctx, cacheKey, func(tx *gorm.DB) ([]*models.Permission, error) {
|
||||
var items []*models.Permission
|
||||
if role == "" {
|
||||
err = tx.Find(&items).Error
|
||||
} else {
|
||||
err = tx.
|
||||
Where("`permission` IN (SELECT `permission` FROM role_permissions WHERE `role` = ?)", role).
|
||||
Find(&items).Error
|
||||
}
|
||||
return items, err
|
||||
},
|
||||
dbcache.WithDB(u.db),
|
||||
dbcache.WithCache(u.cache),
|
||||
dbcache.WithDependency(u.permissionSqlDependency),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
func NewRoleLogic(db *gorm.DB, ch cache.Cache) *Role {
|
||||
return &Role{
|
||||
db: db,
|
||||
cache: ch,
|
||||
sqlDependency: dbcache.NewSqlDependency("SELECT MAX(`updated_at`) FROM `roles`"),
|
||||
permissionSqlDependency: dbcache.NewSqlDependency("SELECT MAX(`updated_at`) FROM `permissions`"),
|
||||
}
|
||||
}
|
|
@ -0,0 +1,75 @@
|
|||
package logic
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"git.nobla.cn/golang/aeus-admin/models"
|
||||
"git.nobla.cn/golang/aeus-admin/pkg/dbcache"
|
||||
"git.nobla.cn/golang/aeus/pkg/cache"
|
||||
"git.nobla.cn/golang/rest"
|
||||
"git.nobla.cn/golang/rest/types"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
db *gorm.DB
|
||||
cache cache.Cache
|
||||
sqlDependency *dbcache.SqlDependency
|
||||
roleDependency *dbcache.SqlDependency
|
||||
}
|
||||
|
||||
// GetPermissions 获取用户权限
|
||||
func (u *User) GetPermissions(ctx context.Context, uid string) (permissions []string, err error) {
|
||||
permissions, err = dbcache.TryCache(ctx, fmt.Sprintf("user:permissions:%s", uid), func(tx *gorm.DB) ([]string, error) {
|
||||
var ss []string
|
||||
err = tx.Select("permission").Model(&models.RolePermission{}).
|
||||
Joins("LEFT JOIN users on users.role = role_permissions.role").
|
||||
Where("users.uid = ?", uid).
|
||||
Pluck("permission", &ss).
|
||||
Error
|
||||
return ss, err
|
||||
},
|
||||
dbcache.WithDependency(u.roleDependency),
|
||||
dbcache.WithCacheDuration(time.Second*20),
|
||||
dbcache.WithDB(u.db),
|
||||
dbcache.WithCache(u.cache),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
// GetLabels 获取用户标签
|
||||
func (u *User) GetLabels(ctx context.Context) (values []*types.TypeValue[string], err error) {
|
||||
values, err = dbcache.TryCache(ctx, fmt.Sprintf("user:labels"), func(tx *gorm.DB) ([]*types.TypeValue[string], error) {
|
||||
return rest.ModelTypes[string](ctx, tx, &models.User{}, "", "username", "uid")
|
||||
},
|
||||
dbcache.WithDB(u.db),
|
||||
dbcache.WithCache(u.cache),
|
||||
dbcache.WithDependency(u.sqlDependency),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
// GeUsers 获取部门列表
|
||||
func (u *User) GeUsers(ctx context.Context) (values []*models.User, err error) {
|
||||
values, err = dbcache.TryCache(ctx, fmt.Sprintf("user:list"), func(tx *gorm.DB) ([]*models.User, error) {
|
||||
var items []*models.User
|
||||
err = tx.Find(&items).Error
|
||||
return items, err
|
||||
},
|
||||
dbcache.WithDB(u.db),
|
||||
dbcache.WithCache(u.cache),
|
||||
dbcache.WithDependency(u.sqlDependency),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
func NewUserLogic(db *gorm.DB, ch cache.Cache) *User {
|
||||
return &User{
|
||||
db: db,
|
||||
cache: ch,
|
||||
roleDependency: dbcache.NewSqlDependency("SELECT COUNT(*) AS count FROM `role_permissions`"),
|
||||
sqlDependency: dbcache.NewSqlDependency("SELECT MAX(`updated_at`) FROM `users`"),
|
||||
}
|
||||
}
|
|
@ -0,0 +1,85 @@
|
|||
package migrate
|
||||
|
||||
import (
|
||||
"git.nobla.cn/golang/aeus-admin/models"
|
||||
)
|
||||
|
||||
var (
|
||||
defaultRoles = []*models.Role{}
|
||||
defaultUsers = []*models.User{}
|
||||
defaultMenus = []*models.Menu{}
|
||||
defaultDepartments = []*models.Department{}
|
||||
)
|
||||
|
||||
func init() {
|
||||
adminRole := &models.Role{}
|
||||
adminRole.Name = "admin"
|
||||
adminRole.Label = "管理员"
|
||||
adminRole.Description = "管理员角色"
|
||||
defaultRoles = append(defaultRoles, adminRole)
|
||||
|
||||
adminUser := &models.User{}
|
||||
adminUser.Uid = "admin"
|
||||
adminUser.Username = "管理员"
|
||||
adminUser.Password = "admin"
|
||||
adminUser.Role = "admin"
|
||||
adminUser.Admin = true
|
||||
adminUser.DeptId = 1
|
||||
|
||||
guestUser := &models.User{}
|
||||
guestUser.Uid = "test"
|
||||
guestUser.Username = "测试人员"
|
||||
guestUser.Password = "test"
|
||||
guestUser.Role = "admin"
|
||||
guestUser.DeptId = 1
|
||||
defaultUsers = append(defaultUsers, adminUser, guestUser)
|
||||
|
||||
dashboardMenu := &models.Menu{}
|
||||
dashboardMenu.Icon = "dashboard"
|
||||
dashboardMenu.Label = "系统首页"
|
||||
dashboardMenu.Name = "Dashboard"
|
||||
dashboardMenu.Public = true
|
||||
dashboardMenu.Uri = "/dashboard"
|
||||
dashboardMenu.ViewPath = "../views/dashboard/Index.vue"
|
||||
|
||||
orgMenu := &models.Menu{}
|
||||
orgMenu.Icon = "org"
|
||||
orgMenu.Label = "组织机构"
|
||||
orgMenu.Name = "Organize"
|
||||
orgMenu.Public = true
|
||||
orgMenu.Uri = "/organize"
|
||||
orgMenu.Position = 1
|
||||
|
||||
profileMenu := &models.Menu{}
|
||||
profileMenu.Label = "个人信息"
|
||||
profileMenu.Name = "OrganizeUserProfile"
|
||||
profileMenu.Public = true
|
||||
profileMenu.Hidden = true
|
||||
profileMenu.Parent = "Organize"
|
||||
profileMenu.Uri = "/organize/user/profile"
|
||||
profileMenu.ViewPath = "../views/organize/user/Profile.vue"
|
||||
|
||||
settingMenu := &models.Menu{}
|
||||
settingMenu.Icon = "connect"
|
||||
settingMenu.Label = "系统设置"
|
||||
settingMenu.Name = "System"
|
||||
settingMenu.Public = true
|
||||
settingMenu.Uri = "/system"
|
||||
settingMenu.Position = 999
|
||||
|
||||
schemaMenu := &models.Menu{}
|
||||
schemaMenu.Label = "字段设置"
|
||||
schemaMenu.Parent = "System"
|
||||
schemaMenu.Name = "SystemSchema"
|
||||
schemaMenu.Uri = "/system/schemas"
|
||||
schemaMenu.Public = true
|
||||
schemaMenu.Hidden = true
|
||||
schemaMenu.ViewPath = "../views/system/schema/Index.vue"
|
||||
|
||||
defaultMenus = append(defaultMenus, dashboardMenu, orgMenu, settingMenu, profileMenu, schemaMenu)
|
||||
|
||||
systemDepartment := &models.Department{}
|
||||
systemDepartment.Name = "系统部门"
|
||||
systemDepartment.Description = ""
|
||||
defaultDepartments = append(defaultDepartments, systemDepartment)
|
||||
}
|
|
@ -0,0 +1,75 @@
|
|||
package migrate
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"git.nobla.cn/golang/aeus-admin/models"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Menu 合并菜单
|
||||
func Menu(db *gorm.DB, datas ...*models.Menu) (err error) {
|
||||
tx := db.Begin()
|
||||
for _, model := range datas {
|
||||
if err = tx.Where("name = ?", model.Name).First(model).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
if err = tx.Create(model).Error; err != nil {
|
||||
tx.Rollback()
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
err = tx.Commit().Error
|
||||
return
|
||||
}
|
||||
|
||||
// Permission 合并权限数据
|
||||
func Permission(db *gorm.DB, menuName string, permission string, label string) (permissionModel *models.Permission, err error) {
|
||||
permissionModel = &models.Permission{}
|
||||
if err = db.Where("permission = ? AND menu = ?", permission, menuName).First(permissionModel).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
permissionModel.Menu = menuName
|
||||
permissionModel.Label = label
|
||||
permissionModel.Permission = permission
|
||||
err = db.Create(permissionModel).Error
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// #2c7be5
|
||||
// Default 合并初始化数据集
|
||||
func Default(db *gorm.DB) (err error) {
|
||||
var (
|
||||
n int64
|
||||
)
|
||||
for _, row := range defaultMenus {
|
||||
if err = Menu(db, row); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
if db.Model(&models.Role{}).Count(&n); n == 0 {
|
||||
db.Create(defaultRoles)
|
||||
permissions := make([]*models.Permission, 0)
|
||||
db.Find(&permissions)
|
||||
for _, row := range defaultRoles {
|
||||
items := make([]*models.RolePermission, 0)
|
||||
for _, perm := range permissions {
|
||||
item := &models.RolePermission{}
|
||||
item.Role = row.Name
|
||||
item.Permission = perm.Permission
|
||||
items = append(items, item)
|
||||
}
|
||||
db.Save(items)
|
||||
}
|
||||
}
|
||||
|
||||
if db.Model(&models.Department{}).Count(&n); n == 0 {
|
||||
db.Create(defaultDepartments)
|
||||
}
|
||||
if db.Model(&models.User{}).Count(&n); n == 0 {
|
||||
db.Create(defaultUsers)
|
||||
}
|
||||
return
|
||||
}
|
168
models/model.go
168
models/model.go
|
@ -1,6 +1,13 @@
|
|||
package models
|
||||
|
||||
import "git.nobla.cn/golang/aeus-admin/pb"
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"git.nobla.cn/golang/aeus-admin/pb"
|
||||
"git.nobla.cn/golang/aeus-admin/types"
|
||||
restTypes "git.nobla.cn/golang/rest/types"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type (
|
||||
User struct {
|
||||
|
@ -9,6 +16,9 @@ type (
|
|||
Menu struct {
|
||||
pb.MenuModel
|
||||
}
|
||||
Login struct {
|
||||
pb.LoginModel
|
||||
}
|
||||
Department struct {
|
||||
pb.DepartmentModel
|
||||
}
|
||||
|
@ -21,4 +31,160 @@ type (
|
|||
RolePermission struct {
|
||||
pb.RolePermissionModel
|
||||
}
|
||||
|
||||
Setting struct {
|
||||
pb.SettingModel
|
||||
}
|
||||
|
||||
Activity struct {
|
||||
pb.ActivityModel
|
||||
}
|
||||
)
|
||||
|
||||
func (m *User) GetMenu() *types.Menu {
|
||||
return &types.Menu{
|
||||
Name: "OrganizeUser",
|
||||
Parent: "Organize",
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Login) GetMenu() *types.Menu {
|
||||
return &types.Menu{
|
||||
Name: "OrganizeLogin",
|
||||
Parent: "Organize",
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Login) Scenario() []string {
|
||||
return []string{restTypes.ScenarioList, restTypes.ScenarioExport}
|
||||
}
|
||||
|
||||
func (m *Menu) GetMenu() *types.Menu {
|
||||
return &types.Menu{
|
||||
Name: "OrganizeMenu",
|
||||
Parent: "Organize",
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Menu) BeforeDelete(tx *gorm.DB) (err error) {
|
||||
var count int64
|
||||
if err = tx.Model(&Menu{}).Where("`parent` = ?", m.Name).Count(&count).Error; err != nil {
|
||||
return
|
||||
}
|
||||
if count > 0 {
|
||||
err = errors.New("please delete sub menus first")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (m *Menu) ModelPermissions() map[string]string {
|
||||
return map[string]string{
|
||||
"organize:permission:list": "权限",
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Department) GetMenu() *types.Menu {
|
||||
return &types.Menu{
|
||||
Name: "OrganizeDepartment",
|
||||
Parent: "Organize",
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Department) BeforeDelete(tx *gorm.DB) (err error) {
|
||||
var count int64
|
||||
if err = tx.Model(&Department{}).Where("`parent_id` = ?", m.Id).Count(&count).Error; err != nil {
|
||||
return
|
||||
}
|
||||
if count > 0 {
|
||||
return errors.New("please delete sub department first")
|
||||
}
|
||||
if err = tx.Model(&User{}).Where("`dept_id` = ?", m.Id).Count(&count).Error; err != nil {
|
||||
return
|
||||
}
|
||||
if count > 0 {
|
||||
err = errors.New("please delete user first")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (m *Role) GetMenu() *types.Menu {
|
||||
return &types.Menu{
|
||||
Name: "OrganizeRole",
|
||||
Parent: "Organize",
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Role) ModelPermissions() map[string]string {
|
||||
return map[string]string{
|
||||
"organize:role_permission:list": "权限",
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Role) BeforeDelete(tx *gorm.DB) (err error) {
|
||||
var count int64
|
||||
if err = tx.Model(&User{}).Where("`role` = ?", m.Name).Count(&count).Error; err != nil {
|
||||
return
|
||||
}
|
||||
if count > 0 {
|
||||
err = errors.New("please delete user first")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (m *Permission) GetMenu() *types.Menu {
|
||||
return &types.Menu{
|
||||
Name: "OrganizePermission",
|
||||
Parent: "Organize",
|
||||
Hidden: true,
|
||||
Uri: "/organize/menu/permission/:id",
|
||||
ViewPath: "../views/organize/menu/Permission.vue",
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Permission) GetPermission(s string) string {
|
||||
return "organize:permission:list"
|
||||
}
|
||||
|
||||
func (m *RolePermission) GetMenu() *types.Menu {
|
||||
return &types.Menu{
|
||||
Name: "OrganizeRolePermission",
|
||||
Parent: "Organize",
|
||||
Hidden: true,
|
||||
Uri: "/organize/role/permission/:id",
|
||||
ViewPath: "../views/organize/role/Permission.vue",
|
||||
}
|
||||
}
|
||||
|
||||
func (m *RolePermission) GetPermission(s string) string {
|
||||
return "organize:role_permission:list"
|
||||
}
|
||||
|
||||
func (m *Setting) GetMenu() *types.Menu {
|
||||
return &types.Menu{
|
||||
Name: "SystemSetting",
|
||||
Parent: "System",
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Setting) ModuleName() string {
|
||||
return "system"
|
||||
}
|
||||
|
||||
func (m *Activity) GetMenu() *types.Menu {
|
||||
return &types.Menu{
|
||||
Name: "SystemActivity",
|
||||
Parent: "System",
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Activity) Scenario() []string {
|
||||
return []string{restTypes.ScenarioList, restTypes.ScenarioExport}
|
||||
}
|
||||
|
||||
func (m *Activity) ModuleName() string {
|
||||
return "system"
|
||||
}
|
||||
|
||||
func (m *Activity) GetPermission(s string) string {
|
||||
return "system:activity:list"
|
||||
}
|
||||
|
|
2141
pb/organize.pb.go
2141
pb/organize.pb.go
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
|
@ -14,15 +14,19 @@ message Menu {
|
|||
option (aeus.rest) = {
|
||||
table: "menus"
|
||||
};
|
||||
int64 id = 1 [(aeus.field) = {gorm:"primaryKey"}];
|
||||
int64 parent_id = 2;
|
||||
string name = 3 [(aeus.field)={gorm:"index;size:60"},(validate.rules).string = {max_len: 60}];
|
||||
string label = 4 [(aeus.field)={gorm:"size:120"},(validate.rules).string = {max_len: 120}];
|
||||
string uri = 5 [(aeus.field)={gorm:"size:512"},(validate.rules).string = {max_len: 512}];
|
||||
string view_path = 6 [(aeus.field)={gorm:"size:512"},(validate.rules).string = {max_len: 512}];
|
||||
string icon = 7 [(aeus.field)={gorm:"size:60"},(validate.rules).string = {max_len: 60}];
|
||||
bool hidden = 8;
|
||||
bool public = 9;
|
||||
int64 id = 1 [(aeus.field) = {gorm:"primaryKey",comment:"菜单ID"}];
|
||||
int64 created_at = 2 [(aeus.field)={scenarios:"view;export",comment:"创建时间"}];
|
||||
int64 updated_at = 3 [(aeus.field)={gorm:"index",scenarios:"view;export",comment:"更新时间"}];
|
||||
string parent = 4 [(aeus.field)={gorm:"index;size:60",scenarios:"create;update;view;export",props:"readonly:update",live:"type:dropdown;url:/menu/level-labels",format:"menu",comment:"父级菜单"}];
|
||||
string name = 5 [(aeus.field)={gorm:"index;size:60",props:"readonly:update",rule:"unique;required",comment: "组件名称"},(validate.rules).string = {max_len: 60}];
|
||||
string label = 6 [(aeus.field)={gorm:"size:120",rule:"required",comment: "菜单标题"},(validate.rules).string = {max_len: 120}];
|
||||
string uri = 7 [(aeus.field)={gorm:"size:512",rule:"required",scenarios:"create;update;view;export",comment: "菜单链接"},(validate.rules).string = {max_len: 512}];
|
||||
string view_path = 8 [(aeus.field)={gorm:"size:512",scenarios:"create;update;view;export",comment: "视图路径"},(validate.rules).string = {max_len: 512}];
|
||||
string icon = 9 [(aeus.field)={gorm:"size:60",scenarios:"create;update;view;export",comment: "菜单图标"},(validate.rules).string = {max_len: 60}];
|
||||
bool hidden = 10 [(aeus.field)={scenarios:"create;update;view;export",comment:"是否隐藏"}];
|
||||
bool public = 11 [(aeus.field)={scenarios:"create;update;view;export",comment:"是否公开"}];
|
||||
string description = 12 [(aeus.field)={gorm:"size:1024",scenarios:"create;update;view;export",format:"textarea",comment: "备注说明"},(validate.rules).string = {max_len: 1024}];
|
||||
int64 position = 13 [(aeus.field)={comment:"排序",scenarios:"create;update"}];
|
||||
}
|
||||
|
||||
// Role 角色模型定义
|
||||
|
@ -30,10 +34,12 @@ message Role {
|
|||
option (aeus.rest) = {
|
||||
table: "roles"
|
||||
};
|
||||
int64 id = 1 [(aeus.field) = {gorm:"primaryKey"}];
|
||||
string name = 2 [(aeus.field)={gorm:"index;size:60"},(validate.rules).string = {max_len: 60}];
|
||||
string label = 3 [(aeus.field)={gorm:"size:60"},(validate.rules).string = {max_len: 60}];
|
||||
string description = 4 [(aeus.field)={gorm:"size:1024"},(validate.rules).string = {max_len: 1024}];
|
||||
int64 id = 1 [(aeus.field) = {gorm:"primaryKey",comment: "角色ID"}];
|
||||
int64 created_at = 2 [(aeus.field)={scenarios:"view;export",comment:"创建时间"}];
|
||||
int64 updated_at = 3 [(aeus.field)={gorm:"index",scenarios:"view;export",comment:"更新时间"}];
|
||||
string name = 4 [(aeus.field)={gorm:"index;size:60",rule:"required",props:"readonly:update",comment: "角色名称"},(validate.rules).string = {max_len: 60}];
|
||||
string label = 5 [(aeus.field)={gorm:"size:60",rule:"required",comment: "角色标题"},(validate.rules).string = {max_len: 60}];
|
||||
string description = 6 [(aeus.field)={gorm:"size:1024",scenarios:"list;create;update;export",format:"textarea",comment: "备注说明"},(validate.rules).string = {max_len: 1024}];
|
||||
}
|
||||
|
||||
// Permission 权限模型定义
|
||||
|
@ -41,10 +47,12 @@ message Permission {
|
|||
option (aeus.rest) = {
|
||||
table: "permissions"
|
||||
};
|
||||
int64 id = 1 [(aeus.field) = {gorm:"primaryKey"}];
|
||||
int64 menu_id = 2 [(aeus.field)={gorm:"index"}];
|
||||
string permission = 3 [(aeus.field)={gorm:"index;size:60"},(validate.rules).string = {max_len: 60}];
|
||||
string label = 4 [(aeus.field)={gorm:"size:60"},(validate.rules).string = {max_len: 60}];
|
||||
int64 id = 1 [(aeus.field) = {gorm:"primaryKey",comment: "权限ID"}];
|
||||
int64 created_at = 2 [(aeus.field)={scenarios:"view;export",comment:"创建时间"}];
|
||||
int64 updated_at = 3 [(aeus.field)={gorm:"index",scenarios:"view;export",comment:"更新时间"}];
|
||||
string menu = 4 [(aeus.field)={gorm:"index;size:60",format:"menu",rule:"required",comment: "所属菜单"}];
|
||||
string permission = 5 [(aeus.field)={gorm:"index;size:60",rule:"required",comment: "权限名称"},(validate.rules).string = {max_len: 60}];
|
||||
string label = 6 [(aeus.field)={gorm:"size:60",rule:"required",comment: "权限标题"},(validate.rules).string = {max_len: 60}];
|
||||
}
|
||||
|
||||
// RolePermission 角色权限关联表
|
||||
|
@ -52,9 +60,9 @@ message RolePermission {
|
|||
option (aeus.rest) = {
|
||||
table: "role_permissions"
|
||||
};
|
||||
int64 id = 1 [(aeus.field) = {gorm:"primaryKey"}];
|
||||
string role = 2 [(aeus.field)={gorm:"size:60"},(validate.rules).string = {max_len: 60}];
|
||||
int64 permission_id = 3;
|
||||
int64 id = 1 [(aeus.field) = {gorm:"primaryKey",comment: "ID"}];
|
||||
string role = 2 [(aeus.field)={gorm:"index;size:60",rule:"required",comment: "角色"},(validate.rules).string = {max_len: 60}];
|
||||
string permission = 3 [(aeus.field)={gorm:"size:60",rule:"required",comment: "权限"}];
|
||||
}
|
||||
|
||||
// User 用户模型定义
|
||||
|
@ -62,20 +70,21 @@ message User {
|
|||
option (aeus.rest) = {
|
||||
table: "users"
|
||||
};
|
||||
int64 id = 1 [(aeus.field) = {gorm:"primaryKey"}];
|
||||
int64 created_at = 2;
|
||||
int64 updated_at = 3;
|
||||
string uid = 4 [(aeus.field) = {gorm:"index;size:20"},(validate.rules).string = {min_len: 5, max_len: 20}];
|
||||
string username = 5 [(aeus.field)={gorm:"size:20"},(validate.rules).string = {min_len: 5, max_len: 20}];
|
||||
string role = 6 [(aeus.field)={gorm:"size:60"},(validate.rules).string = {max_len: 60}];
|
||||
bool admin = 7;
|
||||
int64 dept_id = 8 [(aeus.field) = {gorm:"not null;default:0"}];
|
||||
string tag = 9 [ (aeus.field)={gorm:"size:60"},(validate.rules).string = {max_len: 60}];
|
||||
string password = 10 [(aeus.field)={gorm:"size:60"},(validate.rules).string = {max_len: 60}];
|
||||
string email = 11 [(aeus.field)={gorm:"size:60"},(validate.rules).string = {max_len: 60}];
|
||||
string avatar = 12 [(aeus.field)={gorm:"size:1024"},(validate.rules).string = {max_len: 1024}];
|
||||
string gender = 13 [(aeus.field)={gorm:"size:20;default:man"},(validate.rules).string = {max_len: 20}];
|
||||
string description = 14 [(aeus.field)={gorm:"size:1024"},(validate.rules).string = {max_len: 1024}];
|
||||
int64 id = 1 [(aeus.field) = {gorm:"primaryKey",comment: "ID"}];
|
||||
int64 created_at = 2 [(aeus.field)={scenarios:"view;export",comment:"创建时间"}];
|
||||
int64 updated_at = 3 [(aeus.field)={gorm:"index",scenarios:"view;export",comment:"更新时间"}];
|
||||
string uid = 4 [(aeus.field) = {gorm:"index;size:20",rule:"required;unique;regexp:^[a-zA-Z0-9]{3,8}$",props:"readonly:update",comment: "用户工号"},(validate.rules).string = {min_len: 5, max_len: 20}];
|
||||
string username = 5 [(aeus.field)={gorm:"size:20",rule:"required",comment: "用户名称"},(validate.rules).string = {min_len: 5, max_len: 20}];
|
||||
string role = 6 [(aeus.field)={gorm:"size:60;not null;default:''",rule:"required",format:"role",live:"type:dropdown;url:/role/labels",comment: "所属角色"},(validate.rules).string = {max_len: 60}];
|
||||
bool admin = 7 [(aeus.field)={scenarios:"create",comment:"管理员"}];
|
||||
string status = 8 [(aeus.field)={scenarios:"create,update,list,search",gorm:"size:20;default:normal",enum:"normal:正常;disable:禁用",comment:"状态"}];
|
||||
int64 dept_id = 9 [(aeus.field) = {gorm:"not null;default:0",rule:"required",live:"type:dropdown;url:/department/labels",format:"department",comment: "所属部门"}];
|
||||
string tag = 10 [ (aeus.field)={gorm:"size:60",scenarios:"list;create;update",dropdown:"created;filterable;default_first",live:"type:dropdown;url:/user/tags",comment: "用户标签"},(validate.rules).string = {max_len: 60}];
|
||||
string password = 11 [(aeus.field)={gorm:"size:60",rule:"required",scenarios:"create",comment: "用户密码"},(validate.rules).string = {max_len: 60}];
|
||||
string email = 12 [(aeus.field)={gorm:"size:60",scenarios:"create;update;view;list;export",comment: "用户邮箱"},(validate.rules).string = {max_len: 60}];
|
||||
string avatar = 13 [(aeus.field)={gorm:"size:1024",scenarios:"view",comment: "用户头像"},(validate.rules).string = {max_len: 1024}];
|
||||
string gender = 14 [(aeus.field)={gorm:"size:20;default:man",rule:"required",scenarios:"list;create;update;view;export",enum:"man:男;woman:女;other:其他",comment: "用户性别"},(validate.rules).string = {max_len: 20}];
|
||||
string description = 15 [(aeus.field)={gorm:"size:1024",format:"textarea",scenarios:"create;update;view;export",comment: "备注说明"},(validate.rules).string = {max_len: 1024}];
|
||||
}
|
||||
|
||||
// Department 部门模型定义
|
||||
|
@ -83,14 +92,33 @@ message Department {
|
|||
option (aeus.rest) = {
|
||||
table: "departments"
|
||||
};
|
||||
int64 id = 1 [(aeus.field) = {gorm:"primaryKey"}];
|
||||
int64 created_at = 2;
|
||||
int64 updated_at = 3;
|
||||
int64 parent_id = 4;
|
||||
string name = 5 [(aeus.field)={gorm:"size:20"},(validate.rules).string = {max_len: 20}];
|
||||
string description = 6 [(aeus.field)={gorm:"size:1024"},(validate.rules).string = {max_len: 1024}];
|
||||
int64 id = 1 [(aeus.field) = {gorm:"primaryKey",comment:"ID"}];
|
||||
int64 created_at = 2 [(aeus.field)={scenarios:"view;export",comment:"创建时间"}];
|
||||
int64 updated_at = 3 [(aeus.field)={gorm:"index",scenarios:"view;export",comment:"更新时间"}];
|
||||
int64 parent_id = 4 [(aeus.field)={live:"type:dropdown;url:/department/level-labels",format:"department",comment:"父级部门"}];
|
||||
string name = 5 [(aeus.field)={gorm:"size:20",rule:"required",comment: "部门名称"},(validate.rules).string = {max_len: 20}];
|
||||
string description = 6 [(aeus.field)={gorm:"size:1024",scenarios:"create;update;view;export;list",format:"textarea",comment: "备注说明"},(validate.rules).string = {max_len: 1024}];
|
||||
}
|
||||
|
||||
message Login {
|
||||
option (aeus.rest) = {
|
||||
table: "logins"
|
||||
};
|
||||
int64 id = 1 [(aeus.field) = {gorm:"primaryKey",comment:"ID"}];
|
||||
int64 created_at = 2 [(aeus.field)={scenarios:"list;search;view;export",comment:"登录时间"}];
|
||||
string uid = 4 [(aeus.field)={gorm:"index;size:20",rule:"required",props:"readonly:update",format:"user",comment: "用户"},(validate.rules).string = {min_len: 5, max_len: 20}];
|
||||
string ip = 5 [(aeus.field)={gorm:"size:128",scenarios:"list;search;view;export",comment: "登录地址"}];
|
||||
string browser = 6 [(aeus.field)={gorm:"size:128",scenarios:"list;view;export",comment: "浏览器"}];
|
||||
string os = 7 [(aeus.field)={gorm:"size:128",scenarios:"list;view;export",comment: "操作系统"}];
|
||||
string platform = 8 [(aeus.field)={gorm:"size:128",scenarios:"list;view;export",comment: "系统平台"}];
|
||||
string access_token = 9 [(aeus.field)={gorm:"size:1024",scenarios:"list;view;export",comment: "访问令牌"}];
|
||||
string user_agent = 10 [(aeus.field)={gorm:"size:1024",scenarios:"list;view;export",comment: "用户代理"}];
|
||||
}
|
||||
|
||||
message LabelValue {
|
||||
string label = 1;
|
||||
string value = 2;
|
||||
}
|
||||
|
||||
message PermissionItem {
|
||||
string value = 1;
|
||||
|
@ -105,29 +133,21 @@ message MenuItem {
|
|||
bool hidden = 4;
|
||||
bool public = 5;
|
||||
string route = 6;
|
||||
repeated PermissionItem permissions = 7;
|
||||
repeated MenuItem children = 8;
|
||||
string view = 7;
|
||||
repeated PermissionItem permissions = 8;
|
||||
repeated MenuItem children = 9;
|
||||
}
|
||||
|
||||
// 获取菜单的请求
|
||||
message GetMenuRequest {
|
||||
message GetUserMenuRequest {
|
||||
bool permission = 1;
|
||||
}
|
||||
|
||||
// 获取菜单的响应
|
||||
message GetMenuResponse {
|
||||
message GetUserMenuResponse {
|
||||
repeated MenuItem data = 1;
|
||||
}
|
||||
|
||||
// 菜单服务
|
||||
service MenuService {
|
||||
rpc GetMenus(GetMenuRequest) returns (GetMenuResponse) {
|
||||
option (google.api.http) = {
|
||||
get: "/api/menu"
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 获取用户信息
|
||||
message GetProfileRequest {
|
||||
|
@ -167,25 +187,223 @@ message UpdateProfileResponse {
|
|||
string uid = 1;
|
||||
}
|
||||
|
||||
message GetPermissionRequest {
|
||||
string uid = 1;
|
||||
}
|
||||
|
||||
message GetPermissionResponse {
|
||||
string uid = 1;
|
||||
repeated string permissions = 2;
|
||||
}
|
||||
|
||||
message GetUserLabelRequest {
|
||||
}
|
||||
|
||||
message GetUserLabelResponse {
|
||||
repeated LabelValue data = 1;
|
||||
}
|
||||
|
||||
message GetUserTagRequest {
|
||||
}
|
||||
|
||||
message GetUserTagResponse {
|
||||
repeated LabelValue data = 1;
|
||||
}
|
||||
|
||||
// 用户服务
|
||||
service ProfileService {
|
||||
service UserService {
|
||||
// 获取用户菜单
|
||||
rpc GetMenus(GetUserMenuRequest) returns (GetUserMenuResponse) {
|
||||
option (google.api.http) = {
|
||||
get: "/user/menus"
|
||||
};
|
||||
}
|
||||
// 获取用户信息
|
||||
rpc GetProfile(GetProfileRequest) returns (GetProfileResponse) {
|
||||
option (google.api.http) = {
|
||||
get: "/user/profile"
|
||||
};
|
||||
}
|
||||
// 更新用户信息
|
||||
rpc UpdateProfile(UpdateProfileRequest) returns (UpdateProfileResponse) {
|
||||
option (google.api.http) = {
|
||||
put: "/user/profile"
|
||||
body: "*"
|
||||
};
|
||||
}
|
||||
// 重置用户密码
|
||||
rpc ResetPassword(ResetPasswordRequest) returns (ResetPasswordResponse) {
|
||||
option (google.api.http) = {
|
||||
post: "/user/reset-password"
|
||||
body: "*"
|
||||
};
|
||||
}
|
||||
// 获取用户权限
|
||||
rpc GetPermissions(GetPermissionRequest) returns (GetPermissionResponse) {
|
||||
option (google.api.http) = {
|
||||
get: "/user/permissions"
|
||||
};
|
||||
}
|
||||
// 获取用户标签
|
||||
rpc GetUserLabels(GetUserLabelRequest) returns (GetUserLabelResponse) {
|
||||
option (google.api.http) = {
|
||||
get: "/user/labels"
|
||||
};
|
||||
}
|
||||
// 获取用户标签
|
||||
rpc GetUserTags(GetUserTagRequest) returns (GetUserTagResponse) {
|
||||
option (google.api.http) = {
|
||||
get: "/user/tags"
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
message DepartmentLabelValue {
|
||||
string label = 1;
|
||||
int64 value = 2;
|
||||
}
|
||||
|
||||
message DepartmentUserValue {
|
||||
string label = 1;
|
||||
string value = 2;
|
||||
bool isuser = 3;
|
||||
repeated DepartmentUserValue children = 4;
|
||||
}
|
||||
|
||||
message GetDepartmentLabelRequest {
|
||||
}
|
||||
|
||||
message GetDepartmentLabelResponse {
|
||||
repeated DepartmentLabelValue data = 1;
|
||||
}
|
||||
|
||||
message GetDepartmentUserRequest {
|
||||
}
|
||||
|
||||
message GetDepartmentUserResponse {
|
||||
repeated DepartmentUserValue data = 1;
|
||||
}
|
||||
|
||||
message DepartmentLevelValue {
|
||||
string label = 1;
|
||||
int64 value = 2;
|
||||
repeated DepartmentLevelValue children = 4;
|
||||
}
|
||||
|
||||
message GetDepartmentLevelLabelsRequest {
|
||||
}
|
||||
|
||||
message GetDepartmentLevelLabelsResponse {
|
||||
repeated DepartmentLevelValue data = 1;
|
||||
}
|
||||
|
||||
service DepartmentService {
|
||||
// 获取部门标签
|
||||
rpc GetDepartmentLabels(GetDepartmentLabelRequest) returns (GetDepartmentLabelResponse) {
|
||||
option (google.api.http) = {
|
||||
get: "/department/labels"
|
||||
};
|
||||
}
|
||||
rpc GetDepartmentUsers(GetDepartmentUserRequest) returns (GetDepartmentUserResponse) {
|
||||
option (google.api.http) = {
|
||||
get: "/department/users"
|
||||
};
|
||||
}
|
||||
rpc GetDepartmentLevelLabels(GetDepartmentLevelLabelsRequest) returns (GetDepartmentLevelLabelsResponse) {
|
||||
option (google.api.http) = {
|
||||
get: "/department/level-labels"
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
message GetRoleLabelRequest {
|
||||
}
|
||||
|
||||
message GetRoleLabelResponse {
|
||||
repeated LabelValue data = 1;
|
||||
}
|
||||
|
||||
message GetRolePermissionRequest {
|
||||
string role = 1;
|
||||
}
|
||||
|
||||
message GetRolePermissionResponse {
|
||||
string role = 1;
|
||||
repeated string permissions = 2;
|
||||
}
|
||||
|
||||
message SaveRolePermissionRequest {
|
||||
string role = 1;
|
||||
repeated string permissions = 2;
|
||||
}
|
||||
|
||||
message SaveRolePermissionResponse {
|
||||
string role = 1;
|
||||
}
|
||||
|
||||
service RoleService {
|
||||
// 获取角色标签
|
||||
rpc GetRoleLabels(GetRoleLabelRequest) returns (GetRoleLabelResponse) {
|
||||
option (google.api.http) = {
|
||||
get: "/role/labels"
|
||||
};
|
||||
}
|
||||
// 获取角色权限
|
||||
rpc GetRolePermissions(GetRolePermissionRequest) returns (GetRolePermissionResponse) {
|
||||
option (google.api.http) = {
|
||||
get: "/role/permissions"
|
||||
};
|
||||
}
|
||||
|
||||
rpc SaveRolePermission(SaveRolePermissionRequest) returns (SaveRolePermissionResponse) {
|
||||
option (google.api.http) = {
|
||||
post: "/role/permissions"
|
||||
body: "*"
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
message MenuLevelValue {
|
||||
string label = 1;
|
||||
string value = 2;
|
||||
repeated MenuLevelValue children = 4;
|
||||
}
|
||||
|
||||
message GetMenuLevelLabelsRequest {
|
||||
}
|
||||
|
||||
message GetMenuLevelLabelsResponse {
|
||||
repeated MenuLevelValue data = 1;
|
||||
}
|
||||
|
||||
message MenuValue {
|
||||
int64 id = 1;
|
||||
string parent = 2;
|
||||
string name = 3;
|
||||
string label = 4;
|
||||
repeated MenuValue children = 5;
|
||||
}
|
||||
|
||||
message GetMenuRequest{
|
||||
|
||||
}
|
||||
|
||||
message GetMenuResponse{
|
||||
repeated MenuValue data = 1;
|
||||
}
|
||||
|
||||
service MenuService {
|
||||
rpc GetMenus(GetMenuRequest) returns (GetMenuResponse) {
|
||||
option (google.api.http) = {
|
||||
get: "/menu/list"
|
||||
};
|
||||
}
|
||||
rpc GetMenuLevelLabels(GetMenuLevelLabelsRequest) returns (GetMenuLevelLabelsResponse) {
|
||||
option (google.api.http) = {
|
||||
get: "/menu/level-labels"
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
@ -224,4 +442,4 @@ service AuthService {
|
|||
body: "*"
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -19,16 +19,726 @@ import (
|
|||
const _ = grpc.SupportPackageIsVersion9
|
||||
|
||||
const (
|
||||
MenuService_GetMenus_FullMethodName = "/organize.MenuService/GetMenus"
|
||||
UserService_GetMenus_FullMethodName = "/organize.UserService/GetMenus"
|
||||
UserService_GetProfile_FullMethodName = "/organize.UserService/GetProfile"
|
||||
UserService_UpdateProfile_FullMethodName = "/organize.UserService/UpdateProfile"
|
||||
UserService_ResetPassword_FullMethodName = "/organize.UserService/ResetPassword"
|
||||
UserService_GetPermissions_FullMethodName = "/organize.UserService/GetPermissions"
|
||||
UserService_GetUserLabels_FullMethodName = "/organize.UserService/GetUserLabels"
|
||||
UserService_GetUserTags_FullMethodName = "/organize.UserService/GetUserTags"
|
||||
)
|
||||
|
||||
// UserServiceClient is the client API for UserService service.
|
||||
//
|
||||
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
|
||||
//
|
||||
// 用户服务
|
||||
type UserServiceClient interface {
|
||||
// 获取用户菜单
|
||||
GetMenus(ctx context.Context, in *GetUserMenuRequest, opts ...grpc.CallOption) (*GetUserMenuResponse, error)
|
||||
// 获取用户信息
|
||||
GetProfile(ctx context.Context, in *GetProfileRequest, opts ...grpc.CallOption) (*GetProfileResponse, error)
|
||||
// 更新用户信息
|
||||
UpdateProfile(ctx context.Context, in *UpdateProfileRequest, opts ...grpc.CallOption) (*UpdateProfileResponse, error)
|
||||
// 重置用户密码
|
||||
ResetPassword(ctx context.Context, in *ResetPasswordRequest, opts ...grpc.CallOption) (*ResetPasswordResponse, error)
|
||||
// 获取用户权限
|
||||
GetPermissions(ctx context.Context, in *GetPermissionRequest, opts ...grpc.CallOption) (*GetPermissionResponse, error)
|
||||
// 获取用户标签
|
||||
GetUserLabels(ctx context.Context, in *GetUserLabelRequest, opts ...grpc.CallOption) (*GetUserLabelResponse, error)
|
||||
// 获取用户标签
|
||||
GetUserTags(ctx context.Context, in *GetUserTagRequest, opts ...grpc.CallOption) (*GetUserTagResponse, error)
|
||||
}
|
||||
|
||||
type userServiceClient struct {
|
||||
cc grpc.ClientConnInterface
|
||||
}
|
||||
|
||||
func NewUserServiceClient(cc grpc.ClientConnInterface) UserServiceClient {
|
||||
return &userServiceClient{cc}
|
||||
}
|
||||
|
||||
func (c *userServiceClient) GetMenus(ctx context.Context, in *GetUserMenuRequest, opts ...grpc.CallOption) (*GetUserMenuResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(GetUserMenuResponse)
|
||||
err := c.cc.Invoke(ctx, UserService_GetMenus_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *userServiceClient) GetProfile(ctx context.Context, in *GetProfileRequest, opts ...grpc.CallOption) (*GetProfileResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(GetProfileResponse)
|
||||
err := c.cc.Invoke(ctx, UserService_GetProfile_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *userServiceClient) UpdateProfile(ctx context.Context, in *UpdateProfileRequest, opts ...grpc.CallOption) (*UpdateProfileResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(UpdateProfileResponse)
|
||||
err := c.cc.Invoke(ctx, UserService_UpdateProfile_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *userServiceClient) ResetPassword(ctx context.Context, in *ResetPasswordRequest, opts ...grpc.CallOption) (*ResetPasswordResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(ResetPasswordResponse)
|
||||
err := c.cc.Invoke(ctx, UserService_ResetPassword_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *userServiceClient) GetPermissions(ctx context.Context, in *GetPermissionRequest, opts ...grpc.CallOption) (*GetPermissionResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(GetPermissionResponse)
|
||||
err := c.cc.Invoke(ctx, UserService_GetPermissions_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *userServiceClient) GetUserLabels(ctx context.Context, in *GetUserLabelRequest, opts ...grpc.CallOption) (*GetUserLabelResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(GetUserLabelResponse)
|
||||
err := c.cc.Invoke(ctx, UserService_GetUserLabels_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *userServiceClient) GetUserTags(ctx context.Context, in *GetUserTagRequest, opts ...grpc.CallOption) (*GetUserTagResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(GetUserTagResponse)
|
||||
err := c.cc.Invoke(ctx, UserService_GetUserTags_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// UserServiceServer is the server API for UserService service.
|
||||
// All implementations must embed UnimplementedUserServiceServer
|
||||
// for forward compatibility.
|
||||
//
|
||||
// 用户服务
|
||||
type UserServiceServer interface {
|
||||
// 获取用户菜单
|
||||
GetMenus(context.Context, *GetUserMenuRequest) (*GetUserMenuResponse, error)
|
||||
// 获取用户信息
|
||||
GetProfile(context.Context, *GetProfileRequest) (*GetProfileResponse, error)
|
||||
// 更新用户信息
|
||||
UpdateProfile(context.Context, *UpdateProfileRequest) (*UpdateProfileResponse, error)
|
||||
// 重置用户密码
|
||||
ResetPassword(context.Context, *ResetPasswordRequest) (*ResetPasswordResponse, error)
|
||||
// 获取用户权限
|
||||
GetPermissions(context.Context, *GetPermissionRequest) (*GetPermissionResponse, error)
|
||||
// 获取用户标签
|
||||
GetUserLabels(context.Context, *GetUserLabelRequest) (*GetUserLabelResponse, error)
|
||||
// 获取用户标签
|
||||
GetUserTags(context.Context, *GetUserTagRequest) (*GetUserTagResponse, error)
|
||||
mustEmbedUnimplementedUserServiceServer()
|
||||
}
|
||||
|
||||
// UnimplementedUserServiceServer must be embedded to have
|
||||
// forward compatible implementations.
|
||||
//
|
||||
// NOTE: this should be embedded by value instead of pointer to avoid a nil
|
||||
// pointer dereference when methods are called.
|
||||
type UnimplementedUserServiceServer struct{}
|
||||
|
||||
func (UnimplementedUserServiceServer) GetMenus(context.Context, *GetUserMenuRequest) (*GetUserMenuResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method GetMenus not implemented")
|
||||
}
|
||||
func (UnimplementedUserServiceServer) GetProfile(context.Context, *GetProfileRequest) (*GetProfileResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method GetProfile not implemented")
|
||||
}
|
||||
func (UnimplementedUserServiceServer) UpdateProfile(context.Context, *UpdateProfileRequest) (*UpdateProfileResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method UpdateProfile not implemented")
|
||||
}
|
||||
func (UnimplementedUserServiceServer) ResetPassword(context.Context, *ResetPasswordRequest) (*ResetPasswordResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method ResetPassword not implemented")
|
||||
}
|
||||
func (UnimplementedUserServiceServer) GetPermissions(context.Context, *GetPermissionRequest) (*GetPermissionResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method GetPermissions not implemented")
|
||||
}
|
||||
func (UnimplementedUserServiceServer) GetUserLabels(context.Context, *GetUserLabelRequest) (*GetUserLabelResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method GetUserLabels not implemented")
|
||||
}
|
||||
func (UnimplementedUserServiceServer) GetUserTags(context.Context, *GetUserTagRequest) (*GetUserTagResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method GetUserTags not implemented")
|
||||
}
|
||||
func (UnimplementedUserServiceServer) mustEmbedUnimplementedUserServiceServer() {}
|
||||
func (UnimplementedUserServiceServer) testEmbeddedByValue() {}
|
||||
|
||||
// UnsafeUserServiceServer may be embedded to opt out of forward compatibility for this service.
|
||||
// Use of this interface is not recommended, as added methods to UserServiceServer will
|
||||
// result in compilation errors.
|
||||
type UnsafeUserServiceServer interface {
|
||||
mustEmbedUnimplementedUserServiceServer()
|
||||
}
|
||||
|
||||
func RegisterUserServiceServer(s grpc.ServiceRegistrar, srv UserServiceServer) {
|
||||
// If the following call pancis, it indicates UnimplementedUserServiceServer was
|
||||
// embedded by pointer and is nil. This will cause panics if an
|
||||
// unimplemented method is ever invoked, so we test this at initialization
|
||||
// time to prevent it from happening at runtime later due to I/O.
|
||||
if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {
|
||||
t.testEmbeddedByValue()
|
||||
}
|
||||
s.RegisterService(&UserService_ServiceDesc, srv)
|
||||
}
|
||||
|
||||
func _UserService_GetMenus_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(GetUserMenuRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(UserServiceServer).GetMenus(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: UserService_GetMenus_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(UserServiceServer).GetMenus(ctx, req.(*GetUserMenuRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _UserService_GetProfile_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(GetProfileRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(UserServiceServer).GetProfile(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: UserService_GetProfile_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(UserServiceServer).GetProfile(ctx, req.(*GetProfileRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _UserService_UpdateProfile_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(UpdateProfileRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(UserServiceServer).UpdateProfile(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: UserService_UpdateProfile_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(UserServiceServer).UpdateProfile(ctx, req.(*UpdateProfileRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _UserService_ResetPassword_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(ResetPasswordRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(UserServiceServer).ResetPassword(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: UserService_ResetPassword_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(UserServiceServer).ResetPassword(ctx, req.(*ResetPasswordRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _UserService_GetPermissions_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(GetPermissionRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(UserServiceServer).GetPermissions(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: UserService_GetPermissions_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(UserServiceServer).GetPermissions(ctx, req.(*GetPermissionRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _UserService_GetUserLabels_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(GetUserLabelRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(UserServiceServer).GetUserLabels(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: UserService_GetUserLabels_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(UserServiceServer).GetUserLabels(ctx, req.(*GetUserLabelRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _UserService_GetUserTags_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(GetUserTagRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(UserServiceServer).GetUserTags(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: UserService_GetUserTags_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(UserServiceServer).GetUserTags(ctx, req.(*GetUserTagRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
// UserService_ServiceDesc is the grpc.ServiceDesc for UserService service.
|
||||
// It's only intended for direct use with grpc.RegisterService,
|
||||
// and not to be introspected or modified (even as a copy)
|
||||
var UserService_ServiceDesc = grpc.ServiceDesc{
|
||||
ServiceName: "organize.UserService",
|
||||
HandlerType: (*UserServiceServer)(nil),
|
||||
Methods: []grpc.MethodDesc{
|
||||
{
|
||||
MethodName: "GetMenus",
|
||||
Handler: _UserService_GetMenus_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "GetProfile",
|
||||
Handler: _UserService_GetProfile_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "UpdateProfile",
|
||||
Handler: _UserService_UpdateProfile_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "ResetPassword",
|
||||
Handler: _UserService_ResetPassword_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "GetPermissions",
|
||||
Handler: _UserService_GetPermissions_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "GetUserLabels",
|
||||
Handler: _UserService_GetUserLabels_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "GetUserTags",
|
||||
Handler: _UserService_GetUserTags_Handler,
|
||||
},
|
||||
},
|
||||
Streams: []grpc.StreamDesc{},
|
||||
Metadata: "organize.proto",
|
||||
}
|
||||
|
||||
const (
|
||||
DepartmentService_GetDepartmentLabels_FullMethodName = "/organize.DepartmentService/GetDepartmentLabels"
|
||||
DepartmentService_GetDepartmentUsers_FullMethodName = "/organize.DepartmentService/GetDepartmentUsers"
|
||||
DepartmentService_GetDepartmentLevelLabels_FullMethodName = "/organize.DepartmentService/GetDepartmentLevelLabels"
|
||||
)
|
||||
|
||||
// DepartmentServiceClient is the client API for DepartmentService service.
|
||||
//
|
||||
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
|
||||
type DepartmentServiceClient interface {
|
||||
// 获取部门标签
|
||||
GetDepartmentLabels(ctx context.Context, in *GetDepartmentLabelRequest, opts ...grpc.CallOption) (*GetDepartmentLabelResponse, error)
|
||||
GetDepartmentUsers(ctx context.Context, in *GetDepartmentUserRequest, opts ...grpc.CallOption) (*GetDepartmentUserResponse, error)
|
||||
GetDepartmentLevelLabels(ctx context.Context, in *GetDepartmentLevelLabelsRequest, opts ...grpc.CallOption) (*GetDepartmentLevelLabelsResponse, error)
|
||||
}
|
||||
|
||||
type departmentServiceClient struct {
|
||||
cc grpc.ClientConnInterface
|
||||
}
|
||||
|
||||
func NewDepartmentServiceClient(cc grpc.ClientConnInterface) DepartmentServiceClient {
|
||||
return &departmentServiceClient{cc}
|
||||
}
|
||||
|
||||
func (c *departmentServiceClient) GetDepartmentLabels(ctx context.Context, in *GetDepartmentLabelRequest, opts ...grpc.CallOption) (*GetDepartmentLabelResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(GetDepartmentLabelResponse)
|
||||
err := c.cc.Invoke(ctx, DepartmentService_GetDepartmentLabels_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *departmentServiceClient) GetDepartmentUsers(ctx context.Context, in *GetDepartmentUserRequest, opts ...grpc.CallOption) (*GetDepartmentUserResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(GetDepartmentUserResponse)
|
||||
err := c.cc.Invoke(ctx, DepartmentService_GetDepartmentUsers_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *departmentServiceClient) GetDepartmentLevelLabels(ctx context.Context, in *GetDepartmentLevelLabelsRequest, opts ...grpc.CallOption) (*GetDepartmentLevelLabelsResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(GetDepartmentLevelLabelsResponse)
|
||||
err := c.cc.Invoke(ctx, DepartmentService_GetDepartmentLevelLabels_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// DepartmentServiceServer is the server API for DepartmentService service.
|
||||
// All implementations must embed UnimplementedDepartmentServiceServer
|
||||
// for forward compatibility.
|
||||
type DepartmentServiceServer interface {
|
||||
// 获取部门标签
|
||||
GetDepartmentLabels(context.Context, *GetDepartmentLabelRequest) (*GetDepartmentLabelResponse, error)
|
||||
GetDepartmentUsers(context.Context, *GetDepartmentUserRequest) (*GetDepartmentUserResponse, error)
|
||||
GetDepartmentLevelLabels(context.Context, *GetDepartmentLevelLabelsRequest) (*GetDepartmentLevelLabelsResponse, error)
|
||||
mustEmbedUnimplementedDepartmentServiceServer()
|
||||
}
|
||||
|
||||
// UnimplementedDepartmentServiceServer must be embedded to have
|
||||
// forward compatible implementations.
|
||||
//
|
||||
// NOTE: this should be embedded by value instead of pointer to avoid a nil
|
||||
// pointer dereference when methods are called.
|
||||
type UnimplementedDepartmentServiceServer struct{}
|
||||
|
||||
func (UnimplementedDepartmentServiceServer) GetDepartmentLabels(context.Context, *GetDepartmentLabelRequest) (*GetDepartmentLabelResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method GetDepartmentLabels not implemented")
|
||||
}
|
||||
func (UnimplementedDepartmentServiceServer) GetDepartmentUsers(context.Context, *GetDepartmentUserRequest) (*GetDepartmentUserResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method GetDepartmentUsers not implemented")
|
||||
}
|
||||
func (UnimplementedDepartmentServiceServer) GetDepartmentLevelLabels(context.Context, *GetDepartmentLevelLabelsRequest) (*GetDepartmentLevelLabelsResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method GetDepartmentLevelLabels not implemented")
|
||||
}
|
||||
func (UnimplementedDepartmentServiceServer) mustEmbedUnimplementedDepartmentServiceServer() {}
|
||||
func (UnimplementedDepartmentServiceServer) testEmbeddedByValue() {}
|
||||
|
||||
// UnsafeDepartmentServiceServer may be embedded to opt out of forward compatibility for this service.
|
||||
// Use of this interface is not recommended, as added methods to DepartmentServiceServer will
|
||||
// result in compilation errors.
|
||||
type UnsafeDepartmentServiceServer interface {
|
||||
mustEmbedUnimplementedDepartmentServiceServer()
|
||||
}
|
||||
|
||||
func RegisterDepartmentServiceServer(s grpc.ServiceRegistrar, srv DepartmentServiceServer) {
|
||||
// If the following call pancis, it indicates UnimplementedDepartmentServiceServer was
|
||||
// embedded by pointer and is nil. This will cause panics if an
|
||||
// unimplemented method is ever invoked, so we test this at initialization
|
||||
// time to prevent it from happening at runtime later due to I/O.
|
||||
if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {
|
||||
t.testEmbeddedByValue()
|
||||
}
|
||||
s.RegisterService(&DepartmentService_ServiceDesc, srv)
|
||||
}
|
||||
|
||||
func _DepartmentService_GetDepartmentLabels_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(GetDepartmentLabelRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(DepartmentServiceServer).GetDepartmentLabels(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: DepartmentService_GetDepartmentLabels_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(DepartmentServiceServer).GetDepartmentLabels(ctx, req.(*GetDepartmentLabelRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _DepartmentService_GetDepartmentUsers_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(GetDepartmentUserRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(DepartmentServiceServer).GetDepartmentUsers(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: DepartmentService_GetDepartmentUsers_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(DepartmentServiceServer).GetDepartmentUsers(ctx, req.(*GetDepartmentUserRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _DepartmentService_GetDepartmentLevelLabels_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(GetDepartmentLevelLabelsRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(DepartmentServiceServer).GetDepartmentLevelLabels(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: DepartmentService_GetDepartmentLevelLabels_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(DepartmentServiceServer).GetDepartmentLevelLabels(ctx, req.(*GetDepartmentLevelLabelsRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
// DepartmentService_ServiceDesc is the grpc.ServiceDesc for DepartmentService service.
|
||||
// It's only intended for direct use with grpc.RegisterService,
|
||||
// and not to be introspected or modified (even as a copy)
|
||||
var DepartmentService_ServiceDesc = grpc.ServiceDesc{
|
||||
ServiceName: "organize.DepartmentService",
|
||||
HandlerType: (*DepartmentServiceServer)(nil),
|
||||
Methods: []grpc.MethodDesc{
|
||||
{
|
||||
MethodName: "GetDepartmentLabels",
|
||||
Handler: _DepartmentService_GetDepartmentLabels_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "GetDepartmentUsers",
|
||||
Handler: _DepartmentService_GetDepartmentUsers_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "GetDepartmentLevelLabels",
|
||||
Handler: _DepartmentService_GetDepartmentLevelLabels_Handler,
|
||||
},
|
||||
},
|
||||
Streams: []grpc.StreamDesc{},
|
||||
Metadata: "organize.proto",
|
||||
}
|
||||
|
||||
const (
|
||||
RoleService_GetRoleLabels_FullMethodName = "/organize.RoleService/GetRoleLabels"
|
||||
RoleService_GetRolePermissions_FullMethodName = "/organize.RoleService/GetRolePermissions"
|
||||
RoleService_SaveRolePermission_FullMethodName = "/organize.RoleService/SaveRolePermission"
|
||||
)
|
||||
|
||||
// RoleServiceClient is the client API for RoleService service.
|
||||
//
|
||||
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
|
||||
type RoleServiceClient interface {
|
||||
// 获取角色标签
|
||||
GetRoleLabels(ctx context.Context, in *GetRoleLabelRequest, opts ...grpc.CallOption) (*GetRoleLabelResponse, error)
|
||||
// 获取角色权限
|
||||
GetRolePermissions(ctx context.Context, in *GetRolePermissionRequest, opts ...grpc.CallOption) (*GetRolePermissionResponse, error)
|
||||
SaveRolePermission(ctx context.Context, in *SaveRolePermissionRequest, opts ...grpc.CallOption) (*SaveRolePermissionResponse, error)
|
||||
}
|
||||
|
||||
type roleServiceClient struct {
|
||||
cc grpc.ClientConnInterface
|
||||
}
|
||||
|
||||
func NewRoleServiceClient(cc grpc.ClientConnInterface) RoleServiceClient {
|
||||
return &roleServiceClient{cc}
|
||||
}
|
||||
|
||||
func (c *roleServiceClient) GetRoleLabels(ctx context.Context, in *GetRoleLabelRequest, opts ...grpc.CallOption) (*GetRoleLabelResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(GetRoleLabelResponse)
|
||||
err := c.cc.Invoke(ctx, RoleService_GetRoleLabels_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *roleServiceClient) GetRolePermissions(ctx context.Context, in *GetRolePermissionRequest, opts ...grpc.CallOption) (*GetRolePermissionResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(GetRolePermissionResponse)
|
||||
err := c.cc.Invoke(ctx, RoleService_GetRolePermissions_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *roleServiceClient) SaveRolePermission(ctx context.Context, in *SaveRolePermissionRequest, opts ...grpc.CallOption) (*SaveRolePermissionResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(SaveRolePermissionResponse)
|
||||
err := c.cc.Invoke(ctx, RoleService_SaveRolePermission_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// RoleServiceServer is the server API for RoleService service.
|
||||
// All implementations must embed UnimplementedRoleServiceServer
|
||||
// for forward compatibility.
|
||||
type RoleServiceServer interface {
|
||||
// 获取角色标签
|
||||
GetRoleLabels(context.Context, *GetRoleLabelRequest) (*GetRoleLabelResponse, error)
|
||||
// 获取角色权限
|
||||
GetRolePermissions(context.Context, *GetRolePermissionRequest) (*GetRolePermissionResponse, error)
|
||||
SaveRolePermission(context.Context, *SaveRolePermissionRequest) (*SaveRolePermissionResponse, error)
|
||||
mustEmbedUnimplementedRoleServiceServer()
|
||||
}
|
||||
|
||||
// UnimplementedRoleServiceServer must be embedded to have
|
||||
// forward compatible implementations.
|
||||
//
|
||||
// NOTE: this should be embedded by value instead of pointer to avoid a nil
|
||||
// pointer dereference when methods are called.
|
||||
type UnimplementedRoleServiceServer struct{}
|
||||
|
||||
func (UnimplementedRoleServiceServer) GetRoleLabels(context.Context, *GetRoleLabelRequest) (*GetRoleLabelResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method GetRoleLabels not implemented")
|
||||
}
|
||||
func (UnimplementedRoleServiceServer) GetRolePermissions(context.Context, *GetRolePermissionRequest) (*GetRolePermissionResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method GetRolePermissions not implemented")
|
||||
}
|
||||
func (UnimplementedRoleServiceServer) SaveRolePermission(context.Context, *SaveRolePermissionRequest) (*SaveRolePermissionResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method SaveRolePermission not implemented")
|
||||
}
|
||||
func (UnimplementedRoleServiceServer) mustEmbedUnimplementedRoleServiceServer() {}
|
||||
func (UnimplementedRoleServiceServer) testEmbeddedByValue() {}
|
||||
|
||||
// UnsafeRoleServiceServer may be embedded to opt out of forward compatibility for this service.
|
||||
// Use of this interface is not recommended, as added methods to RoleServiceServer will
|
||||
// result in compilation errors.
|
||||
type UnsafeRoleServiceServer interface {
|
||||
mustEmbedUnimplementedRoleServiceServer()
|
||||
}
|
||||
|
||||
func RegisterRoleServiceServer(s grpc.ServiceRegistrar, srv RoleServiceServer) {
|
||||
// If the following call pancis, it indicates UnimplementedRoleServiceServer was
|
||||
// embedded by pointer and is nil. This will cause panics if an
|
||||
// unimplemented method is ever invoked, so we test this at initialization
|
||||
// time to prevent it from happening at runtime later due to I/O.
|
||||
if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {
|
||||
t.testEmbeddedByValue()
|
||||
}
|
||||
s.RegisterService(&RoleService_ServiceDesc, srv)
|
||||
}
|
||||
|
||||
func _RoleService_GetRoleLabels_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(GetRoleLabelRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(RoleServiceServer).GetRoleLabels(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: RoleService_GetRoleLabels_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(RoleServiceServer).GetRoleLabels(ctx, req.(*GetRoleLabelRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _RoleService_GetRolePermissions_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(GetRolePermissionRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(RoleServiceServer).GetRolePermissions(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: RoleService_GetRolePermissions_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(RoleServiceServer).GetRolePermissions(ctx, req.(*GetRolePermissionRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _RoleService_SaveRolePermission_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(SaveRolePermissionRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(RoleServiceServer).SaveRolePermission(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: RoleService_SaveRolePermission_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(RoleServiceServer).SaveRolePermission(ctx, req.(*SaveRolePermissionRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
// RoleService_ServiceDesc is the grpc.ServiceDesc for RoleService service.
|
||||
// It's only intended for direct use with grpc.RegisterService,
|
||||
// and not to be introspected or modified (even as a copy)
|
||||
var RoleService_ServiceDesc = grpc.ServiceDesc{
|
||||
ServiceName: "organize.RoleService",
|
||||
HandlerType: (*RoleServiceServer)(nil),
|
||||
Methods: []grpc.MethodDesc{
|
||||
{
|
||||
MethodName: "GetRoleLabels",
|
||||
Handler: _RoleService_GetRoleLabels_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "GetRolePermissions",
|
||||
Handler: _RoleService_GetRolePermissions_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "SaveRolePermission",
|
||||
Handler: _RoleService_SaveRolePermission_Handler,
|
||||
},
|
||||
},
|
||||
Streams: []grpc.StreamDesc{},
|
||||
Metadata: "organize.proto",
|
||||
}
|
||||
|
||||
const (
|
||||
MenuService_GetMenus_FullMethodName = "/organize.MenuService/GetMenus"
|
||||
MenuService_GetMenuLevelLabels_FullMethodName = "/organize.MenuService/GetMenuLevelLabels"
|
||||
)
|
||||
|
||||
// MenuServiceClient is the client API for MenuService service.
|
||||
//
|
||||
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
|
||||
//
|
||||
// 菜单服务
|
||||
type MenuServiceClient interface {
|
||||
GetMenus(ctx context.Context, in *GetMenuRequest, opts ...grpc.CallOption) (*GetMenuResponse, error)
|
||||
GetMenuLevelLabels(ctx context.Context, in *GetMenuLevelLabelsRequest, opts ...grpc.CallOption) (*GetMenuLevelLabelsResponse, error)
|
||||
}
|
||||
|
||||
type menuServiceClient struct {
|
||||
|
@ -49,13 +759,22 @@ func (c *menuServiceClient) GetMenus(ctx context.Context, in *GetMenuRequest, op
|
|||
return out, nil
|
||||
}
|
||||
|
||||
func (c *menuServiceClient) GetMenuLevelLabels(ctx context.Context, in *GetMenuLevelLabelsRequest, opts ...grpc.CallOption) (*GetMenuLevelLabelsResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(GetMenuLevelLabelsResponse)
|
||||
err := c.cc.Invoke(ctx, MenuService_GetMenuLevelLabels_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// MenuServiceServer is the server API for MenuService service.
|
||||
// All implementations must embed UnimplementedMenuServiceServer
|
||||
// for forward compatibility.
|
||||
//
|
||||
// 菜单服务
|
||||
type MenuServiceServer interface {
|
||||
GetMenus(context.Context, *GetMenuRequest) (*GetMenuResponse, error)
|
||||
GetMenuLevelLabels(context.Context, *GetMenuLevelLabelsRequest) (*GetMenuLevelLabelsResponse, error)
|
||||
mustEmbedUnimplementedMenuServiceServer()
|
||||
}
|
||||
|
||||
|
@ -69,6 +788,9 @@ type UnimplementedMenuServiceServer struct{}
|
|||
func (UnimplementedMenuServiceServer) GetMenus(context.Context, *GetMenuRequest) (*GetMenuResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method GetMenus not implemented")
|
||||
}
|
||||
func (UnimplementedMenuServiceServer) GetMenuLevelLabels(context.Context, *GetMenuLevelLabelsRequest) (*GetMenuLevelLabelsResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method GetMenuLevelLabels not implemented")
|
||||
}
|
||||
func (UnimplementedMenuServiceServer) mustEmbedUnimplementedMenuServiceServer() {}
|
||||
func (UnimplementedMenuServiceServer) testEmbeddedByValue() {}
|
||||
|
||||
|
@ -108,6 +830,24 @@ func _MenuService_GetMenus_Handler(srv interface{}, ctx context.Context, dec fun
|
|||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _MenuService_GetMenuLevelLabels_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(GetMenuLevelLabelsRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(MenuServiceServer).GetMenuLevelLabels(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: MenuService_GetMenuLevelLabels_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(MenuServiceServer).GetMenuLevelLabels(ctx, req.(*GetMenuLevelLabelsRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
// MenuService_ServiceDesc is the grpc.ServiceDesc for MenuService service.
|
||||
// It's only intended for direct use with grpc.RegisterService,
|
||||
// and not to be introspected or modified (even as a copy)
|
||||
|
@ -119,187 +859,9 @@ var MenuService_ServiceDesc = grpc.ServiceDesc{
|
|||
MethodName: "GetMenus",
|
||||
Handler: _MenuService_GetMenus_Handler,
|
||||
},
|
||||
},
|
||||
Streams: []grpc.StreamDesc{},
|
||||
Metadata: "organize.proto",
|
||||
}
|
||||
|
||||
const (
|
||||
ProfileService_GetProfile_FullMethodName = "/organize.ProfileService/GetProfile"
|
||||
ProfileService_UpdateProfile_FullMethodName = "/organize.ProfileService/UpdateProfile"
|
||||
ProfileService_ResetPassword_FullMethodName = "/organize.ProfileService/ResetPassword"
|
||||
)
|
||||
|
||||
// ProfileServiceClient is the client API for ProfileService service.
|
||||
//
|
||||
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
|
||||
//
|
||||
// 用户服务
|
||||
type ProfileServiceClient interface {
|
||||
GetProfile(ctx context.Context, in *GetProfileRequest, opts ...grpc.CallOption) (*GetProfileResponse, error)
|
||||
UpdateProfile(ctx context.Context, in *UpdateProfileRequest, opts ...grpc.CallOption) (*UpdateProfileResponse, error)
|
||||
ResetPassword(ctx context.Context, in *ResetPasswordRequest, opts ...grpc.CallOption) (*ResetPasswordResponse, error)
|
||||
}
|
||||
|
||||
type profileServiceClient struct {
|
||||
cc grpc.ClientConnInterface
|
||||
}
|
||||
|
||||
func NewProfileServiceClient(cc grpc.ClientConnInterface) ProfileServiceClient {
|
||||
return &profileServiceClient{cc}
|
||||
}
|
||||
|
||||
func (c *profileServiceClient) GetProfile(ctx context.Context, in *GetProfileRequest, opts ...grpc.CallOption) (*GetProfileResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(GetProfileResponse)
|
||||
err := c.cc.Invoke(ctx, ProfileService_GetProfile_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *profileServiceClient) UpdateProfile(ctx context.Context, in *UpdateProfileRequest, opts ...grpc.CallOption) (*UpdateProfileResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(UpdateProfileResponse)
|
||||
err := c.cc.Invoke(ctx, ProfileService_UpdateProfile_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *profileServiceClient) ResetPassword(ctx context.Context, in *ResetPasswordRequest, opts ...grpc.CallOption) (*ResetPasswordResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(ResetPasswordResponse)
|
||||
err := c.cc.Invoke(ctx, ProfileService_ResetPassword_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ProfileServiceServer is the server API for ProfileService service.
|
||||
// All implementations must embed UnimplementedProfileServiceServer
|
||||
// for forward compatibility.
|
||||
//
|
||||
// 用户服务
|
||||
type ProfileServiceServer interface {
|
||||
GetProfile(context.Context, *GetProfileRequest) (*GetProfileResponse, error)
|
||||
UpdateProfile(context.Context, *UpdateProfileRequest) (*UpdateProfileResponse, error)
|
||||
ResetPassword(context.Context, *ResetPasswordRequest) (*ResetPasswordResponse, error)
|
||||
mustEmbedUnimplementedProfileServiceServer()
|
||||
}
|
||||
|
||||
// UnimplementedProfileServiceServer must be embedded to have
|
||||
// forward compatible implementations.
|
||||
//
|
||||
// NOTE: this should be embedded by value instead of pointer to avoid a nil
|
||||
// pointer dereference when methods are called.
|
||||
type UnimplementedProfileServiceServer struct{}
|
||||
|
||||
func (UnimplementedProfileServiceServer) GetProfile(context.Context, *GetProfileRequest) (*GetProfileResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method GetProfile not implemented")
|
||||
}
|
||||
func (UnimplementedProfileServiceServer) UpdateProfile(context.Context, *UpdateProfileRequest) (*UpdateProfileResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method UpdateProfile not implemented")
|
||||
}
|
||||
func (UnimplementedProfileServiceServer) ResetPassword(context.Context, *ResetPasswordRequest) (*ResetPasswordResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method ResetPassword not implemented")
|
||||
}
|
||||
func (UnimplementedProfileServiceServer) mustEmbedUnimplementedProfileServiceServer() {}
|
||||
func (UnimplementedProfileServiceServer) testEmbeddedByValue() {}
|
||||
|
||||
// UnsafeProfileServiceServer may be embedded to opt out of forward compatibility for this service.
|
||||
// Use of this interface is not recommended, as added methods to ProfileServiceServer will
|
||||
// result in compilation errors.
|
||||
type UnsafeProfileServiceServer interface {
|
||||
mustEmbedUnimplementedProfileServiceServer()
|
||||
}
|
||||
|
||||
func RegisterProfileServiceServer(s grpc.ServiceRegistrar, srv ProfileServiceServer) {
|
||||
// If the following call pancis, it indicates UnimplementedProfileServiceServer was
|
||||
// embedded by pointer and is nil. This will cause panics if an
|
||||
// unimplemented method is ever invoked, so we test this at initialization
|
||||
// time to prevent it from happening at runtime later due to I/O.
|
||||
if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {
|
||||
t.testEmbeddedByValue()
|
||||
}
|
||||
s.RegisterService(&ProfileService_ServiceDesc, srv)
|
||||
}
|
||||
|
||||
func _ProfileService_GetProfile_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(GetProfileRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(ProfileServiceServer).GetProfile(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: ProfileService_GetProfile_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(ProfileServiceServer).GetProfile(ctx, req.(*GetProfileRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _ProfileService_UpdateProfile_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(UpdateProfileRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(ProfileServiceServer).UpdateProfile(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: ProfileService_UpdateProfile_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(ProfileServiceServer).UpdateProfile(ctx, req.(*UpdateProfileRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _ProfileService_ResetPassword_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(ResetPasswordRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(ProfileServiceServer).ResetPassword(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: ProfileService_ResetPassword_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(ProfileServiceServer).ResetPassword(ctx, req.(*ResetPasswordRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
// ProfileService_ServiceDesc is the grpc.ServiceDesc for ProfileService service.
|
||||
// It's only intended for direct use with grpc.RegisterService,
|
||||
// and not to be introspected or modified (even as a copy)
|
||||
var ProfileService_ServiceDesc = grpc.ServiceDesc{
|
||||
ServiceName: "organize.ProfileService",
|
||||
HandlerType: (*ProfileServiceServer)(nil),
|
||||
Methods: []grpc.MethodDesc{
|
||||
{
|
||||
MethodName: "GetProfile",
|
||||
Handler: _ProfileService_GetProfile_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "UpdateProfile",
|
||||
Handler: _ProfileService_UpdateProfile_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "ResetPassword",
|
||||
Handler: _ProfileService_ResetPassword_Handler,
|
||||
MethodName: "GetMenuLevelLabels",
|
||||
Handler: _MenuService_GetMenuLevelLabels_Handler,
|
||||
},
|
||||
},
|
||||
Streams: []grpc.StreamDesc{},
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
// Code generated by protoc-gen-go-aeus. DO NOT EDIT.
|
||||
// source: organize.proto
|
||||
// date: 2025-06-13 11:10:07
|
||||
// date: 2025-06-22 11:09:05
|
||||
|
||||
package pb
|
||||
|
||||
|
@ -10,32 +10,299 @@ import (
|
|||
"git.nobla.cn/golang/aeus/pkg/errors"
|
||||
)
|
||||
|
||||
type MenuServiceHttpServer interface {
|
||||
GetMenus(context.Context, *GetMenuRequest) (*GetMenuResponse, error)
|
||||
type UserServiceHttpServer interface {
|
||||
|
||||
// 获取用户菜单
|
||||
GetMenus(ctx context.Context, req *GetUserMenuRequest) (res *GetUserMenuResponse, err error)
|
||||
|
||||
// 获取用户信息
|
||||
GetProfile(ctx context.Context, req *GetProfileRequest) (res *GetProfileResponse, err error)
|
||||
|
||||
// 更新用户信息
|
||||
UpdateProfile(ctx context.Context, req *UpdateProfileRequest) (res *UpdateProfileResponse, err error)
|
||||
|
||||
// 重置用户密码
|
||||
ResetPassword(ctx context.Context, req *ResetPasswordRequest) (res *ResetPasswordResponse, err error)
|
||||
|
||||
// 获取用户权限
|
||||
GetPermissions(ctx context.Context, req *GetPermissionRequest) (res *GetPermissionResponse, err error)
|
||||
|
||||
// 获取用户标签
|
||||
GetUserLabels(ctx context.Context, req *GetUserLabelRequest) (res *GetUserLabelResponse, err error)
|
||||
|
||||
// 获取用户标签
|
||||
GetUserTags(ctx context.Context, req *GetUserTagRequest) (res *GetUserTagResponse, err error)
|
||||
}
|
||||
|
||||
type ProfileServiceHttpServer interface {
|
||||
GetProfile(context.Context, *GetProfileRequest) (*GetProfileResponse, error)
|
||||
type DepartmentServiceHttpServer interface {
|
||||
|
||||
UpdateProfile(context.Context, *UpdateProfileRequest) (*UpdateProfileResponse, error)
|
||||
// 获取部门标签
|
||||
GetDepartmentLabels(ctx context.Context, req *GetDepartmentLabelRequest) (res *GetDepartmentLabelResponse, err error)
|
||||
|
||||
ResetPassword(context.Context, *ResetPasswordRequest) (*ResetPasswordResponse, error)
|
||||
GetDepartmentUsers(ctx context.Context, req *GetDepartmentUserRequest) (res *GetDepartmentUserResponse, err error)
|
||||
|
||||
GetDepartmentLevelLabels(ctx context.Context, req *GetDepartmentLevelLabelsRequest) (res *GetDepartmentLevelLabelsResponse, err error)
|
||||
}
|
||||
|
||||
type RoleServiceHttpServer interface {
|
||||
|
||||
// 获取角色标签
|
||||
GetRoleLabels(ctx context.Context, req *GetRoleLabelRequest) (res *GetRoleLabelResponse, err error)
|
||||
|
||||
// 获取角色权限
|
||||
GetRolePermissions(ctx context.Context, req *GetRolePermissionRequest) (res *GetRolePermissionResponse, err error)
|
||||
|
||||
SaveRolePermission(ctx context.Context, req *SaveRolePermissionRequest) (res *SaveRolePermissionResponse, err error)
|
||||
}
|
||||
|
||||
type MenuServiceHttpServer interface {
|
||||
GetMenus(ctx context.Context, req *GetMenuRequest) (res *GetMenuResponse, err error)
|
||||
|
||||
GetMenuLevelLabels(ctx context.Context, req *GetMenuLevelLabelsRequest) (res *GetMenuLevelLabelsResponse, err error)
|
||||
}
|
||||
|
||||
type AuthServiceHttpServer interface {
|
||||
Login(context.Context, *LoginRequest) (*LoginResponse, error)
|
||||
Login(ctx context.Context, req *LoginRequest) (res *LoginResponse, err error)
|
||||
|
||||
Logout(context.Context, *LogoutRequest) (*LogoutResponse, error)
|
||||
Logout(ctx context.Context, req *LogoutRequest) (res *LogoutResponse, err error)
|
||||
}
|
||||
|
||||
// 获取用户菜单
|
||||
func handleUserServiceGetMenus(s UserServiceHttpServer) http.HandleFunc {
|
||||
return func(ctx *http.Context) (err error) {
|
||||
req := &GetUserMenuRequest{}
|
||||
if err := ctx.Bind(req); err != nil {
|
||||
return ctx.Error(errors.Invalid, err.Error())
|
||||
}
|
||||
if res, err := s.GetMenus(ctx.Context(), req); err != nil {
|
||||
if er, ok := err.(*errors.Error); ok {
|
||||
return ctx.Error(er.Code, er.Message)
|
||||
} else {
|
||||
return ctx.Error(errors.Unavailable, err.Error())
|
||||
}
|
||||
} else {
|
||||
return ctx.Success(res)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 获取用户信息
|
||||
func handleUserServiceGetProfile(s UserServiceHttpServer) http.HandleFunc {
|
||||
return func(ctx *http.Context) (err error) {
|
||||
req := &GetProfileRequest{}
|
||||
if err := ctx.Bind(req); err != nil {
|
||||
return ctx.Error(errors.Invalid, err.Error())
|
||||
}
|
||||
if res, err := s.GetProfile(ctx.Context(), req); err != nil {
|
||||
if er, ok := err.(*errors.Error); ok {
|
||||
return ctx.Error(er.Code, er.Message)
|
||||
} else {
|
||||
return ctx.Error(errors.Unavailable, err.Error())
|
||||
}
|
||||
} else {
|
||||
return ctx.Success(res)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 更新用户信息
|
||||
func handleUserServiceUpdateProfile(s UserServiceHttpServer) http.HandleFunc {
|
||||
return func(ctx *http.Context) (err error) {
|
||||
req := &UpdateProfileRequest{}
|
||||
if err := ctx.Bind(req); err != nil {
|
||||
return ctx.Error(errors.Invalid, err.Error())
|
||||
}
|
||||
if res, err := s.UpdateProfile(ctx.Context(), req); err != nil {
|
||||
if er, ok := err.(*errors.Error); ok {
|
||||
return ctx.Error(er.Code, er.Message)
|
||||
} else {
|
||||
return ctx.Error(errors.Unavailable, err.Error())
|
||||
}
|
||||
} else {
|
||||
return ctx.Success(res)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 重置用户密码
|
||||
func handleUserServiceResetPassword(s UserServiceHttpServer) http.HandleFunc {
|
||||
return func(ctx *http.Context) (err error) {
|
||||
req := &ResetPasswordRequest{}
|
||||
if err := ctx.Bind(req); err != nil {
|
||||
return ctx.Error(errors.Invalid, err.Error())
|
||||
}
|
||||
if res, err := s.ResetPassword(ctx.Context(), req); err != nil {
|
||||
if er, ok := err.(*errors.Error); ok {
|
||||
return ctx.Error(er.Code, er.Message)
|
||||
} else {
|
||||
return ctx.Error(errors.Unavailable, err.Error())
|
||||
}
|
||||
} else {
|
||||
return ctx.Success(res)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 获取用户权限
|
||||
func handleUserServiceGetPermissions(s UserServiceHttpServer) http.HandleFunc {
|
||||
return func(ctx *http.Context) (err error) {
|
||||
req := &GetPermissionRequest{}
|
||||
if err := ctx.Bind(req); err != nil {
|
||||
return ctx.Error(errors.Invalid, err.Error())
|
||||
}
|
||||
if res, err := s.GetPermissions(ctx.Context(), req); err != nil {
|
||||
if er, ok := err.(*errors.Error); ok {
|
||||
return ctx.Error(er.Code, er.Message)
|
||||
} else {
|
||||
return ctx.Error(errors.Unavailable, err.Error())
|
||||
}
|
||||
} else {
|
||||
return ctx.Success(res)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 获取用户标签
|
||||
func handleUserServiceGetUserLabels(s UserServiceHttpServer) http.HandleFunc {
|
||||
return func(ctx *http.Context) (err error) {
|
||||
req := &GetUserLabelRequest{}
|
||||
|
||||
if res, err := s.GetUserLabels(ctx.Context(), req); err != nil {
|
||||
if er, ok := err.(*errors.Error); ok {
|
||||
return ctx.Error(er.Code, er.Message)
|
||||
} else {
|
||||
return ctx.Error(errors.Unavailable, err.Error())
|
||||
}
|
||||
} else {
|
||||
return ctx.Success(res)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 获取用户标签
|
||||
func handleUserServiceGetUserTags(s UserServiceHttpServer) http.HandleFunc {
|
||||
return func(ctx *http.Context) (err error) {
|
||||
req := &GetUserTagRequest{}
|
||||
|
||||
if res, err := s.GetUserTags(ctx.Context(), req); err != nil {
|
||||
if er, ok := err.(*errors.Error); ok {
|
||||
return ctx.Error(er.Code, er.Message)
|
||||
} else {
|
||||
return ctx.Error(errors.Unavailable, err.Error())
|
||||
}
|
||||
} else {
|
||||
return ctx.Success(res)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 获取部门标签
|
||||
func handleDepartmentServiceGetDepartmentLabels(s DepartmentServiceHttpServer) http.HandleFunc {
|
||||
return func(ctx *http.Context) (err error) {
|
||||
req := &GetDepartmentLabelRequest{}
|
||||
|
||||
if res, err := s.GetDepartmentLabels(ctx.Context(), req); err != nil {
|
||||
if er, ok := err.(*errors.Error); ok {
|
||||
return ctx.Error(er.Code, er.Message)
|
||||
} else {
|
||||
return ctx.Error(errors.Unavailable, err.Error())
|
||||
}
|
||||
} else {
|
||||
return ctx.Success(res)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func handleDepartmentServiceGetDepartmentUsers(s DepartmentServiceHttpServer) http.HandleFunc {
|
||||
return func(ctx *http.Context) (err error) {
|
||||
req := &GetDepartmentUserRequest{}
|
||||
|
||||
if res, err := s.GetDepartmentUsers(ctx.Context(), req); err != nil {
|
||||
if er, ok := err.(*errors.Error); ok {
|
||||
return ctx.Error(er.Code, er.Message)
|
||||
} else {
|
||||
return ctx.Error(errors.Unavailable, err.Error())
|
||||
}
|
||||
} else {
|
||||
return ctx.Success(res)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func handleDepartmentServiceGetDepartmentLevelLabels(s DepartmentServiceHttpServer) http.HandleFunc {
|
||||
return func(ctx *http.Context) (err error) {
|
||||
req := &GetDepartmentLevelLabelsRequest{}
|
||||
|
||||
if res, err := s.GetDepartmentLevelLabels(ctx.Context(), req); err != nil {
|
||||
if er, ok := err.(*errors.Error); ok {
|
||||
return ctx.Error(er.Code, er.Message)
|
||||
} else {
|
||||
return ctx.Error(errors.Unavailable, err.Error())
|
||||
}
|
||||
} else {
|
||||
return ctx.Success(res)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 获取角色标签
|
||||
func handleRoleServiceGetRoleLabels(s RoleServiceHttpServer) http.HandleFunc {
|
||||
return func(ctx *http.Context) (err error) {
|
||||
req := &GetRoleLabelRequest{}
|
||||
|
||||
if res, err := s.GetRoleLabels(ctx.Context(), req); err != nil {
|
||||
if er, ok := err.(*errors.Error); ok {
|
||||
return ctx.Error(er.Code, er.Message)
|
||||
} else {
|
||||
return ctx.Error(errors.Unavailable, err.Error())
|
||||
}
|
||||
} else {
|
||||
return ctx.Success(res)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 获取角色权限
|
||||
func handleRoleServiceGetRolePermissions(s RoleServiceHttpServer) http.HandleFunc {
|
||||
return func(ctx *http.Context) (err error) {
|
||||
req := &GetRolePermissionRequest{}
|
||||
if err := ctx.Bind(req); err != nil {
|
||||
return ctx.Error(errors.Invalid, err.Error())
|
||||
}
|
||||
if res, err := s.GetRolePermissions(ctx.Context(), req); err != nil {
|
||||
if er, ok := err.(*errors.Error); ok {
|
||||
return ctx.Error(er.Code, er.Message)
|
||||
} else {
|
||||
return ctx.Error(errors.Unavailable, err.Error())
|
||||
}
|
||||
} else {
|
||||
return ctx.Success(res)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func handleRoleServiceSaveRolePermission(s RoleServiceHttpServer) http.HandleFunc {
|
||||
return func(ctx *http.Context) (err error) {
|
||||
req := &SaveRolePermissionRequest{}
|
||||
if err := ctx.Bind(req); err != nil {
|
||||
return ctx.Error(errors.Invalid, err.Error())
|
||||
}
|
||||
if res, err := s.SaveRolePermission(ctx.Context(), req); err != nil {
|
||||
if er, ok := err.(*errors.Error); ok {
|
||||
return ctx.Error(er.Code, er.Message)
|
||||
} else {
|
||||
return ctx.Error(errors.Unavailable, err.Error())
|
||||
}
|
||||
} else {
|
||||
return ctx.Success(res)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func handleMenuServiceGetMenus(s MenuServiceHttpServer) http.HandleFunc {
|
||||
return func(ctx *http.Context) (err error) {
|
||||
req := &GetMenuRequest{}
|
||||
|
||||
if err := ctx.Bind(req); err != nil {
|
||||
return ctx.Error(errors.Invalid, err.Error())
|
||||
}
|
||||
|
||||
if res, err := s.GetMenus(ctx.Context(), req); err != nil {
|
||||
if er, ok := err.(*errors.Error); ok {
|
||||
return ctx.Error(er.Code, er.Message)
|
||||
|
@ -48,55 +315,11 @@ func handleMenuServiceGetMenus(s MenuServiceHttpServer) http.HandleFunc {
|
|||
}
|
||||
}
|
||||
|
||||
func handleProfileServiceGetProfile(s ProfileServiceHttpServer) http.HandleFunc {
|
||||
func handleMenuServiceGetMenuLevelLabels(s MenuServiceHttpServer) http.HandleFunc {
|
||||
return func(ctx *http.Context) (err error) {
|
||||
req := &GetProfileRequest{}
|
||||
req := &GetMenuLevelLabelsRequest{}
|
||||
|
||||
if err := ctx.Bind(req); err != nil {
|
||||
return ctx.Error(errors.Invalid, err.Error())
|
||||
}
|
||||
|
||||
if res, err := s.GetProfile(ctx.Context(), req); err != nil {
|
||||
if er, ok := err.(*errors.Error); ok {
|
||||
return ctx.Error(er.Code, er.Message)
|
||||
} else {
|
||||
return ctx.Error(errors.Unavailable, err.Error())
|
||||
}
|
||||
} else {
|
||||
return ctx.Success(res)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func handleProfileServiceUpdateProfile(s ProfileServiceHttpServer) http.HandleFunc {
|
||||
return func(ctx *http.Context) (err error) {
|
||||
req := &UpdateProfileRequest{}
|
||||
|
||||
if err := ctx.Bind(req); err != nil {
|
||||
return ctx.Error(errors.Invalid, err.Error())
|
||||
}
|
||||
|
||||
if res, err := s.UpdateProfile(ctx.Context(), req); err != nil {
|
||||
if er, ok := err.(*errors.Error); ok {
|
||||
return ctx.Error(er.Code, er.Message)
|
||||
} else {
|
||||
return ctx.Error(errors.Unavailable, err.Error())
|
||||
}
|
||||
} else {
|
||||
return ctx.Success(res)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func handleProfileServiceResetPassword(s ProfileServiceHttpServer) http.HandleFunc {
|
||||
return func(ctx *http.Context) (err error) {
|
||||
req := &ResetPasswordRequest{}
|
||||
|
||||
if err := ctx.Bind(req); err != nil {
|
||||
return ctx.Error(errors.Invalid, err.Error())
|
||||
}
|
||||
|
||||
if res, err := s.ResetPassword(ctx.Context(), req); err != nil {
|
||||
if res, err := s.GetMenuLevelLabels(ctx.Context(), req); err != nil {
|
||||
if er, ok := err.(*errors.Error); ok {
|
||||
return ctx.Error(er.Code, er.Message)
|
||||
} else {
|
||||
|
@ -111,11 +334,9 @@ func handleProfileServiceResetPassword(s ProfileServiceHttpServer) http.HandleFu
|
|||
func handleAuthServiceLogin(s AuthServiceHttpServer) http.HandleFunc {
|
||||
return func(ctx *http.Context) (err error) {
|
||||
req := &LoginRequest{}
|
||||
|
||||
if err := ctx.Bind(req); err != nil {
|
||||
return ctx.Error(errors.Invalid, err.Error())
|
||||
}
|
||||
|
||||
if res, err := s.Login(ctx.Context(), req); err != nil {
|
||||
if er, ok := err.(*errors.Error); ok {
|
||||
return ctx.Error(er.Code, er.Message)
|
||||
|
@ -131,11 +352,9 @@ func handleAuthServiceLogin(s AuthServiceHttpServer) http.HandleFunc {
|
|||
func handleAuthServiceLogout(s AuthServiceHttpServer) http.HandleFunc {
|
||||
return func(ctx *http.Context) (err error) {
|
||||
req := &LogoutRequest{}
|
||||
|
||||
if err := ctx.Bind(req); err != nil {
|
||||
return ctx.Error(errors.Invalid, err.Error())
|
||||
}
|
||||
|
||||
if res, err := s.Logout(ctx.Context(), req); err != nil {
|
||||
if er, ok := err.(*errors.Error); ok {
|
||||
return ctx.Error(er.Code, er.Message)
|
||||
|
@ -148,23 +367,64 @@ func handleAuthServiceLogout(s AuthServiceHttpServer) http.HandleFunc {
|
|||
}
|
||||
}
|
||||
|
||||
func RegisterMenuServiceRouter(hs *http.Server, s MenuServiceHttpServer) {
|
||||
func RegisterUserServiceRouter(hs *http.Server, s UserServiceHttpServer) {
|
||||
|
||||
// Register handle GetMenus route
|
||||
hs.GET("/api/menu", handleMenuServiceGetMenus(s))
|
||||
hs.GET("/user/menus", handleUserServiceGetMenus(s))
|
||||
|
||||
// Register handle GetProfile route
|
||||
hs.GET("/user/profile", handleUserServiceGetProfile(s))
|
||||
|
||||
// Register handle UpdateProfile route
|
||||
hs.PUT("/user/profile", handleUserServiceUpdateProfile(s))
|
||||
|
||||
// Register handle ResetPassword route
|
||||
hs.POST("/user/reset-password", handleUserServiceResetPassword(s))
|
||||
|
||||
// Register handle GetPermissions route
|
||||
hs.GET("/user/permissions", handleUserServiceGetPermissions(s))
|
||||
|
||||
// Register handle GetUserLabels route
|
||||
hs.GET("/user/labels", handleUserServiceGetUserLabels(s))
|
||||
|
||||
// Register handle GetUserTags route
|
||||
hs.GET("/user/tags", handleUserServiceGetUserTags(s))
|
||||
|
||||
}
|
||||
|
||||
func RegisterProfileServiceRouter(hs *http.Server, s ProfileServiceHttpServer) {
|
||||
func RegisterDepartmentServiceRouter(hs *http.Server, s DepartmentServiceHttpServer) {
|
||||
|
||||
// Register handle GetProfile route
|
||||
hs.GET("/user/profile", handleProfileServiceGetProfile(s))
|
||||
// Register handle GetDepartmentLabels route
|
||||
hs.GET("/department/labels", handleDepartmentServiceGetDepartmentLabels(s))
|
||||
|
||||
// Register handle UpdateProfile route
|
||||
hs.PUT("/user/profile", handleProfileServiceUpdateProfile(s))
|
||||
// Register handle GetDepartmentUsers route
|
||||
hs.GET("/department/users", handleDepartmentServiceGetDepartmentUsers(s))
|
||||
|
||||
// Register handle ResetPassword route
|
||||
hs.POST("/user/reset-password", handleProfileServiceResetPassword(s))
|
||||
// Register handle GetDepartmentLevelLabels route
|
||||
hs.GET("/department/level-labels", handleDepartmentServiceGetDepartmentLevelLabels(s))
|
||||
|
||||
}
|
||||
|
||||
func RegisterRoleServiceRouter(hs *http.Server, s RoleServiceHttpServer) {
|
||||
|
||||
// Register handle GetRoleLabels route
|
||||
hs.GET("/role/labels", handleRoleServiceGetRoleLabels(s))
|
||||
|
||||
// Register handle GetRolePermissions route
|
||||
hs.GET("/role/permissions", handleRoleServiceGetRolePermissions(s))
|
||||
|
||||
// Register handle SaveRolePermission route
|
||||
hs.POST("/role/permissions", handleRoleServiceSaveRolePermission(s))
|
||||
|
||||
}
|
||||
|
||||
func RegisterMenuServiceRouter(hs *http.Server, s MenuServiceHttpServer) {
|
||||
|
||||
// Register handle GetMenus route
|
||||
hs.GET("/menu/list", handleMenuServiceGetMenus(s))
|
||||
|
||||
// Register handle GetMenuLevelLabels route
|
||||
hs.GET("/menu/level-labels", handleMenuServiceGetMenuLevelLabels(s))
|
||||
|
||||
}
|
||||
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
// Code generated by protoc-gen-go-aeus. DO NOT EDIT.
|
||||
// source: organize.proto
|
||||
// date: 2025-06-13 11:10:07
|
||||
// date: 2025-06-22 11:09:05
|
||||
|
||||
package pb
|
||||
|
||||
|
@ -9,15 +9,19 @@ import (
|
|||
)
|
||||
|
||||
type MenuModel struct {
|
||||
Id int64 `json:"id" yaml:"id" xml:"id" gorm:"primaryKey"`
|
||||
ParentId int64 `json:"parent_id" yaml:"parentId" xml:"parentId" gorm:"column:parent_id"`
|
||||
Name string `json:"name" yaml:"name" xml:"name" gorm:"index;size:60"`
|
||||
Label string `json:"label" yaml:"label" xml:"label" gorm:"size:120"`
|
||||
Uri string `json:"uri" yaml:"uri" xml:"uri" gorm:"size:512"`
|
||||
ViewPath string `json:"view_path" yaml:"viewPath" xml:"viewPath" gorm:"size:512"`
|
||||
Icon string `json:"icon" yaml:"icon" xml:"icon" gorm:"size:60"`
|
||||
Hidden bool `json:"hidden" yaml:"hidden" xml:"hidden" gorm:"column:hidden"`
|
||||
Public bool `json:"public" yaml:"public" xml:"public" gorm:"column:public"`
|
||||
Id int64 `json:"id" yaml:"id" xml:"id" gorm:"primaryKey;column:id" comment:"菜单ID"`
|
||||
CreatedAt int64 `json:"created_at" yaml:"createdAt" xml:"createdAt" gorm:"column:created_at" comment:"创建时间" scenarios:"view;export"`
|
||||
UpdatedAt int64 `json:"updated_at" yaml:"updatedAt" xml:"updatedAt" gorm:"index;column:updated_at" comment:"更新时间" scenarios:"view;export"`
|
||||
Parent string `json:"parent" yaml:"parent" xml:"parent" gorm:"index;size:60;column:parent" comment:"父级菜单" scenarios:"create;update;view;export" format:"menu" props:"readonly:update" live:"type:dropdown;url:/menu/level-labels"`
|
||||
Name string `json:"name" yaml:"name" xml:"name" gorm:"index;size:60;column:name" comment:"组件名称" props:"readonly:update" rule:"unique;required"`
|
||||
Label string `json:"label" yaml:"label" xml:"label" gorm:"size:120;column:label" comment:"菜单标题" rule:"required"`
|
||||
Uri string `json:"uri" yaml:"uri" xml:"uri" gorm:"size:512;column:uri" comment:"菜单链接" scenarios:"create;update;view;export" rule:"required"`
|
||||
ViewPath string `json:"view_path" yaml:"viewPath" xml:"viewPath" gorm:"size:512;column:view_path" comment:"视图路径" scenarios:"create;update;view;export"`
|
||||
Icon string `json:"icon" yaml:"icon" xml:"icon" gorm:"size:60;column:icon" comment:"菜单图标" scenarios:"create;update;view;export"`
|
||||
Hidden bool `json:"hidden" yaml:"hidden" xml:"hidden" gorm:"column:hidden" comment:"是否隐藏" scenarios:"create;update;view;export"`
|
||||
Public bool `json:"public" yaml:"public" xml:"public" gorm:"column:public" comment:"是否公开" scenarios:"create;update;view;export"`
|
||||
Description string `json:"description" yaml:"description" xml:"description" gorm:"size:1024;column:description" comment:"备注说明" scenarios:"create;update;view;export" format:"textarea"`
|
||||
Position int64 `json:"position" yaml:"position" xml:"position" gorm:"column:position" comment:"排序" scenarios:"create;update"`
|
||||
}
|
||||
|
||||
func (m *MenuModel) TableName() string {
|
||||
|
@ -26,7 +30,9 @@ func (m *MenuModel) TableName() string {
|
|||
|
||||
func (m *MenuModel) FromValue(x *Menu) {
|
||||
m.Id = x.Id
|
||||
m.ParentId = x.ParentId
|
||||
m.CreatedAt = x.CreatedAt
|
||||
m.UpdatedAt = x.UpdatedAt
|
||||
m.Parent = x.Parent
|
||||
m.Name = x.Name
|
||||
m.Label = x.Label
|
||||
m.Uri = x.Uri
|
||||
|
@ -34,12 +40,16 @@ func (m *MenuModel) FromValue(x *Menu) {
|
|||
m.Icon = x.Icon
|
||||
m.Hidden = x.Hidden
|
||||
m.Public = x.Public
|
||||
m.Description = x.Description
|
||||
m.Position = x.Position
|
||||
}
|
||||
|
||||
func (m *MenuModel) ToValue() (x *Menu) {
|
||||
x = &Menu{}
|
||||
x.Id = m.Id
|
||||
x.ParentId = m.ParentId
|
||||
x.CreatedAt = m.CreatedAt
|
||||
x.UpdatedAt = m.UpdatedAt
|
||||
x.Parent = m.Parent
|
||||
x.Name = m.Name
|
||||
x.Label = m.Label
|
||||
x.Uri = m.Uri
|
||||
|
@ -47,6 +57,8 @@ func (m *MenuModel) ToValue() (x *Menu) {
|
|||
x.Icon = m.Icon
|
||||
x.Hidden = m.Hidden
|
||||
x.Public = m.Public
|
||||
x.Description = m.Description
|
||||
x.Position = m.Position
|
||||
return x
|
||||
}
|
||||
|
||||
|
@ -67,14 +79,14 @@ func (m *MenuModel) Delete(db *gorm.DB) (err error) {
|
|||
}
|
||||
|
||||
func (m *MenuModel) Find(db *gorm.DB, pk any) (err error) {
|
||||
return db.Where("icon=?", pk).First(m).Error
|
||||
return db.Where("id=?", pk).First(m).Error
|
||||
}
|
||||
|
||||
func (m *MenuModel) FindOne(db *gorm.DB, query any, args ...any) (err error) {
|
||||
func (m *MenuModel) QueryOne(db *gorm.DB, query any, args ...any) (err error) {
|
||||
return db.Where(query, args...).First(m).Error
|
||||
}
|
||||
|
||||
func (m *MenuModel) FindAll(db *gorm.DB, query any, args ...any) (err error) {
|
||||
func (m *MenuModel) QueryAll(db *gorm.DB, query any, args ...any) (err error) {
|
||||
return db.Where(query, args...).Find(m).Error
|
||||
}
|
||||
|
||||
|
@ -83,10 +95,12 @@ func NewMenuModel() *MenuModel {
|
|||
}
|
||||
|
||||
type RoleModel struct {
|
||||
Id int64 `json:"id" yaml:"id" xml:"id" gorm:"primaryKey"`
|
||||
Name string `json:"name" yaml:"name" xml:"name" gorm:"index;size:60"`
|
||||
Label string `json:"label" yaml:"label" xml:"label" gorm:"size:60"`
|
||||
Description string `json:"description" yaml:"description" xml:"description" gorm:"size:1024"`
|
||||
Id int64 `json:"id" yaml:"id" xml:"id" gorm:"primaryKey;column:id" comment:"角色ID"`
|
||||
CreatedAt int64 `json:"created_at" yaml:"createdAt" xml:"createdAt" gorm:"column:created_at" comment:"创建时间" scenarios:"view;export"`
|
||||
UpdatedAt int64 `json:"updated_at" yaml:"updatedAt" xml:"updatedAt" gorm:"index;column:updated_at" comment:"更新时间" scenarios:"view;export"`
|
||||
Name string `json:"name" yaml:"name" xml:"name" gorm:"index;size:60;column:name" comment:"角色名称" props:"readonly:update" rule:"required"`
|
||||
Label string `json:"label" yaml:"label" xml:"label" gorm:"size:60;column:label" comment:"角色标题" rule:"required"`
|
||||
Description string `json:"description" yaml:"description" xml:"description" gorm:"size:1024;column:description" comment:"备注说明" scenarios:"list;create;update;export" format:"textarea"`
|
||||
}
|
||||
|
||||
func (m *RoleModel) TableName() string {
|
||||
|
@ -95,6 +109,8 @@ func (m *RoleModel) TableName() string {
|
|||
|
||||
func (m *RoleModel) FromValue(x *Role) {
|
||||
m.Id = x.Id
|
||||
m.CreatedAt = x.CreatedAt
|
||||
m.UpdatedAt = x.UpdatedAt
|
||||
m.Name = x.Name
|
||||
m.Label = x.Label
|
||||
m.Description = x.Description
|
||||
|
@ -103,6 +119,8 @@ func (m *RoleModel) FromValue(x *Role) {
|
|||
func (m *RoleModel) ToValue() (x *Role) {
|
||||
x = &Role{}
|
||||
x.Id = m.Id
|
||||
x.CreatedAt = m.CreatedAt
|
||||
x.UpdatedAt = m.UpdatedAt
|
||||
x.Name = m.Name
|
||||
x.Label = m.Label
|
||||
x.Description = m.Description
|
||||
|
@ -126,14 +144,14 @@ func (m *RoleModel) Delete(db *gorm.DB) (err error) {
|
|||
}
|
||||
|
||||
func (m *RoleModel) Find(db *gorm.DB, pk any) (err error) {
|
||||
return db.Where("description=?", pk).First(m).Error
|
||||
return db.Where("id=?", pk).First(m).Error
|
||||
}
|
||||
|
||||
func (m *RoleModel) FindOne(db *gorm.DB, query any, args ...any) (err error) {
|
||||
func (m *RoleModel) QueryOne(db *gorm.DB, query any, args ...any) (err error) {
|
||||
return db.Where(query, args...).First(m).Error
|
||||
}
|
||||
|
||||
func (m *RoleModel) FindAll(db *gorm.DB, query any, args ...any) (err error) {
|
||||
func (m *RoleModel) QueryAll(db *gorm.DB, query any, args ...any) (err error) {
|
||||
return db.Where(query, args...).Find(m).Error
|
||||
}
|
||||
|
||||
|
@ -142,10 +160,12 @@ func NewRoleModel() *RoleModel {
|
|||
}
|
||||
|
||||
type PermissionModel struct {
|
||||
Id int64 `json:"id" yaml:"id" xml:"id" gorm:"primaryKey"`
|
||||
MenuId int64 `json:"menu_id" yaml:"menuId" xml:"menuId" gorm:"index"`
|
||||
Permission string `json:"permission" yaml:"permission" xml:"permission" gorm:"index;size:60"`
|
||||
Label string `json:"label" yaml:"label" xml:"label" gorm:"size:60"`
|
||||
Id int64 `json:"id" yaml:"id" xml:"id" gorm:"primaryKey;column:id" comment:"权限ID"`
|
||||
CreatedAt int64 `json:"created_at" yaml:"createdAt" xml:"createdAt" gorm:"column:created_at" comment:"创建时间" scenarios:"view;export"`
|
||||
UpdatedAt int64 `json:"updated_at" yaml:"updatedAt" xml:"updatedAt" gorm:"index;column:updated_at" comment:"更新时间" scenarios:"view;export"`
|
||||
Menu string `json:"menu" yaml:"menu" xml:"menu" gorm:"index;size:60;column:menu" comment:"所属菜单" format:"menu" rule:"required"`
|
||||
Permission string `json:"permission" yaml:"permission" xml:"permission" gorm:"index;size:60;column:permission" comment:"权限名称" rule:"required"`
|
||||
Label string `json:"label" yaml:"label" xml:"label" gorm:"size:60;column:label" comment:"权限标题" rule:"required"`
|
||||
}
|
||||
|
||||
func (m *PermissionModel) TableName() string {
|
||||
|
@ -154,7 +174,9 @@ func (m *PermissionModel) TableName() string {
|
|||
|
||||
func (m *PermissionModel) FromValue(x *Permission) {
|
||||
m.Id = x.Id
|
||||
m.MenuId = x.MenuId
|
||||
m.CreatedAt = x.CreatedAt
|
||||
m.UpdatedAt = x.UpdatedAt
|
||||
m.Menu = x.Menu
|
||||
m.Permission = x.Permission
|
||||
m.Label = x.Label
|
||||
}
|
||||
|
@ -162,7 +184,9 @@ func (m *PermissionModel) FromValue(x *Permission) {
|
|||
func (m *PermissionModel) ToValue() (x *Permission) {
|
||||
x = &Permission{}
|
||||
x.Id = m.Id
|
||||
x.MenuId = m.MenuId
|
||||
x.CreatedAt = m.CreatedAt
|
||||
x.UpdatedAt = m.UpdatedAt
|
||||
x.Menu = m.Menu
|
||||
x.Permission = m.Permission
|
||||
x.Label = m.Label
|
||||
return x
|
||||
|
@ -185,14 +209,14 @@ func (m *PermissionModel) Delete(db *gorm.DB) (err error) {
|
|||
}
|
||||
|
||||
func (m *PermissionModel) Find(db *gorm.DB, pk any) (err error) {
|
||||
return db.Where("label=?", pk).First(m).Error
|
||||
return db.Where("id=?", pk).First(m).Error
|
||||
}
|
||||
|
||||
func (m *PermissionModel) FindOne(db *gorm.DB, query any, args ...any) (err error) {
|
||||
func (m *PermissionModel) QueryOne(db *gorm.DB, query any, args ...any) (err error) {
|
||||
return db.Where(query, args...).First(m).Error
|
||||
}
|
||||
|
||||
func (m *PermissionModel) FindAll(db *gorm.DB, query any, args ...any) (err error) {
|
||||
func (m *PermissionModel) QueryAll(db *gorm.DB, query any, args ...any) (err error) {
|
||||
return db.Where(query, args...).Find(m).Error
|
||||
}
|
||||
|
||||
|
@ -201,9 +225,9 @@ func NewPermissionModel() *PermissionModel {
|
|||
}
|
||||
|
||||
type RolePermissionModel struct {
|
||||
Id int64 `json:"id" yaml:"id" xml:"id" gorm:"primaryKey"`
|
||||
Role string `json:"role" yaml:"role" xml:"role" gorm:"size:60"`
|
||||
PermissionId int64 `json:"permission_id" yaml:"permissionId" xml:"permissionId" gorm:"column:permission_id"`
|
||||
Id int64 `json:"id" yaml:"id" xml:"id" gorm:"primaryKey;column:id" comment:"ID"`
|
||||
Role string `json:"role" yaml:"role" xml:"role" gorm:"index;size:60;column:role" comment:"角色" rule:"required"`
|
||||
Permission string `json:"permission" yaml:"permission" xml:"permission" gorm:"size:60;column:permission" comment:"权限" rule:"required"`
|
||||
}
|
||||
|
||||
func (m *RolePermissionModel) TableName() string {
|
||||
|
@ -213,14 +237,14 @@ func (m *RolePermissionModel) TableName() string {
|
|||
func (m *RolePermissionModel) FromValue(x *RolePermission) {
|
||||
m.Id = x.Id
|
||||
m.Role = x.Role
|
||||
m.PermissionId = x.PermissionId
|
||||
m.Permission = x.Permission
|
||||
}
|
||||
|
||||
func (m *RolePermissionModel) ToValue() (x *RolePermission) {
|
||||
x = &RolePermission{}
|
||||
x.Id = m.Id
|
||||
x.Role = m.Role
|
||||
x.PermissionId = m.PermissionId
|
||||
x.Permission = m.Permission
|
||||
return x
|
||||
}
|
||||
|
||||
|
@ -241,14 +265,14 @@ func (m *RolePermissionModel) Delete(db *gorm.DB) (err error) {
|
|||
}
|
||||
|
||||
func (m *RolePermissionModel) Find(db *gorm.DB, pk any) (err error) {
|
||||
return db.Where("role=?", pk).First(m).Error
|
||||
return db.Where("id=?", pk).First(m).Error
|
||||
}
|
||||
|
||||
func (m *RolePermissionModel) FindOne(db *gorm.DB, query any, args ...any) (err error) {
|
||||
func (m *RolePermissionModel) QueryOne(db *gorm.DB, query any, args ...any) (err error) {
|
||||
return db.Where(query, args...).First(m).Error
|
||||
}
|
||||
|
||||
func (m *RolePermissionModel) FindAll(db *gorm.DB, query any, args ...any) (err error) {
|
||||
func (m *RolePermissionModel) QueryAll(db *gorm.DB, query any, args ...any) (err error) {
|
||||
return db.Where(query, args...).Find(m).Error
|
||||
}
|
||||
|
||||
|
@ -257,20 +281,21 @@ func NewRolePermissionModel() *RolePermissionModel {
|
|||
}
|
||||
|
||||
type UserModel struct {
|
||||
Id int64 `json:"id" yaml:"id" xml:"id" gorm:"primaryKey"`
|
||||
CreatedAt int64 `json:"created_at" yaml:"createdAt" xml:"createdAt" gorm:"column:created_at"`
|
||||
UpdatedAt int64 `json:"updated_at" yaml:"updatedAt" xml:"updatedAt" gorm:"column:updated_at"`
|
||||
Uid string `json:"uid" yaml:"uid" xml:"uid" gorm:"index;size:20"`
|
||||
Username string `json:"username" yaml:"username" xml:"username" gorm:"size:20"`
|
||||
Role string `json:"role" yaml:"role" xml:"role" gorm:"size:60"`
|
||||
Admin bool `json:"admin" yaml:"admin" xml:"admin" gorm:"column:admin"`
|
||||
DeptId int64 `json:"dept_id" yaml:"deptId" xml:"deptId" gorm:"not null;default:0"`
|
||||
Tag string `json:"tag" yaml:"tag" xml:"tag" gorm:"size:60"`
|
||||
Password string `json:"password" yaml:"password" xml:"password" gorm:"size:60"`
|
||||
Email string `json:"email" yaml:"email" xml:"email" gorm:"size:60"`
|
||||
Avatar string `json:"avatar" yaml:"avatar" xml:"avatar" gorm:"size:1024"`
|
||||
Gender string `json:"gender" yaml:"gender" xml:"gender" gorm:"size:20;default:man"`
|
||||
Description string `json:"description" yaml:"description" xml:"description" gorm:"size:1024"`
|
||||
Id int64 `json:"id" yaml:"id" xml:"id" gorm:"primaryKey;column:id" comment:"ID"`
|
||||
CreatedAt int64 `json:"created_at" yaml:"createdAt" xml:"createdAt" gorm:"column:created_at" comment:"创建时间" scenarios:"view;export"`
|
||||
UpdatedAt int64 `json:"updated_at" yaml:"updatedAt" xml:"updatedAt" gorm:"index;column:updated_at" comment:"更新时间" scenarios:"view;export"`
|
||||
Uid string `json:"uid" yaml:"uid" xml:"uid" gorm:"index;size:20;column:uid" comment:"用户工号" props:"readonly:update" rule:"required;unique;regexp:^[a-zA-Z0-9]{3,8}$"`
|
||||
Username string `json:"username" yaml:"username" xml:"username" gorm:"size:20;column:username" comment:"用户名称" rule:"required"`
|
||||
Role string `json:"role" yaml:"role" xml:"role" gorm:"size:60;not null;default:'';column:role" comment:"所属角色" format:"role" rule:"required" live:"type:dropdown;url:/role/labels"`
|
||||
Admin bool `json:"admin" yaml:"admin" xml:"admin" gorm:"column:admin" comment:"管理员" scenarios:"create"`
|
||||
Status string `json:"status" yaml:"status" xml:"status" gorm:"size:20;default:normal;column:status" comment:"状态" scenarios:"create,update,list,search" enum:"normal:正常;disable:禁用"`
|
||||
DeptId int64 `json:"dept_id" yaml:"deptId" xml:"deptId" gorm:"not null;default:0;column:dept_id" comment:"所属部门" format:"department" rule:"required" live:"type:dropdown;url:/department/labels"`
|
||||
Tag string `json:"tag" yaml:"tag" xml:"tag" gorm:"size:60;column:tag" comment:"用户标签" scenarios:"list;create;update" live:"type:dropdown;url:/user/tags" dropdown:"created;filterable;default_first"`
|
||||
Password string `json:"password" yaml:"password" xml:"password" gorm:"size:60;column:password" comment:"用户密码" scenarios:"create" rule:"required"`
|
||||
Email string `json:"email" yaml:"email" xml:"email" gorm:"size:60;column:email" comment:"用户邮箱" scenarios:"create;update;view;list;export"`
|
||||
Avatar string `json:"avatar" yaml:"avatar" xml:"avatar" gorm:"size:1024;column:avatar" comment:"用户头像" scenarios:"view"`
|
||||
Gender string `json:"gender" yaml:"gender" xml:"gender" gorm:"size:20;default:man;column:gender" comment:"用户性别" scenarios:"list;create;update;view;export" rule:"required" enum:"man:男;woman:女;other:其他"`
|
||||
Description string `json:"description" yaml:"description" xml:"description" gorm:"size:1024;column:description" comment:"备注说明" scenarios:"create;update;view;export" format:"textarea"`
|
||||
}
|
||||
|
||||
func (m *UserModel) TableName() string {
|
||||
|
@ -285,6 +310,7 @@ func (m *UserModel) FromValue(x *User) {
|
|||
m.Username = x.Username
|
||||
m.Role = x.Role
|
||||
m.Admin = x.Admin
|
||||
m.Status = x.Status
|
||||
m.DeptId = x.DeptId
|
||||
m.Tag = x.Tag
|
||||
m.Password = x.Password
|
||||
|
@ -303,6 +329,7 @@ func (m *UserModel) ToValue() (x *User) {
|
|||
x.Username = m.Username
|
||||
x.Role = m.Role
|
||||
x.Admin = m.Admin
|
||||
x.Status = m.Status
|
||||
x.DeptId = m.DeptId
|
||||
x.Tag = m.Tag
|
||||
x.Password = m.Password
|
||||
|
@ -330,14 +357,14 @@ func (m *UserModel) Delete(db *gorm.DB) (err error) {
|
|||
}
|
||||
|
||||
func (m *UserModel) Find(db *gorm.DB, pk any) (err error) {
|
||||
return db.Where("description=?", pk).First(m).Error
|
||||
return db.Where("id=?", pk).First(m).Error
|
||||
}
|
||||
|
||||
func (m *UserModel) FindOne(db *gorm.DB, query any, args ...any) (err error) {
|
||||
func (m *UserModel) QueryOne(db *gorm.DB, query any, args ...any) (err error) {
|
||||
return db.Where(query, args...).First(m).Error
|
||||
}
|
||||
|
||||
func (m *UserModel) FindAll(db *gorm.DB, query any, args ...any) (err error) {
|
||||
func (m *UserModel) QueryAll(db *gorm.DB, query any, args ...any) (err error) {
|
||||
return db.Where(query, args...).Find(m).Error
|
||||
}
|
||||
|
||||
|
@ -346,12 +373,12 @@ func NewUserModel() *UserModel {
|
|||
}
|
||||
|
||||
type DepartmentModel struct {
|
||||
Id int64 `json:"id" yaml:"id" xml:"id" gorm:"primaryKey"`
|
||||
CreatedAt int64 `json:"created_at" yaml:"createdAt" xml:"createdAt" gorm:"column:created_at"`
|
||||
UpdatedAt int64 `json:"updated_at" yaml:"updatedAt" xml:"updatedAt" gorm:"column:updated_at"`
|
||||
ParentId int64 `json:"parent_id" yaml:"parentId" xml:"parentId" gorm:"column:parent_id"`
|
||||
Name string `json:"name" yaml:"name" xml:"name" gorm:"size:20"`
|
||||
Description string `json:"description" yaml:"description" xml:"description" gorm:"size:1024"`
|
||||
Id int64 `json:"id" yaml:"id" xml:"id" gorm:"primaryKey;column:id" comment:"ID"`
|
||||
CreatedAt int64 `json:"created_at" yaml:"createdAt" xml:"createdAt" gorm:"column:created_at" comment:"创建时间" scenarios:"view;export"`
|
||||
UpdatedAt int64 `json:"updated_at" yaml:"updatedAt" xml:"updatedAt" gorm:"index;column:updated_at" comment:"更新时间" scenarios:"view;export"`
|
||||
ParentId int64 `json:"parent_id" yaml:"parentId" xml:"parentId" gorm:"column:parent_id" comment:"父级部门" format:"department" live:"type:dropdown;url:/department/level-labels"`
|
||||
Name string `json:"name" yaml:"name" xml:"name" gorm:"size:20;column:name" comment:"部门名称" rule:"required"`
|
||||
Description string `json:"description" yaml:"description" xml:"description" gorm:"size:1024;column:description" comment:"备注说明" scenarios:"create;update;view;export;list" format:"textarea"`
|
||||
}
|
||||
|
||||
func (m *DepartmentModel) TableName() string {
|
||||
|
@ -395,17 +422,91 @@ func (m *DepartmentModel) Delete(db *gorm.DB) (err error) {
|
|||
}
|
||||
|
||||
func (m *DepartmentModel) Find(db *gorm.DB, pk any) (err error) {
|
||||
return db.Where("description=?", pk).First(m).Error
|
||||
return db.Where("id=?", pk).First(m).Error
|
||||
}
|
||||
|
||||
func (m *DepartmentModel) FindOne(db *gorm.DB, query any, args ...any) (err error) {
|
||||
func (m *DepartmentModel) QueryOne(db *gorm.DB, query any, args ...any) (err error) {
|
||||
return db.Where(query, args...).First(m).Error
|
||||
}
|
||||
|
||||
func (m *DepartmentModel) FindAll(db *gorm.DB, query any, args ...any) (err error) {
|
||||
func (m *DepartmentModel) QueryAll(db *gorm.DB, query any, args ...any) (err error) {
|
||||
return db.Where(query, args...).Find(m).Error
|
||||
}
|
||||
|
||||
func NewDepartmentModel() *DepartmentModel {
|
||||
return &DepartmentModel{}
|
||||
}
|
||||
|
||||
type LoginModel struct {
|
||||
Id int64 `json:"id" yaml:"id" xml:"id" gorm:"primaryKey;column:id" comment:"ID"`
|
||||
CreatedAt int64 `json:"created_at" yaml:"createdAt" xml:"createdAt" gorm:"column:created_at" comment:"登录时间" scenarios:"list;search;view;export"`
|
||||
Uid string `json:"uid" yaml:"uid" xml:"uid" gorm:"index;size:20;column:uid" comment:"用户" format:"user" props:"readonly:update" rule:"required"`
|
||||
Ip string `json:"ip" yaml:"ip" xml:"ip" gorm:"size:128;column:ip" comment:"登录地址" scenarios:"list;search;view;export"`
|
||||
Browser string `json:"browser" yaml:"browser" xml:"browser" gorm:"size:128;column:browser" comment:"浏览器" scenarios:"list;view;export"`
|
||||
Os string `json:"os" yaml:"os" xml:"os" gorm:"size:128;column:os" comment:"操作系统" scenarios:"list;view;export"`
|
||||
Platform string `json:"platform" yaml:"platform" xml:"platform" gorm:"size:128;column:platform" comment:"系统平台" scenarios:"list;view;export"`
|
||||
AccessToken string `json:"access_token" yaml:"accessToken" xml:"accessToken" gorm:"size:1024;column:access_token" comment:"访问令牌" scenarios:"list;view;export"`
|
||||
UserAgent string `json:"user_agent" yaml:"userAgent" xml:"userAgent" gorm:"size:1024;column:user_agent" comment:"用户代理" scenarios:"list;view;export"`
|
||||
}
|
||||
|
||||
func (m *LoginModel) TableName() string {
|
||||
return "logins"
|
||||
}
|
||||
|
||||
func (m *LoginModel) FromValue(x *Login) {
|
||||
m.Id = x.Id
|
||||
m.CreatedAt = x.CreatedAt
|
||||
m.Uid = x.Uid
|
||||
m.Ip = x.Ip
|
||||
m.Browser = x.Browser
|
||||
m.Os = x.Os
|
||||
m.Platform = x.Platform
|
||||
m.AccessToken = x.AccessToken
|
||||
m.UserAgent = x.UserAgent
|
||||
}
|
||||
|
||||
func (m *LoginModel) ToValue() (x *Login) {
|
||||
x = &Login{}
|
||||
x.Id = m.Id
|
||||
x.CreatedAt = m.CreatedAt
|
||||
x.Uid = m.Uid
|
||||
x.Ip = m.Ip
|
||||
x.Browser = m.Browser
|
||||
x.Os = m.Os
|
||||
x.Platform = m.Platform
|
||||
x.AccessToken = m.AccessToken
|
||||
x.UserAgent = m.UserAgent
|
||||
return x
|
||||
}
|
||||
|
||||
func (m *LoginModel) Create(db *gorm.DB) (err error) {
|
||||
return db.Create(m).Error
|
||||
}
|
||||
|
||||
func (m *LoginModel) UpdateColumn(db *gorm.DB, column string, value any) (err error) {
|
||||
return db.Model(m).UpdateColumn(column, value).Error
|
||||
}
|
||||
|
||||
func (m *LoginModel) Save(db *gorm.DB) (err error) {
|
||||
return db.Save(m).Error
|
||||
}
|
||||
|
||||
func (m *LoginModel) Delete(db *gorm.DB) (err error) {
|
||||
return db.Delete(m).Error
|
||||
}
|
||||
|
||||
func (m *LoginModel) Find(db *gorm.DB, pk any) (err error) {
|
||||
return db.Where("id=?", pk).First(m).Error
|
||||
}
|
||||
|
||||
func (m *LoginModel) QueryOne(db *gorm.DB, query any, args ...any) (err error) {
|
||||
return db.Where(query, args...).First(m).Error
|
||||
}
|
||||
|
||||
func (m *LoginModel) QueryAll(db *gorm.DB, query any, args ...any) (err error) {
|
||||
return db.Where(query, args...).Find(m).Error
|
||||
}
|
||||
|
||||
func NewLoginModel() *LoginModel {
|
||||
return &LoginModel{}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,440 @@
|
|||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-go v1.36.6
|
||||
// protoc v5.29.3
|
||||
// source: system.proto
|
||||
|
||||
package pb
|
||||
|
||||
import (
|
||||
_ "git.nobla.cn/golang/aeus/pkg/proto/rest"
|
||||
_ "github.com/envoyproxy/protoc-gen-validate/validate"
|
||||
_ "google.golang.org/genproto/googleapis/api/annotations"
|
||||
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
|
||||
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
|
||||
_ "google.golang.org/protobuf/types/descriptorpb"
|
||||
reflect "reflect"
|
||||
sync "sync"
|
||||
unsafe "unsafe"
|
||||
)
|
||||
|
||||
const (
|
||||
// Verify that this generated code is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
|
||||
// Verify that runtime/protoimpl is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
|
||||
)
|
||||
|
||||
// Setting 参数设置表
|
||||
type Setting struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"`
|
||||
CreatedAt int64 `protobuf:"varint,2,opt,name=created_at,json=createdAt,proto3" json:"created_at,omitempty"`
|
||||
UpdatedAt int64 `protobuf:"varint,3,opt,name=updated_at,json=updatedAt,proto3" json:"updated_at,omitempty"`
|
||||
Name string `protobuf:"bytes,4,opt,name=name,proto3" json:"name,omitempty"`
|
||||
Value string `protobuf:"bytes,5,opt,name=value,proto3" json:"value,omitempty"`
|
||||
Description string `protobuf:"bytes,6,opt,name=description,proto3" json:"description,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *Setting) Reset() {
|
||||
*x = Setting{}
|
||||
mi := &file_system_proto_msgTypes[0]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *Setting) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*Setting) ProtoMessage() {}
|
||||
|
||||
func (x *Setting) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_system_proto_msgTypes[0]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use Setting.ProtoReflect.Descriptor instead.
|
||||
func (*Setting) Descriptor() ([]byte, []int) {
|
||||
return file_system_proto_rawDescGZIP(), []int{0}
|
||||
}
|
||||
|
||||
func (x *Setting) GetId() int64 {
|
||||
if x != nil {
|
||||
return x.Id
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *Setting) GetCreatedAt() int64 {
|
||||
if x != nil {
|
||||
return x.CreatedAt
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *Setting) GetUpdatedAt() int64 {
|
||||
if x != nil {
|
||||
return x.UpdatedAt
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *Setting) GetName() string {
|
||||
if x != nil {
|
||||
return x.Name
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *Setting) GetValue() string {
|
||||
if x != nil {
|
||||
return x.Value
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *Setting) GetDescription() string {
|
||||
if x != nil {
|
||||
return x.Description
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// Activity 活动记录
|
||||
type Activity struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"`
|
||||
CreatedAt int64 `protobuf:"varint,2,opt,name=created_at,json=createdAt,proto3" json:"created_at,omitempty"`
|
||||
Uid string `protobuf:"bytes,3,opt,name=uid,proto3" json:"uid,omitempty"`
|
||||
Action string `protobuf:"bytes,4,opt,name=action,proto3" json:"action,omitempty"`
|
||||
Module string `protobuf:"bytes,5,opt,name=module,proto3" json:"module,omitempty"`
|
||||
Table string `protobuf:"bytes,6,opt,name=table,proto3" json:"table,omitempty"`
|
||||
Data string `protobuf:"bytes,7,opt,name=data,proto3" json:"data,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *Activity) Reset() {
|
||||
*x = Activity{}
|
||||
mi := &file_system_proto_msgTypes[1]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *Activity) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*Activity) ProtoMessage() {}
|
||||
|
||||
func (x *Activity) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_system_proto_msgTypes[1]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use Activity.ProtoReflect.Descriptor instead.
|
||||
func (*Activity) Descriptor() ([]byte, []int) {
|
||||
return file_system_proto_rawDescGZIP(), []int{1}
|
||||
}
|
||||
|
||||
func (x *Activity) GetId() int64 {
|
||||
if x != nil {
|
||||
return x.Id
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *Activity) GetCreatedAt() int64 {
|
||||
if x != nil {
|
||||
return x.CreatedAt
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *Activity) GetUid() string {
|
||||
if x != nil {
|
||||
return x.Uid
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *Activity) GetAction() string {
|
||||
if x != nil {
|
||||
return x.Action
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *Activity) GetModule() string {
|
||||
if x != nil {
|
||||
return x.Module
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *Activity) GetTable() string {
|
||||
if x != nil {
|
||||
return x.Table
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *Activity) GetData() string {
|
||||
if x != nil {
|
||||
return x.Data
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type SettingItem struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
|
||||
Value string `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *SettingItem) Reset() {
|
||||
*x = SettingItem{}
|
||||
mi := &file_system_proto_msgTypes[2]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *SettingItem) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*SettingItem) ProtoMessage() {}
|
||||
|
||||
func (x *SettingItem) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_system_proto_msgTypes[2]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use SettingItem.ProtoReflect.Descriptor instead.
|
||||
func (*SettingItem) Descriptor() ([]byte, []int) {
|
||||
return file_system_proto_rawDescGZIP(), []int{2}
|
||||
}
|
||||
|
||||
func (x *SettingItem) GetName() string {
|
||||
if x != nil {
|
||||
return x.Name
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *SettingItem) GetValue() string {
|
||||
if x != nil {
|
||||
return x.Value
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type GetSettingRequest struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *GetSettingRequest) Reset() {
|
||||
*x = GetSettingRequest{}
|
||||
mi := &file_system_proto_msgTypes[3]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *GetSettingRequest) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*GetSettingRequest) ProtoMessage() {}
|
||||
|
||||
func (x *GetSettingRequest) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_system_proto_msgTypes[3]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use GetSettingRequest.ProtoReflect.Descriptor instead.
|
||||
func (*GetSettingRequest) Descriptor() ([]byte, []int) {
|
||||
return file_system_proto_rawDescGZIP(), []int{3}
|
||||
}
|
||||
|
||||
type GetSettingResponse struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Data []*SettingItem `protobuf:"bytes,1,rep,name=data,proto3" json:"data,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *GetSettingResponse) Reset() {
|
||||
*x = GetSettingResponse{}
|
||||
mi := &file_system_proto_msgTypes[4]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *GetSettingResponse) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*GetSettingResponse) ProtoMessage() {}
|
||||
|
||||
func (x *GetSettingResponse) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_system_proto_msgTypes[4]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use GetSettingResponse.ProtoReflect.Descriptor instead.
|
||||
func (*GetSettingResponse) Descriptor() ([]byte, []int) {
|
||||
return file_system_proto_rawDescGZIP(), []int{4}
|
||||
}
|
||||
|
||||
func (x *GetSettingResponse) GetData() []*SettingItem {
|
||||
if x != nil {
|
||||
return x.Data
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var File_system_proto protoreflect.FileDescriptor
|
||||
|
||||
const file_system_proto_rawDesc = "" +
|
||||
"\n" +
|
||||
"\fsystem.proto\x12\x06system\x1a\x0faeus/rest.proto\x1a\x17validate/validate.proto\x1a google/protobuf/descriptor.proto\x1a\x1cgoogle/api/annotations.proto\"\xd8\x03\n" +
|
||||
"\aSetting\x12$\n" +
|
||||
"\x02id\x18\x01 \x01(\x03B\x14\xb2\xb9\x19\x10\n" +
|
||||
"\n" +
|
||||
"primaryKey\x12\x02IDR\x02id\x12E\n" +
|
||||
"\n" +
|
||||
"created_at\x18\x02 \x01(\x03B&\xb2\xb9\x19\"\x12\f创建时间\x1a\x12search;view;exportR\tcreatedAt\x12E\n" +
|
||||
"\n" +
|
||||
"updated_at\x18\x03 \x01(\x03B&\xb2\xb9\x19\"\x12\f更新时间\x1a\x12search;view;exportR\tupdatedAt\x12N\n" +
|
||||
"\x04name\x18\x04 \x01(\tB:\xfaB\x04r\x02\x18\x14\xb2\xb9\x19/\n" +
|
||||
"\asize:60\x12\t配置项2\x0freadonly:update:\brequiredR\x04name\x12K\n" +
|
||||
"\x05value\x18\x05 \x01(\tB5\xfaB\x05r\x03\x18\x80\x04\xb2\xb9\x19)\n" +
|
||||
"\bsize:512\x12\t配置值*\btextarea:\brequiredR\x05value\x12l\n" +
|
||||
"\vdescription\x18\x06 \x01(\tBJ\xfaB\x05r\x03\x18\x80\b\xb2\xb9\x19>\n" +
|
||||
"\tsize:1024\x12\f备注说明\x1a\x19create;update;view;export*\btextareaR\vdescription:\x0e\xba\xb9\x19\n" +
|
||||
"\n" +
|
||||
"\bsettings\"\xe2\x05\n" +
|
||||
"\bActivity\x12$\n" +
|
||||
"\x02id\x18\x01 \x01(\x03B\x14\xb2\xb9\x19\x10\n" +
|
||||
"\n" +
|
||||
"primaryKey\x12\x02IDR\x02id\x12L\n" +
|
||||
"\n" +
|
||||
"created_at\x18\x02 \x01(\x03B-\xb2\xb9\x19)\x12\f创建时间\x1a\x19search;search;view;exportR\tcreatedAt\x12W\n" +
|
||||
"\x03uid\x18\x03 \x01(\tBE\xfaB\x06r\x04\x10\x05\x18\x14\xb2\xb9\x198\n" +
|
||||
"\rindex;size:20\x12\x06用户*\x04user2\x0freadonly:update:\brequiredR\x03uid\x12\xc9\x01\n" +
|
||||
"\x06action\x18\x04 \x01(\tB\xb0\x01\xb2\xb9\x19\xab\x01\n" +
|
||||
"!index;size:20;not null;default:''\x12\x06行为\x1a%search;list;create;update;view;export2\rmatch:exactly:\brequiredR>create:新建#198754;update:更新#f09d00;delete:删除#e63757R\x06action\x12h\n" +
|
||||
"\x06module\x18\x05 \x01(\tBP\xb2\xb9\x19L\n" +
|
||||
"\x1bsize:60;not null;default:''\x12\x06模块\x1a%search;list;create;update;view;exportR\x06module\x12_\n" +
|
||||
"\x05table\x18\x06 \x01(\tBI\xb2\xb9\x19E\n" +
|
||||
"\x1bsize:60;not null;default:''\x12\x06模型\x1a\x1elist;create;update;view;exportR\x05table\x12`\n" +
|
||||
"\x04data\x18\a \x01(\tBL\xb2\xb9\x19H\n" +
|
||||
"\x1esize:10240;not null;default:''\x12\x06内容\x1a\x1elist;create;update;view;exportR\x04data:\x10\xba\xb9\x19\f\n" +
|
||||
"\n" +
|
||||
"activities\"7\n" +
|
||||
"\vSettingItem\x12\x12\n" +
|
||||
"\x04name\x18\x01 \x01(\tR\x04name\x12\x14\n" +
|
||||
"\x05value\x18\x02 \x01(\tR\x05value\"\x13\n" +
|
||||
"\x11GetSettingRequest\"=\n" +
|
||||
"\x12GetSettingResponse\x12'\n" +
|
||||
"\x04data\x18\x01 \x03(\v2\x13.system.SettingItemR\x04data2n\n" +
|
||||
"\x0eSettingService\x12\\\n" +
|
||||
"\n" +
|
||||
"GetSetting\x12\x19.system.GetSettingRequest\x1a\x1a.system.GetSettingResponse\"\x17\x82\xd3\xe4\x93\x02\x11\x12\x0f/system/settingB&Z$git.nobla.cn/golang/aeis-admin/pb;pbb\x06proto3"
|
||||
|
||||
var (
|
||||
file_system_proto_rawDescOnce sync.Once
|
||||
file_system_proto_rawDescData []byte
|
||||
)
|
||||
|
||||
func file_system_proto_rawDescGZIP() []byte {
|
||||
file_system_proto_rawDescOnce.Do(func() {
|
||||
file_system_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_system_proto_rawDesc), len(file_system_proto_rawDesc)))
|
||||
})
|
||||
return file_system_proto_rawDescData
|
||||
}
|
||||
|
||||
var file_system_proto_msgTypes = make([]protoimpl.MessageInfo, 5)
|
||||
var file_system_proto_goTypes = []any{
|
||||
(*Setting)(nil), // 0: system.Setting
|
||||
(*Activity)(nil), // 1: system.Activity
|
||||
(*SettingItem)(nil), // 2: system.SettingItem
|
||||
(*GetSettingRequest)(nil), // 3: system.GetSettingRequest
|
||||
(*GetSettingResponse)(nil), // 4: system.GetSettingResponse
|
||||
}
|
||||
var file_system_proto_depIdxs = []int32{
|
||||
2, // 0: system.GetSettingResponse.data:type_name -> system.SettingItem
|
||||
3, // 1: system.SettingService.GetSetting:input_type -> system.GetSettingRequest
|
||||
4, // 2: system.SettingService.GetSetting:output_type -> system.GetSettingResponse
|
||||
2, // [2:3] is the sub-list for method output_type
|
||||
1, // [1:2] is the sub-list for method input_type
|
||||
1, // [1:1] is the sub-list for extension type_name
|
||||
1, // [1:1] is the sub-list for extension extendee
|
||||
0, // [0:1] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_system_proto_init() }
|
||||
func file_system_proto_init() {
|
||||
if File_system_proto != nil {
|
||||
return
|
||||
}
|
||||
type x struct{}
|
||||
out := protoimpl.TypeBuilder{
|
||||
File: protoimpl.DescBuilder{
|
||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||
RawDescriptor: unsafe.Slice(unsafe.StringData(file_system_proto_rawDesc), len(file_system_proto_rawDesc)),
|
||||
NumEnums: 0,
|
||||
NumMessages: 5,
|
||||
NumExtensions: 0,
|
||||
NumServices: 1,
|
||||
},
|
||||
GoTypes: file_system_proto_goTypes,
|
||||
DependencyIndexes: file_system_proto_depIdxs,
|
||||
MessageInfos: file_system_proto_msgTypes,
|
||||
}.Build()
|
||||
File_system_proto = out.File
|
||||
file_system_proto_goTypes = nil
|
||||
file_system_proto_depIdxs = nil
|
||||
}
|
|
@ -0,0 +1,636 @@
|
|||
// Code generated by protoc-gen-validate. DO NOT EDIT.
|
||||
// source: system.proto
|
||||
|
||||
package pb
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/mail"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"google.golang.org/protobuf/types/known/anypb"
|
||||
)
|
||||
|
||||
// ensure the imports are used
|
||||
var (
|
||||
_ = bytes.MinRead
|
||||
_ = errors.New("")
|
||||
_ = fmt.Print
|
||||
_ = utf8.UTFMax
|
||||
_ = (*regexp.Regexp)(nil)
|
||||
_ = (*strings.Reader)(nil)
|
||||
_ = net.IPv4len
|
||||
_ = time.Duration(0)
|
||||
_ = (*url.URL)(nil)
|
||||
_ = (*mail.Address)(nil)
|
||||
_ = anypb.Any{}
|
||||
_ = sort.Sort
|
||||
)
|
||||
|
||||
// Validate checks the field values on Setting with the rules defined in the
|
||||
// proto definition for this message. If any rules are violated, the first
|
||||
// error encountered is returned, or nil if there are no violations.
|
||||
func (m *Setting) Validate() error {
|
||||
return m.validate(false)
|
||||
}
|
||||
|
||||
// ValidateAll checks the field values on Setting with the rules defined in the
|
||||
// proto definition for this message. If any rules are violated, the result is
|
||||
// a list of violation errors wrapped in SettingMultiError, or nil if none found.
|
||||
func (m *Setting) ValidateAll() error {
|
||||
return m.validate(true)
|
||||
}
|
||||
|
||||
func (m *Setting) validate(all bool) error {
|
||||
if m == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
var errors []error
|
||||
|
||||
// no validation rules for Id
|
||||
|
||||
// no validation rules for CreatedAt
|
||||
|
||||
// no validation rules for UpdatedAt
|
||||
|
||||
if utf8.RuneCountInString(m.GetName()) > 20 {
|
||||
err := SettingValidationError{
|
||||
field: "Name",
|
||||
reason: "value length must be at most 20 runes",
|
||||
}
|
||||
if !all {
|
||||
return err
|
||||
}
|
||||
errors = append(errors, err)
|
||||
}
|
||||
|
||||
if utf8.RuneCountInString(m.GetValue()) > 512 {
|
||||
err := SettingValidationError{
|
||||
field: "Value",
|
||||
reason: "value length must be at most 512 runes",
|
||||
}
|
||||
if !all {
|
||||
return err
|
||||
}
|
||||
errors = append(errors, err)
|
||||
}
|
||||
|
||||
if utf8.RuneCountInString(m.GetDescription()) > 1024 {
|
||||
err := SettingValidationError{
|
||||
field: "Description",
|
||||
reason: "value length must be at most 1024 runes",
|
||||
}
|
||||
if !all {
|
||||
return err
|
||||
}
|
||||
errors = append(errors, err)
|
||||
}
|
||||
|
||||
if len(errors) > 0 {
|
||||
return SettingMultiError(errors)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// SettingMultiError is an error wrapping multiple validation errors returned
|
||||
// by Setting.ValidateAll() if the designated constraints aren't met.
|
||||
type SettingMultiError []error
|
||||
|
||||
// Error returns a concatenation of all the error messages it wraps.
|
||||
func (m SettingMultiError) Error() string {
|
||||
msgs := make([]string, 0, len(m))
|
||||
for _, err := range m {
|
||||
msgs = append(msgs, err.Error())
|
||||
}
|
||||
return strings.Join(msgs, "; ")
|
||||
}
|
||||
|
||||
// AllErrors returns a list of validation violation errors.
|
||||
func (m SettingMultiError) AllErrors() []error { return m }
|
||||
|
||||
// SettingValidationError is the validation error returned by Setting.Validate
|
||||
// if the designated constraints aren't met.
|
||||
type SettingValidationError struct {
|
||||
field string
|
||||
reason string
|
||||
cause error
|
||||
key bool
|
||||
}
|
||||
|
||||
// Field function returns field value.
|
||||
func (e SettingValidationError) Field() string { return e.field }
|
||||
|
||||
// Reason function returns reason value.
|
||||
func (e SettingValidationError) Reason() string { return e.reason }
|
||||
|
||||
// Cause function returns cause value.
|
||||
func (e SettingValidationError) Cause() error { return e.cause }
|
||||
|
||||
// Key function returns key value.
|
||||
func (e SettingValidationError) Key() bool { return e.key }
|
||||
|
||||
// ErrorName returns error name.
|
||||
func (e SettingValidationError) ErrorName() string { return "SettingValidationError" }
|
||||
|
||||
// Error satisfies the builtin error interface
|
||||
func (e SettingValidationError) Error() string {
|
||||
cause := ""
|
||||
if e.cause != nil {
|
||||
cause = fmt.Sprintf(" | caused by: %v", e.cause)
|
||||
}
|
||||
|
||||
key := ""
|
||||
if e.key {
|
||||
key = "key for "
|
||||
}
|
||||
|
||||
return fmt.Sprintf(
|
||||
"invalid %sSetting.%s: %s%s",
|
||||
key,
|
||||
e.field,
|
||||
e.reason,
|
||||
cause)
|
||||
}
|
||||
|
||||
var _ error = SettingValidationError{}
|
||||
|
||||
var _ interface {
|
||||
Field() string
|
||||
Reason() string
|
||||
Key() bool
|
||||
Cause() error
|
||||
ErrorName() string
|
||||
} = SettingValidationError{}
|
||||
|
||||
// Validate checks the field values on Activity with the rules defined in the
|
||||
// proto definition for this message. If any rules are violated, the first
|
||||
// error encountered is returned, or nil if there are no violations.
|
||||
func (m *Activity) Validate() error {
|
||||
return m.validate(false)
|
||||
}
|
||||
|
||||
// ValidateAll checks the field values on Activity with the rules defined in
|
||||
// the proto definition for this message. If any rules are violated, the
|
||||
// result is a list of violation errors wrapped in ActivityMultiError, or nil
|
||||
// if none found.
|
||||
func (m *Activity) ValidateAll() error {
|
||||
return m.validate(true)
|
||||
}
|
||||
|
||||
func (m *Activity) validate(all bool) error {
|
||||
if m == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
var errors []error
|
||||
|
||||
// no validation rules for Id
|
||||
|
||||
// no validation rules for CreatedAt
|
||||
|
||||
if l := utf8.RuneCountInString(m.GetUid()); l < 5 || l > 20 {
|
||||
err := ActivityValidationError{
|
||||
field: "Uid",
|
||||
reason: "value length must be between 5 and 20 runes, inclusive",
|
||||
}
|
||||
if !all {
|
||||
return err
|
||||
}
|
||||
errors = append(errors, err)
|
||||
}
|
||||
|
||||
// no validation rules for Action
|
||||
|
||||
// no validation rules for Module
|
||||
|
||||
// no validation rules for Table
|
||||
|
||||
// no validation rules for Data
|
||||
|
||||
if len(errors) > 0 {
|
||||
return ActivityMultiError(errors)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ActivityMultiError is an error wrapping multiple validation errors returned
|
||||
// by Activity.ValidateAll() if the designated constraints aren't met.
|
||||
type ActivityMultiError []error
|
||||
|
||||
// Error returns a concatenation of all the error messages it wraps.
|
||||
func (m ActivityMultiError) Error() string {
|
||||
msgs := make([]string, 0, len(m))
|
||||
for _, err := range m {
|
||||
msgs = append(msgs, err.Error())
|
||||
}
|
||||
return strings.Join(msgs, "; ")
|
||||
}
|
||||
|
||||
// AllErrors returns a list of validation violation errors.
|
||||
func (m ActivityMultiError) AllErrors() []error { return m }
|
||||
|
||||
// ActivityValidationError is the validation error returned by
|
||||
// Activity.Validate if the designated constraints aren't met.
|
||||
type ActivityValidationError struct {
|
||||
field string
|
||||
reason string
|
||||
cause error
|
||||
key bool
|
||||
}
|
||||
|
||||
// Field function returns field value.
|
||||
func (e ActivityValidationError) Field() string { return e.field }
|
||||
|
||||
// Reason function returns reason value.
|
||||
func (e ActivityValidationError) Reason() string { return e.reason }
|
||||
|
||||
// Cause function returns cause value.
|
||||
func (e ActivityValidationError) Cause() error { return e.cause }
|
||||
|
||||
// Key function returns key value.
|
||||
func (e ActivityValidationError) Key() bool { return e.key }
|
||||
|
||||
// ErrorName returns error name.
|
||||
func (e ActivityValidationError) ErrorName() string { return "ActivityValidationError" }
|
||||
|
||||
// Error satisfies the builtin error interface
|
||||
func (e ActivityValidationError) Error() string {
|
||||
cause := ""
|
||||
if e.cause != nil {
|
||||
cause = fmt.Sprintf(" | caused by: %v", e.cause)
|
||||
}
|
||||
|
||||
key := ""
|
||||
if e.key {
|
||||
key = "key for "
|
||||
}
|
||||
|
||||
return fmt.Sprintf(
|
||||
"invalid %sActivity.%s: %s%s",
|
||||
key,
|
||||
e.field,
|
||||
e.reason,
|
||||
cause)
|
||||
}
|
||||
|
||||
var _ error = ActivityValidationError{}
|
||||
|
||||
var _ interface {
|
||||
Field() string
|
||||
Reason() string
|
||||
Key() bool
|
||||
Cause() error
|
||||
ErrorName() string
|
||||
} = ActivityValidationError{}
|
||||
|
||||
// Validate checks the field values on SettingItem with the rules defined in
|
||||
// the proto definition for this message. If any rules are violated, the first
|
||||
// error encountered is returned, or nil if there are no violations.
|
||||
func (m *SettingItem) Validate() error {
|
||||
return m.validate(false)
|
||||
}
|
||||
|
||||
// ValidateAll checks the field values on SettingItem with the rules defined in
|
||||
// the proto definition for this message. If any rules are violated, the
|
||||
// result is a list of violation errors wrapped in SettingItemMultiError, or
|
||||
// nil if none found.
|
||||
func (m *SettingItem) ValidateAll() error {
|
||||
return m.validate(true)
|
||||
}
|
||||
|
||||
func (m *SettingItem) validate(all bool) error {
|
||||
if m == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
var errors []error
|
||||
|
||||
// no validation rules for Name
|
||||
|
||||
// no validation rules for Value
|
||||
|
||||
if len(errors) > 0 {
|
||||
return SettingItemMultiError(errors)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// SettingItemMultiError is an error wrapping multiple validation errors
|
||||
// returned by SettingItem.ValidateAll() if the designated constraints aren't met.
|
||||
type SettingItemMultiError []error
|
||||
|
||||
// Error returns a concatenation of all the error messages it wraps.
|
||||
func (m SettingItemMultiError) Error() string {
|
||||
msgs := make([]string, 0, len(m))
|
||||
for _, err := range m {
|
||||
msgs = append(msgs, err.Error())
|
||||
}
|
||||
return strings.Join(msgs, "; ")
|
||||
}
|
||||
|
||||
// AllErrors returns a list of validation violation errors.
|
||||
func (m SettingItemMultiError) AllErrors() []error { return m }
|
||||
|
||||
// SettingItemValidationError is the validation error returned by
|
||||
// SettingItem.Validate if the designated constraints aren't met.
|
||||
type SettingItemValidationError struct {
|
||||
field string
|
||||
reason string
|
||||
cause error
|
||||
key bool
|
||||
}
|
||||
|
||||
// Field function returns field value.
|
||||
func (e SettingItemValidationError) Field() string { return e.field }
|
||||
|
||||
// Reason function returns reason value.
|
||||
func (e SettingItemValidationError) Reason() string { return e.reason }
|
||||
|
||||
// Cause function returns cause value.
|
||||
func (e SettingItemValidationError) Cause() error { return e.cause }
|
||||
|
||||
// Key function returns key value.
|
||||
func (e SettingItemValidationError) Key() bool { return e.key }
|
||||
|
||||
// ErrorName returns error name.
|
||||
func (e SettingItemValidationError) ErrorName() string { return "SettingItemValidationError" }
|
||||
|
||||
// Error satisfies the builtin error interface
|
||||
func (e SettingItemValidationError) Error() string {
|
||||
cause := ""
|
||||
if e.cause != nil {
|
||||
cause = fmt.Sprintf(" | caused by: %v", e.cause)
|
||||
}
|
||||
|
||||
key := ""
|
||||
if e.key {
|
||||
key = "key for "
|
||||
}
|
||||
|
||||
return fmt.Sprintf(
|
||||
"invalid %sSettingItem.%s: %s%s",
|
||||
key,
|
||||
e.field,
|
||||
e.reason,
|
||||
cause)
|
||||
}
|
||||
|
||||
var _ error = SettingItemValidationError{}
|
||||
|
||||
var _ interface {
|
||||
Field() string
|
||||
Reason() string
|
||||
Key() bool
|
||||
Cause() error
|
||||
ErrorName() string
|
||||
} = SettingItemValidationError{}
|
||||
|
||||
// Validate checks the field values on GetSettingRequest with the rules defined
|
||||
// in the proto definition for this message. If any rules are violated, the
|
||||
// first error encountered is returned, or nil if there are no violations.
|
||||
func (m *GetSettingRequest) Validate() error {
|
||||
return m.validate(false)
|
||||
}
|
||||
|
||||
// ValidateAll checks the field values on GetSettingRequest with the rules
|
||||
// defined in the proto definition for this message. If any rules are
|
||||
// violated, the result is a list of violation errors wrapped in
|
||||
// GetSettingRequestMultiError, or nil if none found.
|
||||
func (m *GetSettingRequest) ValidateAll() error {
|
||||
return m.validate(true)
|
||||
}
|
||||
|
||||
func (m *GetSettingRequest) validate(all bool) error {
|
||||
if m == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
var errors []error
|
||||
|
||||
if len(errors) > 0 {
|
||||
return GetSettingRequestMultiError(errors)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetSettingRequestMultiError is an error wrapping multiple validation errors
|
||||
// returned by GetSettingRequest.ValidateAll() if the designated constraints
|
||||
// aren't met.
|
||||
type GetSettingRequestMultiError []error
|
||||
|
||||
// Error returns a concatenation of all the error messages it wraps.
|
||||
func (m GetSettingRequestMultiError) Error() string {
|
||||
msgs := make([]string, 0, len(m))
|
||||
for _, err := range m {
|
||||
msgs = append(msgs, err.Error())
|
||||
}
|
||||
return strings.Join(msgs, "; ")
|
||||
}
|
||||
|
||||
// AllErrors returns a list of validation violation errors.
|
||||
func (m GetSettingRequestMultiError) AllErrors() []error { return m }
|
||||
|
||||
// GetSettingRequestValidationError is the validation error returned by
|
||||
// GetSettingRequest.Validate if the designated constraints aren't met.
|
||||
type GetSettingRequestValidationError struct {
|
||||
field string
|
||||
reason string
|
||||
cause error
|
||||
key bool
|
||||
}
|
||||
|
||||
// Field function returns field value.
|
||||
func (e GetSettingRequestValidationError) Field() string { return e.field }
|
||||
|
||||
// Reason function returns reason value.
|
||||
func (e GetSettingRequestValidationError) Reason() string { return e.reason }
|
||||
|
||||
// Cause function returns cause value.
|
||||
func (e GetSettingRequestValidationError) Cause() error { return e.cause }
|
||||
|
||||
// Key function returns key value.
|
||||
func (e GetSettingRequestValidationError) Key() bool { return e.key }
|
||||
|
||||
// ErrorName returns error name.
|
||||
func (e GetSettingRequestValidationError) ErrorName() string {
|
||||
return "GetSettingRequestValidationError"
|
||||
}
|
||||
|
||||
// Error satisfies the builtin error interface
|
||||
func (e GetSettingRequestValidationError) Error() string {
|
||||
cause := ""
|
||||
if e.cause != nil {
|
||||
cause = fmt.Sprintf(" | caused by: %v", e.cause)
|
||||
}
|
||||
|
||||
key := ""
|
||||
if e.key {
|
||||
key = "key for "
|
||||
}
|
||||
|
||||
return fmt.Sprintf(
|
||||
"invalid %sGetSettingRequest.%s: %s%s",
|
||||
key,
|
||||
e.field,
|
||||
e.reason,
|
||||
cause)
|
||||
}
|
||||
|
||||
var _ error = GetSettingRequestValidationError{}
|
||||
|
||||
var _ interface {
|
||||
Field() string
|
||||
Reason() string
|
||||
Key() bool
|
||||
Cause() error
|
||||
ErrorName() string
|
||||
} = GetSettingRequestValidationError{}
|
||||
|
||||
// Validate checks the field values on GetSettingResponse with the rules
|
||||
// defined in the proto definition for this message. If any rules are
|
||||
// violated, the first error encountered is returned, or nil if there are no violations.
|
||||
func (m *GetSettingResponse) Validate() error {
|
||||
return m.validate(false)
|
||||
}
|
||||
|
||||
// ValidateAll checks the field values on GetSettingResponse with the rules
|
||||
// defined in the proto definition for this message. If any rules are
|
||||
// violated, the result is a list of violation errors wrapped in
|
||||
// GetSettingResponseMultiError, or nil if none found.
|
||||
func (m *GetSettingResponse) ValidateAll() error {
|
||||
return m.validate(true)
|
||||
}
|
||||
|
||||
func (m *GetSettingResponse) validate(all bool) error {
|
||||
if m == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
var errors []error
|
||||
|
||||
for idx, item := range m.GetData() {
|
||||
_, _ = idx, item
|
||||
|
||||
if all {
|
||||
switch v := interface{}(item).(type) {
|
||||
case interface{ ValidateAll() error }:
|
||||
if err := v.ValidateAll(); err != nil {
|
||||
errors = append(errors, GetSettingResponseValidationError{
|
||||
field: fmt.Sprintf("Data[%v]", idx),
|
||||
reason: "embedded message failed validation",
|
||||
cause: err,
|
||||
})
|
||||
}
|
||||
case interface{ Validate() error }:
|
||||
if err := v.Validate(); err != nil {
|
||||
errors = append(errors, GetSettingResponseValidationError{
|
||||
field: fmt.Sprintf("Data[%v]", idx),
|
||||
reason: "embedded message failed validation",
|
||||
cause: err,
|
||||
})
|
||||
}
|
||||
}
|
||||
} else if v, ok := interface{}(item).(interface{ Validate() error }); ok {
|
||||
if err := v.Validate(); err != nil {
|
||||
return GetSettingResponseValidationError{
|
||||
field: fmt.Sprintf("Data[%v]", idx),
|
||||
reason: "embedded message failed validation",
|
||||
cause: err,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if len(errors) > 0 {
|
||||
return GetSettingResponseMultiError(errors)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetSettingResponseMultiError is an error wrapping multiple validation errors
|
||||
// returned by GetSettingResponse.ValidateAll() if the designated constraints
|
||||
// aren't met.
|
||||
type GetSettingResponseMultiError []error
|
||||
|
||||
// Error returns a concatenation of all the error messages it wraps.
|
||||
func (m GetSettingResponseMultiError) Error() string {
|
||||
msgs := make([]string, 0, len(m))
|
||||
for _, err := range m {
|
||||
msgs = append(msgs, err.Error())
|
||||
}
|
||||
return strings.Join(msgs, "; ")
|
||||
}
|
||||
|
||||
// AllErrors returns a list of validation violation errors.
|
||||
func (m GetSettingResponseMultiError) AllErrors() []error { return m }
|
||||
|
||||
// GetSettingResponseValidationError is the validation error returned by
|
||||
// GetSettingResponse.Validate if the designated constraints aren't met.
|
||||
type GetSettingResponseValidationError struct {
|
||||
field string
|
||||
reason string
|
||||
cause error
|
||||
key bool
|
||||
}
|
||||
|
||||
// Field function returns field value.
|
||||
func (e GetSettingResponseValidationError) Field() string { return e.field }
|
||||
|
||||
// Reason function returns reason value.
|
||||
func (e GetSettingResponseValidationError) Reason() string { return e.reason }
|
||||
|
||||
// Cause function returns cause value.
|
||||
func (e GetSettingResponseValidationError) Cause() error { return e.cause }
|
||||
|
||||
// Key function returns key value.
|
||||
func (e GetSettingResponseValidationError) Key() bool { return e.key }
|
||||
|
||||
// ErrorName returns error name.
|
||||
func (e GetSettingResponseValidationError) ErrorName() string {
|
||||
return "GetSettingResponseValidationError"
|
||||
}
|
||||
|
||||
// Error satisfies the builtin error interface
|
||||
func (e GetSettingResponseValidationError) Error() string {
|
||||
cause := ""
|
||||
if e.cause != nil {
|
||||
cause = fmt.Sprintf(" | caused by: %v", e.cause)
|
||||
}
|
||||
|
||||
key := ""
|
||||
if e.key {
|
||||
key = "key for "
|
||||
}
|
||||
|
||||
return fmt.Sprintf(
|
||||
"invalid %sGetSettingResponse.%s: %s%s",
|
||||
key,
|
||||
e.field,
|
||||
e.reason,
|
||||
cause)
|
||||
}
|
||||
|
||||
var _ error = GetSettingResponseValidationError{}
|
||||
|
||||
var _ interface {
|
||||
Field() string
|
||||
Reason() string
|
||||
Key() bool
|
||||
Cause() error
|
||||
ErrorName() string
|
||||
} = GetSettingResponseValidationError{}
|
|
@ -0,0 +1,59 @@
|
|||
syntax = "proto3";
|
||||
|
||||
package system;
|
||||
|
||||
import "aeus/rest.proto";
|
||||
import "validate/validate.proto";
|
||||
import "google/protobuf/descriptor.proto";
|
||||
import "google/api/annotations.proto";
|
||||
|
||||
option go_package = "git.nobla.cn/golang/aeis-admin/pb;pb";
|
||||
|
||||
|
||||
// Setting 参数设置表
|
||||
message Setting {
|
||||
option (aeus.rest) = {
|
||||
table: "settings"
|
||||
};
|
||||
int64 id = 1 [(aeus.field) = {gorm:"primaryKey",comment:"ID"}];
|
||||
int64 created_at = 2 [(aeus.field)={scenarios:"search;view;export",comment:"创建时间"}];
|
||||
int64 updated_at = 3 [(aeus.field)={scenarios:"search;view;export",comment:"更新时间"}];
|
||||
string name = 4 [(aeus.field)={gorm:"size:60",rule:"required",props:"readonly:update",comment: "配置项"},(validate.rules).string = {max_len: 20}];
|
||||
string value = 5 [(aeus.field)={gorm:"size:512",rule:"required",format:"textarea",comment: "配置值"},(validate.rules).string = {max_len: 512}];
|
||||
string description = 6 [(aeus.field)={gorm:"size:1024",format:"textarea",scenarios:"create;update;view;export",comment: "备注说明"},(validate.rules).string = {max_len: 1024}];
|
||||
}
|
||||
|
||||
|
||||
// Activity 活动记录
|
||||
message Activity {
|
||||
option (aeus.rest) = {
|
||||
table: "activities"
|
||||
};
|
||||
int64 id = 1 [(aeus.field) = {gorm:"primaryKey",comment:"ID"}];
|
||||
int64 created_at = 2 [(aeus.field)={scenarios:"search;search;view;export",comment:"创建时间"}];
|
||||
string uid = 3 [(aeus.field)={gorm:"index;size:20",rule:"required",props:"readonly:update",format:"user",comment: "用户"},(validate.rules).string = {min_len: 5, max_len: 20}];
|
||||
string action = 4 [(aeus.field)={props:"match:exactly",rule:"required",gorm:"index;size:20;not null;default:''",comment:"行为",enum:"create:新建#198754;update:更新#f09d00;delete:删除#e63757",scenarios:"search;list;create;update;view;export"}];
|
||||
string module = 5 [(aeus.field)={gorm:"size:60;not null;default:''",comment:"模块",scenarios:"search;list;create;update;view;export"}];
|
||||
string table = 6 [(aeus.field)={gorm:"size:60;not null;default:''",comment:"模型",scenarios:"list;create;update;view;export"}];
|
||||
string data = 7 [(aeus.field)={gorm:"size:10240;not null;default:''",comment:"内容",scenarios:"list;create;update;view;export"}];
|
||||
}
|
||||
|
||||
|
||||
message SettingItem {
|
||||
string name = 1;
|
||||
string value = 2;
|
||||
}
|
||||
|
||||
message GetSettingRequest{}
|
||||
|
||||
message GetSettingResponse{
|
||||
repeated SettingItem data = 1;
|
||||
}
|
||||
|
||||
service SettingService {
|
||||
rpc GetSetting(GetSettingRequest) returns (GetSettingResponse) {
|
||||
option (google.api.http) = {
|
||||
get: "/system/setting"
|
||||
};
|
||||
}
|
||||
}
|
|
@ -0,0 +1,121 @@
|
|||
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
|
||||
// versions:
|
||||
// - protoc-gen-go-grpc v1.5.1
|
||||
// - protoc v5.29.3
|
||||
// source: system.proto
|
||||
|
||||
package pb
|
||||
|
||||
import (
|
||||
context "context"
|
||||
grpc "google.golang.org/grpc"
|
||||
codes "google.golang.org/grpc/codes"
|
||||
status "google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// This is a compile-time assertion to ensure that this generated file
|
||||
// is compatible with the grpc package it is being compiled against.
|
||||
// Requires gRPC-Go v1.64.0 or later.
|
||||
const _ = grpc.SupportPackageIsVersion9
|
||||
|
||||
const (
|
||||
SettingService_GetSetting_FullMethodName = "/system.SettingService/GetSetting"
|
||||
)
|
||||
|
||||
// SettingServiceClient is the client API for SettingService service.
|
||||
//
|
||||
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
|
||||
type SettingServiceClient interface {
|
||||
GetSetting(ctx context.Context, in *GetSettingRequest, opts ...grpc.CallOption) (*GetSettingResponse, error)
|
||||
}
|
||||
|
||||
type settingServiceClient struct {
|
||||
cc grpc.ClientConnInterface
|
||||
}
|
||||
|
||||
func NewSettingServiceClient(cc grpc.ClientConnInterface) SettingServiceClient {
|
||||
return &settingServiceClient{cc}
|
||||
}
|
||||
|
||||
func (c *settingServiceClient) GetSetting(ctx context.Context, in *GetSettingRequest, opts ...grpc.CallOption) (*GetSettingResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(GetSettingResponse)
|
||||
err := c.cc.Invoke(ctx, SettingService_GetSetting_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// SettingServiceServer is the server API for SettingService service.
|
||||
// All implementations must embed UnimplementedSettingServiceServer
|
||||
// for forward compatibility.
|
||||
type SettingServiceServer interface {
|
||||
GetSetting(context.Context, *GetSettingRequest) (*GetSettingResponse, error)
|
||||
mustEmbedUnimplementedSettingServiceServer()
|
||||
}
|
||||
|
||||
// UnimplementedSettingServiceServer must be embedded to have
|
||||
// forward compatible implementations.
|
||||
//
|
||||
// NOTE: this should be embedded by value instead of pointer to avoid a nil
|
||||
// pointer dereference when methods are called.
|
||||
type UnimplementedSettingServiceServer struct{}
|
||||
|
||||
func (UnimplementedSettingServiceServer) GetSetting(context.Context, *GetSettingRequest) (*GetSettingResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method GetSetting not implemented")
|
||||
}
|
||||
func (UnimplementedSettingServiceServer) mustEmbedUnimplementedSettingServiceServer() {}
|
||||
func (UnimplementedSettingServiceServer) testEmbeddedByValue() {}
|
||||
|
||||
// UnsafeSettingServiceServer may be embedded to opt out of forward compatibility for this service.
|
||||
// Use of this interface is not recommended, as added methods to SettingServiceServer will
|
||||
// result in compilation errors.
|
||||
type UnsafeSettingServiceServer interface {
|
||||
mustEmbedUnimplementedSettingServiceServer()
|
||||
}
|
||||
|
||||
func RegisterSettingServiceServer(s grpc.ServiceRegistrar, srv SettingServiceServer) {
|
||||
// If the following call pancis, it indicates UnimplementedSettingServiceServer was
|
||||
// embedded by pointer and is nil. This will cause panics if an
|
||||
// unimplemented method is ever invoked, so we test this at initialization
|
||||
// time to prevent it from happening at runtime later due to I/O.
|
||||
if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {
|
||||
t.testEmbeddedByValue()
|
||||
}
|
||||
s.RegisterService(&SettingService_ServiceDesc, srv)
|
||||
}
|
||||
|
||||
func _SettingService_GetSetting_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(GetSettingRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(SettingServiceServer).GetSetting(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: SettingService_GetSetting_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(SettingServiceServer).GetSetting(ctx, req.(*GetSettingRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
// SettingService_ServiceDesc is the grpc.ServiceDesc for SettingService service.
|
||||
// It's only intended for direct use with grpc.RegisterService,
|
||||
// and not to be introspected or modified (even as a copy)
|
||||
var SettingService_ServiceDesc = grpc.ServiceDesc{
|
||||
ServiceName: "system.SettingService",
|
||||
HandlerType: (*SettingServiceServer)(nil),
|
||||
Methods: []grpc.MethodDesc{
|
||||
{
|
||||
MethodName: "GetSetting",
|
||||
Handler: _SettingService_GetSetting_Handler,
|
||||
},
|
||||
},
|
||||
Streams: []grpc.StreamDesc{},
|
||||
Metadata: "system.proto",
|
||||
}
|
|
@ -0,0 +1,38 @@
|
|||
// Code generated by protoc-gen-go-aeus. DO NOT EDIT.
|
||||
// source: system.proto
|
||||
// date: 2025-06-22 11:09:05
|
||||
|
||||
package pb
|
||||
|
||||
import (
|
||||
"git.nobla.cn/golang/aeus/transport/http"
|
||||
"context"
|
||||
"git.nobla.cn/golang/aeus/pkg/errors"
|
||||
)
|
||||
|
||||
type SettingServiceHttpServer interface {
|
||||
GetSetting(ctx context.Context, req *GetSettingRequest) (res *GetSettingResponse, err error)
|
||||
}
|
||||
|
||||
func handleSettingServiceGetSetting(s SettingServiceHttpServer) http.HandleFunc {
|
||||
return func(ctx *http.Context) (err error) {
|
||||
req := &GetSettingRequest{}
|
||||
|
||||
if res, err := s.GetSetting(ctx.Context(), req); err != nil {
|
||||
if er, ok := err.(*errors.Error); ok {
|
||||
return ctx.Error(er.Code, er.Message)
|
||||
} else {
|
||||
return ctx.Error(errors.Unavailable, err.Error())
|
||||
}
|
||||
} else {
|
||||
return ctx.Success(res)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func RegisterSettingServiceRouter(hs *http.Server, s SettingServiceHttpServer) {
|
||||
|
||||
// Register handle GetSetting route
|
||||
hs.GET("/system/setting", handleSettingServiceGetSetting(s))
|
||||
|
||||
}
|
|
@ -0,0 +1,142 @@
|
|||
// Code generated by protoc-gen-go-aeus. DO NOT EDIT.
|
||||
// source: system.proto
|
||||
// date: 2025-06-22 11:09:05
|
||||
|
||||
package pb
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type SettingModel struct {
|
||||
Id int64 `json:"id" yaml:"id" xml:"id" gorm:"primaryKey;column:id" comment:"ID"`
|
||||
CreatedAt int64 `json:"created_at" yaml:"createdAt" xml:"createdAt" gorm:"column:created_at" comment:"创建时间" scenarios:"search;view;export"`
|
||||
UpdatedAt int64 `json:"updated_at" yaml:"updatedAt" xml:"updatedAt" gorm:"column:updated_at" comment:"更新时间" scenarios:"search;view;export"`
|
||||
Name string `json:"name" yaml:"name" xml:"name" gorm:"size:60;column:name" comment:"配置项" props:"readonly:update" rule:"required"`
|
||||
Value string `json:"value" yaml:"value" xml:"value" gorm:"size:512;column:value" comment:"配置值" format:"textarea" rule:"required"`
|
||||
Description string `json:"description" yaml:"description" xml:"description" gorm:"size:1024;column:description" comment:"备注说明" scenarios:"create;update;view;export" format:"textarea"`
|
||||
}
|
||||
|
||||
func (m *SettingModel) TableName() string {
|
||||
return "settings"
|
||||
}
|
||||
|
||||
func (m *SettingModel) FromValue(x *Setting) {
|
||||
m.Id = x.Id
|
||||
m.CreatedAt = x.CreatedAt
|
||||
m.UpdatedAt = x.UpdatedAt
|
||||
m.Name = x.Name
|
||||
m.Value = x.Value
|
||||
m.Description = x.Description
|
||||
}
|
||||
|
||||
func (m *SettingModel) ToValue() (x *Setting) {
|
||||
x = &Setting{}
|
||||
x.Id = m.Id
|
||||
x.CreatedAt = m.CreatedAt
|
||||
x.UpdatedAt = m.UpdatedAt
|
||||
x.Name = m.Name
|
||||
x.Value = m.Value
|
||||
x.Description = m.Description
|
||||
return x
|
||||
}
|
||||
|
||||
func (m *SettingModel) Create(db *gorm.DB) (err error) {
|
||||
return db.Create(m).Error
|
||||
}
|
||||
|
||||
func (m *SettingModel) UpdateColumn(db *gorm.DB, column string, value any) (err error) {
|
||||
return db.Model(m).UpdateColumn(column, value).Error
|
||||
}
|
||||
|
||||
func (m *SettingModel) Save(db *gorm.DB) (err error) {
|
||||
return db.Save(m).Error
|
||||
}
|
||||
|
||||
func (m *SettingModel) Delete(db *gorm.DB) (err error) {
|
||||
return db.Delete(m).Error
|
||||
}
|
||||
|
||||
func (m *SettingModel) Find(db *gorm.DB, pk any) (err error) {
|
||||
return db.Where("id=?", pk).First(m).Error
|
||||
}
|
||||
|
||||
func (m *SettingModel) QueryOne(db *gorm.DB, query any, args ...any) (err error) {
|
||||
return db.Where(query, args...).First(m).Error
|
||||
}
|
||||
|
||||
func (m *SettingModel) QueryAll(db *gorm.DB, query any, args ...any) (err error) {
|
||||
return db.Where(query, args...).Find(m).Error
|
||||
}
|
||||
|
||||
func NewSettingModel() *SettingModel {
|
||||
return &SettingModel{}
|
||||
}
|
||||
|
||||
type ActivityModel struct {
|
||||
Id int64 `json:"id" yaml:"id" xml:"id" gorm:"primaryKey;column:id" comment:"ID"`
|
||||
CreatedAt int64 `json:"created_at" yaml:"createdAt" xml:"createdAt" gorm:"column:created_at" comment:"创建时间" scenarios:"search;search;view;export"`
|
||||
Uid string `json:"uid" yaml:"uid" xml:"uid" gorm:"index;size:20;column:uid" comment:"用户" format:"user" props:"readonly:update" rule:"required"`
|
||||
Action string `json:"action" yaml:"action" xml:"action" gorm:"index;size:20;not null;default:'';column:action" comment:"行为" scenarios:"search;list;create;update;view;export" props:"match:exactly" rule:"required" enum:"create:新建#198754;update:更新#f09d00;delete:删除#e63757"`
|
||||
Module string `json:"module" yaml:"module" xml:"module" gorm:"size:60;not null;default:'';column:module" comment:"模块" scenarios:"search;list;create;update;view;export"`
|
||||
Table string `json:"table" yaml:"table" xml:"table" gorm:"size:60;not null;default:'';column:table" comment:"模型" scenarios:"list;create;update;view;export"`
|
||||
Data string `json:"data" yaml:"data" xml:"data" gorm:"size:10240;not null;default:'';column:data" comment:"内容" scenarios:"list;create;update;view;export"`
|
||||
}
|
||||
|
||||
func (m *ActivityModel) TableName() string {
|
||||
return "activities"
|
||||
}
|
||||
|
||||
func (m *ActivityModel) FromValue(x *Activity) {
|
||||
m.Id = x.Id
|
||||
m.CreatedAt = x.CreatedAt
|
||||
m.Uid = x.Uid
|
||||
m.Action = x.Action
|
||||
m.Module = x.Module
|
||||
m.Table = x.Table
|
||||
m.Data = x.Data
|
||||
}
|
||||
|
||||
func (m *ActivityModel) ToValue() (x *Activity) {
|
||||
x = &Activity{}
|
||||
x.Id = m.Id
|
||||
x.CreatedAt = m.CreatedAt
|
||||
x.Uid = m.Uid
|
||||
x.Action = m.Action
|
||||
x.Module = m.Module
|
||||
x.Table = m.Table
|
||||
x.Data = m.Data
|
||||
return x
|
||||
}
|
||||
|
||||
func (m *ActivityModel) Create(db *gorm.DB) (err error) {
|
||||
return db.Create(m).Error
|
||||
}
|
||||
|
||||
func (m *ActivityModel) UpdateColumn(db *gorm.DB, column string, value any) (err error) {
|
||||
return db.Model(m).UpdateColumn(column, value).Error
|
||||
}
|
||||
|
||||
func (m *ActivityModel) Save(db *gorm.DB) (err error) {
|
||||
return db.Save(m).Error
|
||||
}
|
||||
|
||||
func (m *ActivityModel) Delete(db *gorm.DB) (err error) {
|
||||
return db.Delete(m).Error
|
||||
}
|
||||
|
||||
func (m *ActivityModel) Find(db *gorm.DB, pk any) (err error) {
|
||||
return db.Where("id=?", pk).First(m).Error
|
||||
}
|
||||
|
||||
func (m *ActivityModel) QueryOne(db *gorm.DB, query any, args ...any) (err error) {
|
||||
return db.Where(query, args...).First(m).Error
|
||||
}
|
||||
|
||||
func (m *ActivityModel) QueryAll(db *gorm.DB, query any, args ...any) (err error) {
|
||||
return db.Where(query, args...).Find(m).Error
|
||||
}
|
||||
|
||||
func NewActivityModel() *ActivityModel {
|
||||
return &ActivityModel{}
|
||||
}
|
|
@ -0,0 +1,65 @@
|
|||
package aeusadmin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"slices"
|
||||
|
||||
"git.nobla.cn/golang/aeus-admin/internal/logic"
|
||||
"git.nobla.cn/golang/aeus-admin/models"
|
||||
"git.nobla.cn/golang/aeus-admin/types"
|
||||
"git.nobla.cn/golang/aeus/middleware/auth"
|
||||
"git.nobla.cn/golang/aeus/pkg/cache"
|
||||
"git.nobla.cn/golang/aeus/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type PermissionChecker struct {
|
||||
db *gorm.DB
|
||||
user *logic.User
|
||||
role *logic.Role
|
||||
}
|
||||
|
||||
func (p *PermissionChecker) CheckPermission(ctx context.Context, permission string) (err error) {
|
||||
var (
|
||||
uid string
|
||||
ps []string
|
||||
)
|
||||
claims, ok := auth.FromContext(ctx)
|
||||
if !ok {
|
||||
return errors.ErrAccessDenied
|
||||
}
|
||||
if cl, ok := claims.(*types.Claims); ok {
|
||||
if cl.Admin {
|
||||
return
|
||||
} else {
|
||||
var pms []*models.Permission
|
||||
if pms, err = p.role.GetPermissions(ctx, cl.Role); err == nil {
|
||||
for _, pm := range pms {
|
||||
if pm.Permission == permission {
|
||||
return
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return errors.ErrPermissionDenied
|
||||
}
|
||||
}
|
||||
}
|
||||
if uid, err = claims.GetSubject(); err != nil {
|
||||
return
|
||||
}
|
||||
if ps, err = p.user.GetPermissions(ctx, uid); err != nil {
|
||||
return
|
||||
}
|
||||
if !slices.Contains(ps, permission) {
|
||||
err = errors.ErrPermissionDenied
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func NewPermissionChecker(db *gorm.DB, ch cache.Cache) *PermissionChecker {
|
||||
return &PermissionChecker{
|
||||
db: db,
|
||||
user: logic.NewUserLogic(db, ch),
|
||||
role: logic.NewRoleLogic(db, ch),
|
||||
}
|
||||
}
|
|
@ -0,0 +1,30 @@
|
|||
package cfgload
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"encoding/xml"
|
||||
"os"
|
||||
"path"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
// FromFile loads configuration from file
|
||||
func FromFile(filepath string, cfg any) (err error) {
|
||||
var (
|
||||
buf []byte
|
||||
)
|
||||
if buf, err = os.ReadFile(filepath); err != nil {
|
||||
return
|
||||
}
|
||||
ext := path.Ext(filepath)
|
||||
switch ext {
|
||||
case ".json":
|
||||
err = json.Unmarshal(buf, cfg)
|
||||
case ".xml":
|
||||
err = xml.Unmarshal(buf, cfg)
|
||||
case ".yaml", ".yml":
|
||||
err = yaml.Unmarshal(buf, cfg)
|
||||
}
|
||||
return
|
||||
}
|
|
@ -0,0 +1,78 @@
|
|||
package chartjs
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// DataCounter 计数统计, 实现类似Pie 和 Doughnut 之类的图形
|
||||
type DataCounter struct {
|
||||
mutex sync.Mutex
|
||||
legends map[string]*counterValue
|
||||
}
|
||||
|
||||
func (c *DataCounter) Inc(leg string, label string, value float64) {
|
||||
c.mutex.Lock()
|
||||
defer c.mutex.Unlock()
|
||||
v, ok := c.legends[leg]
|
||||
if !ok {
|
||||
v = &counterValue{
|
||||
Label: leg,
|
||||
Values: make(map[string]float64),
|
||||
}
|
||||
c.legends[leg] = v
|
||||
}
|
||||
v.Values[label] += value
|
||||
}
|
||||
|
||||
func (c *DataCounter) Dec(legend string, label string, value float64) {
|
||||
c.mutex.Lock()
|
||||
defer c.mutex.Unlock()
|
||||
v, ok := c.legends[legend]
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if _, ok := v.Values[label]; ok {
|
||||
v.Values[label] -= value
|
||||
}
|
||||
}
|
||||
|
||||
func (c *DataCounter) Data() *CounterData {
|
||||
c.mutex.Lock()
|
||||
defer c.mutex.Unlock()
|
||||
data := &CounterData{
|
||||
Lables: make([]string, 0, 5),
|
||||
Datasets: make([]*CounterValue, 0, len(c.legends)),
|
||||
}
|
||||
for _, row := range c.legends {
|
||||
for k, _ := range row.Values {
|
||||
if !slices.Contains(data.Lables, k) {
|
||||
data.Lables = append(data.Lables, k)
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, row := range c.legends {
|
||||
set := &CounterValue{
|
||||
Label: row.Label,
|
||||
Data: make([]float64, 0, len(data.Lables)),
|
||||
}
|
||||
for _, label := range data.Lables {
|
||||
set.Data = append(set.Data, row.Values[label])
|
||||
}
|
||||
data.Datasets = append(data.Datasets, set)
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
func NewDataCounter(legends ...string) *DataCounter {
|
||||
c := &DataCounter{
|
||||
legends: make(map[string]*counterValue),
|
||||
}
|
||||
for _, legend := range legends {
|
||||
c.legends[legend] = &counterValue{
|
||||
Label: legend,
|
||||
Values: make(map[string]float64),
|
||||
}
|
||||
}
|
||||
return c
|
||||
}
|
|
@ -0,0 +1,46 @@
|
|||
package chartjs
|
||||
|
||||
import "time"
|
||||
|
||||
// TimeSeriesGroup 时间计算数据, 实现类似以时间为维度的折线图
|
||||
type TimeSeriesGroup struct {
|
||||
step string
|
||||
values map[string]*TimeSeries
|
||||
}
|
||||
|
||||
func (g *TimeSeriesGroup) Inc(tm time.Time, key string, value float64) {
|
||||
v, ok := g.values[key]
|
||||
if !ok {
|
||||
v = NewTimeSeries(g.step)
|
||||
g.values[key] = v
|
||||
}
|
||||
v.Inc(tm, value)
|
||||
}
|
||||
|
||||
func (g *TimeSeriesGroup) Dec(tm time.Time, key string, value float64) {
|
||||
v, ok := g.values[key]
|
||||
if !ok {
|
||||
v = NewTimeSeries(g.step)
|
||||
g.values[key] = v
|
||||
}
|
||||
v.Dec(tm, value)
|
||||
}
|
||||
|
||||
// Data 生成chart.js 的图表dataset
|
||||
func (g *TimeSeriesGroup) Data(sts, ets int64) (values []*TimeseriesData) {
|
||||
for key, row := range g.values {
|
||||
data := &TimeseriesData{
|
||||
Label: key,
|
||||
Data: row.Values(sts, ets),
|
||||
}
|
||||
values = append(values, data)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func NewTimeSeriesGroup(step string) *TimeSeriesGroup {
|
||||
return &TimeSeriesGroup{
|
||||
step: step,
|
||||
values: make(map[string]*TimeSeries),
|
||||
}
|
||||
}
|
|
@ -0,0 +1,126 @@
|
|||
package chartjs
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
Minute = "minute"
|
||||
Hour = "hour"
|
||||
Day = "day"
|
||||
Method = "method"
|
||||
)
|
||||
|
||||
// 时间序列值, 实现了按时间进行分组的值计算
|
||||
type TimeSeries struct {
|
||||
mutex sync.Mutex
|
||||
step string
|
||||
values []*TimeseriesValue
|
||||
}
|
||||
|
||||
func (s *TimeSeries) cutTimeSeries(tm time.Time) int64 {
|
||||
switch s.step {
|
||||
case Method:
|
||||
return time.Date(tm.Year(), tm.Month(), 0, 0, 0, 0, 0, time.Local).Unix()
|
||||
case Day:
|
||||
return time.Date(tm.Year(), tm.Month(), tm.Day(), 0, 0, 0, 0, time.Local).Unix()
|
||||
case Hour:
|
||||
return time.Date(tm.Year(), tm.Month(), tm.Day(), tm.Hour(), 0, 0, 0, time.Local).Unix()
|
||||
default:
|
||||
return time.Date(tm.Year(), tm.Month(), tm.Day(), tm.Hour(), tm.Minute(), 0, 0, time.Local).Unix()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *TimeSeries) truncateTime(ts int64) int64 {
|
||||
tm := time.Unix(ts, 0)
|
||||
switch s.step {
|
||||
case Method:
|
||||
return time.Date(tm.Year(), tm.Month(), 0, 0, 0, 0, 0, time.Local).Unix()
|
||||
case Day:
|
||||
return time.Date(tm.Year(), tm.Month(), tm.Day(), 0, 0, 0, 0, time.Local).Unix()
|
||||
case Hour:
|
||||
return time.Date(tm.Year(), tm.Month(), tm.Day(), tm.Hour(), 0, 0, 0, time.Local).Unix()
|
||||
default:
|
||||
return time.Date(tm.Year(), tm.Month(), tm.Day(), tm.Hour(), tm.Minute(), 0, 0, time.Local).Unix()
|
||||
}
|
||||
return tm.Unix()
|
||||
}
|
||||
|
||||
func (s *TimeSeries) nextTimestamp(ts int64) int64 {
|
||||
tm := time.Unix(ts, 0)
|
||||
switch s.step {
|
||||
case Method:
|
||||
return tm.AddDate(0, 1, 0).Unix()
|
||||
case Day:
|
||||
return tm.AddDate(0, 0, 1).Unix()
|
||||
case Hour:
|
||||
return ts + 3600
|
||||
default:
|
||||
return ts + 60
|
||||
}
|
||||
}
|
||||
|
||||
func (s *TimeSeries) Inc(tm time.Time, value float64) {
|
||||
s.mutex.Lock()
|
||||
defer s.mutex.Unlock()
|
||||
ts := s.cutTimeSeries(tm)
|
||||
for _, v := range s.values {
|
||||
if v.Timestamp == ts {
|
||||
v.Value += value
|
||||
return
|
||||
}
|
||||
}
|
||||
s.values = append(s.values, &TimeseriesValue{
|
||||
Timestamp: ts,
|
||||
Value: value,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *TimeSeries) Dec(tm time.Time, value float64) {
|
||||
s.mutex.Lock()
|
||||
defer s.mutex.Unlock()
|
||||
ts := s.cutTimeSeries(tm)
|
||||
for _, v := range s.values {
|
||||
if v.Timestamp == ts {
|
||||
v.Value -= value
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *TimeSeries) Values(sts, ets int64) []*TimeseriesValue {
|
||||
var (
|
||||
nextStamp int64
|
||||
)
|
||||
sts = s.truncateTime(sts)
|
||||
ets = s.truncateTime(ets)
|
||||
series := make([]*TimeseriesValue, 0, len(s.values))
|
||||
nextStamp = sts
|
||||
for _, row := range s.values {
|
||||
for row.Timestamp > nextStamp {
|
||||
series = append(series, &TimeseriesValue{
|
||||
Timestamp: nextStamp,
|
||||
Value: 0,
|
||||
})
|
||||
nextStamp = s.nextTimestamp(nextStamp)
|
||||
}
|
||||
series = append(series, row)
|
||||
nextStamp = s.nextTimestamp(nextStamp)
|
||||
}
|
||||
for ets > nextStamp {
|
||||
series = append(series, &TimeseriesValue{
|
||||
Timestamp: nextStamp,
|
||||
Value: 0,
|
||||
})
|
||||
nextStamp = s.nextTimestamp(nextStamp)
|
||||
}
|
||||
return series
|
||||
}
|
||||
|
||||
func NewTimeSeries(step string) *TimeSeries {
|
||||
return &TimeSeries{
|
||||
step: step,
|
||||
values: make([]*TimeseriesValue, 0, 64),
|
||||
}
|
||||
}
|
|
@ -0,0 +1,66 @@
|
|||
package chartjs
|
||||
|
||||
/*
|
||||
{
|
||||
label: 'My Time Series Data',
|
||||
data: [
|
||||
{ x: '2025-01-01', y: 10 },
|
||||
{ x: '2025-01-02', y: 15 },
|
||||
{ x: '2025-01-03', y: 8 },
|
||||
{ x: '2025-01-04', y: 20 },
|
||||
{ x: '2025-01-05', y: 12 }
|
||||
],
|
||||
borderColor: 'rgb(75, 192, 192)',
|
||||
tension: 0.1
|
||||
}
|
||||
*/
|
||||
|
||||
type TimeseriesValue struct {
|
||||
Timestamp int64 `json:"x"`
|
||||
Value float64 `json:"y"`
|
||||
}
|
||||
|
||||
// TimeseriesData 时间序列的数据
|
||||
type TimeseriesData struct {
|
||||
Label string `json:"label"`
|
||||
Data []*TimeseriesValue `json:"data"`
|
||||
BorderColor string `json:"borderColor,omitempty"`
|
||||
BackgroundColor string `json:"backgroundColor,omitempty"`
|
||||
Tension float64 `json:"tension,omitempty"`
|
||||
Fill bool `json:"fill,omitempty"`
|
||||
}
|
||||
|
||||
/**
|
||||
{
|
||||
labels: labels,
|
||||
datasets: [
|
||||
{
|
||||
label: 'Dataset 1',
|
||||
data: Utils.numbers(NUMBER_CFG),
|
||||
backgroundColor: [
|
||||
Utils.transparentize(Utils.CHART_COLORS.red, 0.5),
|
||||
Utils.transparentize(Utils.CHART_COLORS.orange, 0.5),
|
||||
Utils.transparentize(Utils.CHART_COLORS.yellow, 0.5),
|
||||
Utils.transparentize(Utils.CHART_COLORS.green, 0.5),
|
||||
Utils.transparentize(Utils.CHART_COLORS.blue, 0.5),
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
*/
|
||||
|
||||
type counterValue struct {
|
||||
Label string `json:"label"`
|
||||
Values map[string]float64 `json:"data"`
|
||||
}
|
||||
|
||||
type CounterValue struct {
|
||||
Label string `json:"label"`
|
||||
Data []float64 `json:"data"`
|
||||
BackgroundColor []string `json:"backgroundColor,omitempty"`
|
||||
}
|
||||
|
||||
type CounterData struct {
|
||||
Lables []string `json:"labels"`
|
||||
Datasets []*CounterValue `json:"datasets"`
|
||||
}
|
|
@ -0,0 +1,115 @@
|
|||
package dbcache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"git.nobla.cn/golang/aeus/pkg/cache"
|
||||
"git.nobla.cn/golang/aeus/pkg/errors"
|
||||
"golang.org/x/sync/singleflight"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var singleInstance singleflight.Group
|
||||
|
||||
type (
|
||||
CacheOptions struct {
|
||||
db *gorm.DB
|
||||
cache cache.Cache
|
||||
dependency CacheDependency
|
||||
cacheDuration time.Duration
|
||||
}
|
||||
|
||||
CacheOption func(o *CacheOptions)
|
||||
|
||||
cacheEntry[T any] struct {
|
||||
Value T `json:"v"`
|
||||
CompareValue string `json:"d"`
|
||||
CreatedAt int64 `json:"t"`
|
||||
}
|
||||
)
|
||||
|
||||
func WithDB(db *gorm.DB) CacheOption {
|
||||
return func(o *CacheOptions) {
|
||||
o.db = db
|
||||
}
|
||||
}
|
||||
|
||||
func WithCache(c cache.Cache) CacheOption {
|
||||
return func(o *CacheOptions) {
|
||||
if o != nil {
|
||||
o.cache = c
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func WithCacheDuration(d time.Duration) CacheOption {
|
||||
return func(o *CacheOptions) {
|
||||
if d > 0 {
|
||||
o.cacheDuration = d
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func WithDependency(d CacheDependency) CacheOption {
|
||||
return func(o *CacheOptions) {
|
||||
o.dependency = d
|
||||
}
|
||||
}
|
||||
|
||||
// TryCache 尝试从缓存中获取数据
|
||||
func TryCache[T any](ctx context.Context, key string, f func(tx *gorm.DB) (T, error), cbs ...CacheOption) (result T, err error) {
|
||||
var (
|
||||
none T
|
||||
val any
|
||||
hasDependValue bool
|
||||
dependValue string
|
||||
)
|
||||
opts := &CacheOptions{
|
||||
cache: cache.Default(),
|
||||
cacheDuration: time.Minute * 10,
|
||||
}
|
||||
for _, cb := range cbs {
|
||||
cb(opts)
|
||||
}
|
||||
if opts.db == nil {
|
||||
return none, errors.Format(errors.Unavailable, "db instance unavailable")
|
||||
}
|
||||
//从缓存加载数据
|
||||
entry := &cacheEntry[T]{}
|
||||
if err = opts.cache.Load(ctx, key, entry); err == nil {
|
||||
if time.Now().Unix()-entry.CreatedAt <= 1 {
|
||||
return entry.Value, nil
|
||||
}
|
||||
if opts.dependency == nil {
|
||||
return entry.Value, nil
|
||||
}
|
||||
if dependValue, err = opts.dependency.GetValue(ctx, opts.db); err == nil && dependValue != "" {
|
||||
hasDependValue = true
|
||||
if entry.CompareValue == dependValue {
|
||||
return entry.Value, nil
|
||||
} else {
|
||||
opts.cache.Delete(ctx, key)
|
||||
}
|
||||
}
|
||||
}
|
||||
//从数据库加载数据
|
||||
tx := opts.db.WithContext(ctx)
|
||||
if val, err, _ = singleInstance.Do(key, func() (any, error) {
|
||||
if result, err = f(tx); err == nil {
|
||||
if !hasDependValue && opts.dependency != nil {
|
||||
dependValue, _ = opts.dependency.GetValue(ctx, tx)
|
||||
}
|
||||
opts.cache.Store(ctx, key, &cacheEntry[T]{
|
||||
CompareValue: dependValue,
|
||||
Value: result,
|
||||
CreatedAt: time.Now().Unix(),
|
||||
}, opts.cacheDuration)
|
||||
}
|
||||
return result, err
|
||||
}); err != nil {
|
||||
return none, err
|
||||
} else {
|
||||
return val.(T), err
|
||||
}
|
||||
}
|
|
@ -0,0 +1,29 @@
|
|||
package dbcache
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type CacheDependency interface {
|
||||
GetValue(ctx context.Context, tx *gorm.DB) (value string, err error)
|
||||
}
|
||||
|
||||
type SqlDependency struct {
|
||||
dependSQL string
|
||||
dependArgs []any
|
||||
}
|
||||
|
||||
func (d *SqlDependency) GetValue(ctx context.Context, tx *gorm.DB) (value string, err error) {
|
||||
var dependValue string
|
||||
err = tx.Raw(d.dependSQL, d.dependArgs...).Scan(&dependValue).Error
|
||||
return dependValue, err
|
||||
}
|
||||
|
||||
func NewSqlDependency(dependSQL string, dependArgs ...any) *SqlDependency {
|
||||
return &SqlDependency{
|
||||
dependSQL: dependSQL,
|
||||
dependArgs: dependArgs,
|
||||
}
|
||||
}
|
|
@ -0,0 +1,31 @@
|
|||
package dbdialer
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Dialer open database
|
||||
func Dialer(ctx context.Context, driver string, dsn string, cbs ...Option) (db *gorm.DB, err error) {
|
||||
opts := newOptions(cbs...)
|
||||
|
||||
if opts.cfg == nil {
|
||||
opts.cfg = &gorm.Config{}
|
||||
}
|
||||
opts.cfg.Logger = newLogger(opts.log)
|
||||
switch driver {
|
||||
case mysql.DefaultDriverName:
|
||||
db, err = gorm.Open(mysql.Open(dsn), opts.cfg)
|
||||
case sqlite.DriverName:
|
||||
db, err = gorm.Open(sqlite.Open(dsn), opts.cfg)
|
||||
case "postgres":
|
||||
db, err = gorm.Open(postgres.Open(dsn), opts.cfg)
|
||||
default:
|
||||
err = gorm.ErrNotImplemented
|
||||
}
|
||||
return
|
||||
}
|
|
@ -0,0 +1,83 @@
|
|||
package dbdialer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
logpkg "git.nobla.cn/golang/aeus/pkg/logger"
|
||||
"gorm.io/gorm/logger"
|
||||
"gorm.io/gorm/utils"
|
||||
)
|
||||
|
||||
type Logger struct {
|
||||
LogLevel logger.LogLevel
|
||||
SlowThreshold time.Duration
|
||||
traceStr string
|
||||
traceErrStr string
|
||||
logger logpkg.Logger
|
||||
}
|
||||
|
||||
func (lg *Logger) LogMode(level logger.LogLevel) logger.Interface {
|
||||
lg.LogLevel = level
|
||||
return lg
|
||||
}
|
||||
|
||||
func (lg *Logger) Info(ctx context.Context, s string, i ...interface{}) {
|
||||
if lg.LogLevel >= logger.Info {
|
||||
lg.logger.Info(ctx, s, i...)
|
||||
}
|
||||
}
|
||||
|
||||
func (lg *Logger) Warn(ctx context.Context, s string, i ...interface{}) {
|
||||
if lg.LogLevel >= logger.Warn {
|
||||
lg.logger.Warn(ctx, s, i...)
|
||||
}
|
||||
}
|
||||
|
||||
func (lg *Logger) Error(ctx context.Context, s string, i ...interface{}) {
|
||||
if lg.LogLevel >= logger.Error {
|
||||
lg.logger.Error(ctx, s, i...)
|
||||
}
|
||||
}
|
||||
|
||||
func (lg *Logger) Trace(ctx context.Context, begin time.Time, fc func() (sql string, rowsAffected int64), err error) {
|
||||
if lg.LogLevel <= logger.Silent {
|
||||
return
|
||||
}
|
||||
elapsed := time.Since(begin)
|
||||
switch {
|
||||
case err != nil && lg.LogLevel >= logger.Error && (!errors.Is(err, logger.ErrRecordNotFound)):
|
||||
sql, rows := fc()
|
||||
if rows == -1 {
|
||||
lg.Warn(ctx, lg.traceErrStr, sql, err, float64(elapsed.Nanoseconds())/1e6, "-", utils.FileWithLineNum())
|
||||
} else {
|
||||
lg.Warn(ctx, lg.traceErrStr, sql, err, float64(elapsed.Nanoseconds())/1e6, rows, utils.FileWithLineNum())
|
||||
}
|
||||
case elapsed > lg.SlowThreshold && lg.SlowThreshold != 0 && lg.LogLevel >= logger.Warn:
|
||||
sql, rows := fc()
|
||||
slowLog := fmt.Sprintf("SLOW SQL >= %v", lg.SlowThreshold)
|
||||
if rows == -1 {
|
||||
lg.Warn(ctx, lg.traceErrStr, sql, slowLog, float64(elapsed.Nanoseconds())/1e6, "-", utils.FileWithLineNum())
|
||||
} else {
|
||||
lg.Warn(ctx, lg.traceErrStr, sql, slowLog, float64(elapsed.Nanoseconds())/1e6, rows, utils.FileWithLineNum())
|
||||
}
|
||||
case lg.LogLevel == logger.Info:
|
||||
sql, rows := fc()
|
||||
if rows == -1 {
|
||||
lg.Info(ctx, lg.traceStr, sql, float64(elapsed.Nanoseconds())/1e6, "-", utils.FileWithLineNum())
|
||||
} else {
|
||||
lg.Info(ctx, lg.traceStr, sql, float64(elapsed.Nanoseconds())/1e6, rows, utils.FileWithLineNum())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func newLogger(log logpkg.Logger) *Logger {
|
||||
return &Logger{
|
||||
logger: log,
|
||||
SlowThreshold: time.Second * 10,
|
||||
traceStr: "%s [%.3fms] [rows:%v] in %s",
|
||||
traceErrStr: "%s [%s] [%.3fms] [rows:%v] in %s",
|
||||
}
|
||||
}
|
|
@ -0,0 +1,38 @@
|
|||
package dbdialer
|
||||
|
||||
import (
|
||||
"git.nobla.cn/golang/aeus/pkg/logger"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type (
|
||||
options struct {
|
||||
log logger.Logger
|
||||
cfg *gorm.Config
|
||||
}
|
||||
|
||||
Option func(o *options)
|
||||
)
|
||||
|
||||
func WithConfig(cfg *gorm.Config) Option {
|
||||
return func(o *options) {
|
||||
o.cfg = cfg
|
||||
}
|
||||
}
|
||||
|
||||
func WithLogger(log logger.Logger) Option {
|
||||
return func(o *options) {
|
||||
o.log = log
|
||||
}
|
||||
}
|
||||
|
||||
func newOptions(opts ...Option) *options {
|
||||
o := &options{
|
||||
cfg: &gorm.Config{},
|
||||
log: logger.Default(),
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt(o)
|
||||
}
|
||||
return o
|
||||
}
|
|
@ -0,0 +1,42 @@
|
|||
package tokenize
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"git.nobla.cn/golang/aeus/pkg/cache"
|
||||
"git.nobla.cn/golang/aeus/pkg/errors"
|
||||
)
|
||||
|
||||
// Tokenize 实现简单的session管理, 结合AuthService和JWT middleware可以实现登录和登出等操作
|
||||
type Tokenize struct {
|
||||
cache cache.Cache
|
||||
}
|
||||
|
||||
func (t *Tokenize) buildKey(token string) string {
|
||||
return "user:session:" + token
|
||||
}
|
||||
|
||||
func (t *Tokenize) Put(ctx context.Context, token string, ttl int64) error {
|
||||
return t.cache.Store(ctx, t.buildKey(token), token, time.Second*time.Duration(ttl))
|
||||
}
|
||||
|
||||
func (t *Tokenize) Del(ctx context.Context, token string) error {
|
||||
return t.cache.Delete(ctx, t.buildKey(token))
|
||||
}
|
||||
|
||||
func (t *Tokenize) Validate(ctx context.Context, token string) (err error) {
|
||||
var ok bool
|
||||
if ok, err = t.cache.Exists(ctx, t.buildKey(token)); err == nil {
|
||||
if !ok {
|
||||
return errors.ErrAccessDenied
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func New(c cache.Cache) *Tokenize {
|
||||
return &Tokenize{
|
||||
cache: c,
|
||||
}
|
||||
}
|
463
server.go
463
server.go
|
@ -2,64 +2,110 @@ package aeusadmin
|
|||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"html/template"
|
||||
httpkg "net/http"
|
||||
"os"
|
||||
"path"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.nobla.cn/golang/aeus-admin/defaults"
|
||||
"git.nobla.cn/golang/aeus-admin/migrate"
|
||||
"git.nobla.cn/golang/aeus-admin/models"
|
||||
"git.nobla.cn/golang/aeus-admin/pkg/dbcache"
|
||||
adminTypes "git.nobla.cn/golang/aeus-admin/types"
|
||||
"git.nobla.cn/golang/aeus/middleware/auth"
|
||||
"git.nobla.cn/golang/aeus/pkg/errors"
|
||||
"git.nobla.cn/golang/aeus/pkg/pool"
|
||||
"git.nobla.cn/golang/aeus/transport/http"
|
||||
"git.nobla.cn/golang/rest"
|
||||
"git.nobla.cn/golang/rest/inflector"
|
||||
"git.nobla.cn/golang/rest/types"
|
||||
restTypes "git.nobla.cn/golang/rest/types"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// getModels 获取预定义的模型列表
|
||||
func getModels() []any {
|
||||
return []any{
|
||||
&models.User{},
|
||||
&models.Role{},
|
||||
&models.Menu{},
|
||||
&models.Department{},
|
||||
&models.Role{},
|
||||
&models.User{},
|
||||
&models.Menu{},
|
||||
&models.Login{},
|
||||
&models.Permission{},
|
||||
&models.RolePermission{},
|
||||
&models.Setting{},
|
||||
&models.Activity{},
|
||||
}
|
||||
}
|
||||
|
||||
// checkModelMenu 检查模型菜单
|
||||
func checkModelMenu(db *gorm.DB, viewPath string, model *rest.Model, translate Translate) (value *models.Menu, err error) {
|
||||
menuName := inflector.Camelize(model.Naming().ModuleName) + inflector.Camelize(model.Naming().Singular)
|
||||
value = &models.Menu{}
|
||||
if err = db.Where("name = ?", menuName).First(value).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
value.Name = menuName
|
||||
value.ParentId = 0
|
||||
value.ViewPath = path.Join(viewPath, model.ModuleName(), model.Naming().Singular, "Index.vue")
|
||||
value.Label = inflector.Camel2words(model.Naming().Pluralize)
|
||||
if translate != nil {
|
||||
value.Label = translate.Menu(model, value.Label)
|
||||
func checkModelMenu(db *gorm.DB, viewPath string, apiPrefix string, model *rest.Model, translate Translate) (value *models.Menu, err error) {
|
||||
refVal := reflect.New(model.Value().Type()).Interface()
|
||||
if v, ok := refVal.(adminTypes.MenuModel); ok {
|
||||
row := v.GetMenu()
|
||||
value = &models.Menu{}
|
||||
if row.Name == "" {
|
||||
row.Name = inflector.Camelize(model.Naming().ModuleName) + inflector.Camelize(model.Naming().Singular)
|
||||
}
|
||||
if err = db.Where("name = ?", row.Name).First(value).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
if row.Parent != "" {
|
||||
value.Parent = row.Parent
|
||||
}
|
||||
value.Name = row.Name
|
||||
value.Hidden = row.Hidden
|
||||
value.Icon = row.Icon
|
||||
value.Label = row.Label
|
||||
value.Uri = row.Uri
|
||||
value.ViewPath = row.ViewPath
|
||||
if value.Label == "" {
|
||||
value.Label = inflector.Camel2words(model.Naming().Pluralize)
|
||||
if translate != nil {
|
||||
value.Label = translate.Menu(model, value.Label)
|
||||
}
|
||||
}
|
||||
if value.Uri == "" {
|
||||
value.Uri = strings.TrimPrefix(model.Uri(types.ScenarioList), apiPrefix)
|
||||
}
|
||||
if value.ViewPath == "" {
|
||||
value.ViewPath = path.Join(viewPath, model.ModuleName(), model.Naming().Singular, "Index.vue")
|
||||
}
|
||||
err = db.Create(value).Error
|
||||
}
|
||||
}
|
||||
} else {
|
||||
menuName := inflector.Camelize(model.Naming().ModuleName) + inflector.Camelize(model.Naming().Singular)
|
||||
value = &models.Menu{}
|
||||
if err = db.Where("name = ?", menuName).First(value).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
value.Name = menuName
|
||||
value.Parent = ""
|
||||
value.Label = inflector.Camel2words(model.Naming().Pluralize)
|
||||
if translate != nil {
|
||||
value.Label = translate.Menu(model, value.Label)
|
||||
}
|
||||
value.Uri = strings.TrimPrefix(model.Uri(types.ScenarioList), apiPrefix)
|
||||
value.ViewPath = path.Join(viewPath, model.ModuleName(), model.Naming().Singular, "Index.vue")
|
||||
err = db.Create(value).Error
|
||||
}
|
||||
value.Uri = model.Uri(types.ScenarioList)
|
||||
err = db.Create(value).Error
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// checkModelPermission 检查模型权限是否写入到数据库
|
||||
func checkModelPermission(db *gorm.DB, menuId int64, scene string, model *rest.Model, translate Translate) (permissionModel *models.Permission, err error) {
|
||||
func checkModelPermission(db *gorm.DB, menuName string, scene string, model *rest.Model, translate Translate) (permissionModel *models.Permission, err error) {
|
||||
permissionModel = &models.Permission{}
|
||||
permission := model.Permission(scene)
|
||||
if err = db.Where("permission = ?", permission).First(permissionModel).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
permissionModel.MenuId = menuId
|
||||
permissionModel.Label = scene
|
||||
if translate != nil {
|
||||
permissionModel.Label = translate.Permission(model, scene, permissionModel.Label)
|
||||
}
|
||||
permissionModel.Permission = permission
|
||||
err = db.Create(permissionModel).Error
|
||||
}
|
||||
label := scene
|
||||
if translate != nil {
|
||||
label = translate.Permission(model, scene, label)
|
||||
}
|
||||
permissionModel, err = migrate.Permission(db, menuName, permission, label)
|
||||
return
|
||||
}
|
||||
|
||||
|
@ -69,13 +115,22 @@ func checkModel(opts *options, model *rest.Model) (err error) {
|
|||
menuModel *models.Menu
|
||||
)
|
||||
tx := opts.db.Begin()
|
||||
if menuModel, err = checkModelMenu(tx, opts.viewPath, model, opts.translate); err != nil {
|
||||
if menuModel, err = checkModelMenu(tx, opts.viewPrefix, opts.apiPrefix, model, opts.translate); err != nil {
|
||||
tx.Rollback()
|
||||
return
|
||||
}
|
||||
for _, s := range defaultScenarios {
|
||||
if model.HasScenario(s) {
|
||||
if _, err = checkModelPermission(tx, menuModel.Id, s, model, opts.translate); err != nil {
|
||||
if _, err = checkModelPermission(tx, menuModel.Name, s, model, opts.translate); err != nil {
|
||||
tx.Rollback()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
modelValue := reflect.New(model.Value().Type()).Interface()
|
||||
if v, ok := modelValue.(adminTypes.PerrmissionModule); ok {
|
||||
for k, v := range v.ModelPermissions() {
|
||||
if _, err = migrate.Permission(tx, menuModel.Name, k, v); err != nil {
|
||||
tx.Rollback()
|
||||
return
|
||||
}
|
||||
|
@ -85,6 +140,71 @@ func checkModel(opts *options, model *rest.Model) (err error) {
|
|||
return
|
||||
}
|
||||
|
||||
// generateVueFile 生成Vue文件
|
||||
func generateVueFile(prefix string, apiPrefix string, mv *rest.Model) (err error) {
|
||||
refVal := reflect.New(mv.Value().Type()).Interface()
|
||||
if v, ok := refVal.(adminTypes.MenuModel); ok {
|
||||
instance := v.GetMenu()
|
||||
if instance != nil {
|
||||
if instance.Hidden {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
filename := path.Join(prefix, mv.Naming().ModuleName, mv.Naming().Singular, "Index.vue")
|
||||
if _, err = os.Stat(filename); err == nil {
|
||||
return
|
||||
}
|
||||
dirname := path.Dir(filename)
|
||||
if _, err = os.Stat(dirname); err != nil {
|
||||
if err = os.MkdirAll(dirname, os.ModePerm); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
var (
|
||||
editable bool
|
||||
temp *template.Template
|
||||
)
|
||||
if temp, err = template.New("vue").Parse(vueTemplate); err != nil {
|
||||
return
|
||||
}
|
||||
permissions := make(map[string]string)
|
||||
for _, s := range defaultScenarios {
|
||||
if mv.HasScenario(s) {
|
||||
if s == types.ScenarioCreate || s == types.ScenarioUpdate {
|
||||
editable = true
|
||||
}
|
||||
permissions[s] = mv.Permission(s)
|
||||
}
|
||||
}
|
||||
data := &vueTemplateData{
|
||||
ModuleName: mv.ModuleName(),
|
||||
TableName: mv.TableName(),
|
||||
Permissions: permissions,
|
||||
Readonly: !editable,
|
||||
ApiPrefix: strings.TrimPrefix(apiPrefix, "/"),
|
||||
}
|
||||
writer := pool.GetBuffer()
|
||||
defer pool.PutBuffer(writer)
|
||||
if err = temp.Execute(writer, data); err != nil {
|
||||
return
|
||||
}
|
||||
return os.WriteFile(filename, writer.Bytes(), 0644)
|
||||
}
|
||||
|
||||
// restValueLookup 特殊字段获取方式
|
||||
func restValueLookup(column string, w httpkg.ResponseWriter, r *httpkg.Request) string {
|
||||
switch column {
|
||||
case "user":
|
||||
// 从授权信息里面获取用户的ID
|
||||
if t, ok := auth.FromContext(r.Context()); ok {
|
||||
uid, _ := t.GetSubject()
|
||||
return uid
|
||||
}
|
||||
}
|
||||
return r.Header.Get(column)
|
||||
}
|
||||
|
||||
// initREST 初始化REST模块
|
||||
func initREST(ctx context.Context, o *options) (err error) {
|
||||
tx := o.db
|
||||
|
@ -94,6 +214,10 @@ func initREST(ctx context.Context, o *options) (err error) {
|
|||
opts := make([]rest.Option, 0)
|
||||
opts = append(opts, o.restOpts...)
|
||||
opts = append(opts, rest.WithDB(tx))
|
||||
opts = append(opts, rest.WithValueLookup(restValueLookup))
|
||||
if o.apiPrefix != "" {
|
||||
opts = append(opts, rest.WithUriPrefix(o.apiPrefix))
|
||||
}
|
||||
if err = rest.Init(opts...); err != nil {
|
||||
return
|
||||
}
|
||||
|
@ -104,30 +228,283 @@ func initREST(ctx context.Context, o *options) (err error) {
|
|||
}
|
||||
|
||||
// initRBAC 初始化权限控制, 用于生成角色权限相关的信息
|
||||
func initRBAC(ctx context.Context, o *options) (err error) {
|
||||
func initModels(ctx context.Context, o *options) (err error) {
|
||||
var mv *rest.Model
|
||||
for _, v := range getModels() {
|
||||
if mv, err = rest.AutoMigrate(ctx, v); err != nil {
|
||||
moduleName := o.moduleName
|
||||
if mm, ok := v.(adminTypes.ModuleModel); ok {
|
||||
moduleName = mm.ModuleName()
|
||||
}
|
||||
if mv, err = rest.AutoMigrate(ctx, v, rest.WithModuleName(moduleName)); err != nil {
|
||||
return
|
||||
} else {
|
||||
if err = checkModel(o, mv); err != nil {
|
||||
return
|
||||
}
|
||||
if o.vuePath != "" {
|
||||
if err = generateVueFile(o.vuePath, o.apiPrefix, mv); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func registerRESTRoute(domain string, db *gorm.DB, hs *http.Server) {
|
||||
handleListSchemas := func(ctx *http.Context) (err error) {
|
||||
var (
|
||||
schemas []*restTypes.Schema
|
||||
)
|
||||
scenario := ctx.Request().URL.Query().Get("scenario")
|
||||
if scenario == "" {
|
||||
schemas, err = dbcache.TryCache(
|
||||
ctx.Request().Context(),
|
||||
fmt.Sprintf("rest:schems:%s:%s", ctx.Param("module"), ctx.Param("table")),
|
||||
func(tx *gorm.DB) ([]*restTypes.Schema, error) {
|
||||
return rest.GetSchemas(
|
||||
ctx.Request().Context(),
|
||||
tx,
|
||||
"",
|
||||
ctx.Param("module"),
|
||||
ctx.Param("table"),
|
||||
)
|
||||
},
|
||||
dbcache.WithDB(db),
|
||||
dbcache.WithDependency(dbcache.NewSqlDependency("SELECT MAX(`updated_at`) FROM `schemas`")),
|
||||
)
|
||||
} else {
|
||||
schemas, err = dbcache.TryCache(
|
||||
ctx.Request().Context(),
|
||||
fmt.Sprintf("rest:schems:%s:%s", ctx.Param("module"), ctx.Param("table")),
|
||||
func(tx *gorm.DB) ([]*restTypes.Schema, error) {
|
||||
return rest.VisibleSchemas(
|
||||
ctx.Request().Context(),
|
||||
db.WithContext(ctx.Request().Context()),
|
||||
"",
|
||||
ctx.Param("module"),
|
||||
ctx.Param("table"),
|
||||
scenario,
|
||||
)
|
||||
},
|
||||
dbcache.WithDB(db),
|
||||
dbcache.WithDependency(dbcache.NewSqlDependency("SELECT MAX(`updated_at`) FROM `schemas`")),
|
||||
)
|
||||
}
|
||||
if err != nil {
|
||||
return ctx.Error(errors.NotFound, err.Error())
|
||||
} else {
|
||||
return ctx.Success(schemas)
|
||||
}
|
||||
}
|
||||
|
||||
handleUpdateSchemas := func(ctx *http.Context) (err error) {
|
||||
schemas := make([]*restTypes.Schema, 0)
|
||||
if err = ctx.Bind(&schemas); err != nil {
|
||||
return ctx.Error(errors.Invalid, err.Error())
|
||||
}
|
||||
for i := range schemas {
|
||||
schemas[i].Domain = domain
|
||||
}
|
||||
if err = db.WithContext(ctx.Request().Context()).Transaction(func(tx *gorm.DB) (errTx error) {
|
||||
for _, row := range schemas {
|
||||
if errTx = tx.Save(row).Error; errTx != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
return
|
||||
}); err == nil {
|
||||
return ctx.Success(map[string]interface{}{
|
||||
"count": len(schemas),
|
||||
"state": "success",
|
||||
})
|
||||
} else {
|
||||
return ctx.Error(errors.Unavailable, err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
handleDeleteSchema := func(ctx *http.Context) (err error) {
|
||||
id, _ := strconv.Atoi(ctx.Param("id"))
|
||||
model := &restTypes.Schema{Id: uint64(id)}
|
||||
if err = db.WithContext(ctx.Request().Context()).Delete(model).Error; err == nil {
|
||||
return ctx.Success(map[string]any{
|
||||
"id": id,
|
||||
})
|
||||
} else {
|
||||
return ctx.Error(errors.Unavailable, err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
handleKeyValues := func(ctx *http.Context) (err error) {
|
||||
var (
|
||||
dbDependency dbcache.CacheDependency
|
||||
pairs []*restTypes.TypeValue[any]
|
||||
modelValue any
|
||||
)
|
||||
moduleName := ctx.Param("module")
|
||||
tableName := ctx.Param("table")
|
||||
entities := rest.GetModels()
|
||||
for _, entry := range entities {
|
||||
if entry.ModuleName() == moduleName && entry.TableName() == tableName {
|
||||
modelValue = reflect.New(entry.Value().Type()).Interface()
|
||||
for _, field := range entry.Fields() {
|
||||
if field.AutoUpdateTime > 0 {
|
||||
dbDependency = dbcache.NewSqlDependency(fmt.Sprintf("SELECT MAX(`%s`) FROM `%s`", field.DBName, entry.TableName()))
|
||||
break
|
||||
}
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
if modelValue == nil {
|
||||
return ctx.Error(errors.NotFound, "model not found")
|
||||
}
|
||||
labelColumn := ctx.Param("label")
|
||||
valueColumn := ctx.Param("value")
|
||||
opts := make([]dbcache.CacheOption, 0, 4)
|
||||
opts = append(opts, dbcache.WithDB(db))
|
||||
if dbDependency != nil {
|
||||
opts = append(opts, dbcache.WithCacheDuration(time.Minute*30))
|
||||
opts = append(opts, dbcache.WithDependency(dbDependency))
|
||||
} else {
|
||||
opts = append(opts, dbcache.WithCacheDuration(time.Minute))
|
||||
}
|
||||
if pairs, err = dbcache.TryCache(ctx.Context(), fmt.Sprintf("rest:kvpairs:%s:%s:%s:%s", moduleName, tableName, labelColumn, valueColumn), func(tx *gorm.DB) ([]*restTypes.TypeValue[any], error) {
|
||||
return rest.ModelTypes[any](ctx.Context(), db, modelValue, "", labelColumn, valueColumn)
|
||||
}, opts...); err == nil {
|
||||
return ctx.Success(pairs)
|
||||
} else {
|
||||
return ctx.Error(errors.Unavailable, err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
handleTierPairs := func(ctx *http.Context) (err error) {
|
||||
var (
|
||||
dbDependency dbcache.CacheDependency
|
||||
pairs []*restTypes.TierValue[string]
|
||||
modelValue any
|
||||
)
|
||||
moduleName := ctx.Param("module")
|
||||
tableName := ctx.Param("table")
|
||||
entities := rest.GetModels()
|
||||
for _, entry := range entities {
|
||||
if entry.ModuleName() == moduleName && entry.TableName() == tableName {
|
||||
// 权限控制
|
||||
if err = entry.HasPermission(ctx.Context(), entry.Permission(restTypes.ScenarioList)); err != nil {
|
||||
return ctx.Error(errors.AccessDenied, err.Error())
|
||||
}
|
||||
modelValue = reflect.New(entry.Value().Type()).Interface()
|
||||
for _, field := range entry.Fields() {
|
||||
if field.AutoUpdateTime > 0 {
|
||||
dbDependency = dbcache.NewSqlDependency(fmt.Sprintf("SELECT MAX(`%s`) FROM `%s`", field.DBName, entry.TableName()))
|
||||
break
|
||||
}
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
if modelValue == nil {
|
||||
return ctx.Error(errors.NotFound, "model not found")
|
||||
}
|
||||
parentColumn := ctx.Param("parent")
|
||||
labelColumn := ctx.Param("label")
|
||||
valueColumn := ctx.Param("value")
|
||||
opts := make([]dbcache.CacheOption, 0, 4)
|
||||
opts = append(opts, dbcache.WithDB(db))
|
||||
if dbDependency != nil {
|
||||
opts = append(opts, dbcache.WithCacheDuration(time.Minute*30))
|
||||
opts = append(opts, dbcache.WithDependency(dbDependency))
|
||||
} else {
|
||||
opts = append(opts, dbcache.WithCacheDuration(time.Minute))
|
||||
}
|
||||
if pairs, err = dbcache.TryCache(ctx.Context(), fmt.Sprintf("rest:tierpairs:%s:%s:%s:%s", moduleName, tableName, labelColumn, valueColumn), func(tx *gorm.DB) ([]*restTypes.TierValue[string], error) {
|
||||
return rest.ModelTiers[string](ctx.Context(), db, modelValue, "", parentColumn, labelColumn, valueColumn)
|
||||
}, opts...); err == nil {
|
||||
return ctx.Success(pairs)
|
||||
} else {
|
||||
return ctx.Error(errors.Unavailable, err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
handleNumberTierPairs := func(ctx *http.Context) (err error) {
|
||||
var (
|
||||
dbDependency dbcache.CacheDependency
|
||||
pairs []*restTypes.TierValue[int64]
|
||||
modelValue any
|
||||
)
|
||||
moduleName := ctx.Param("module")
|
||||
tableName := ctx.Param("table")
|
||||
entities := rest.GetModels()
|
||||
for _, entry := range entities {
|
||||
if entry.ModuleName() == moduleName && entry.TableName() == tableName {
|
||||
// 权限控制
|
||||
if err = entry.HasPermission(ctx.Context(), entry.Permission(restTypes.ScenarioList)); err != nil {
|
||||
return ctx.Error(errors.AccessDenied, err.Error())
|
||||
}
|
||||
modelValue = reflect.New(entry.Value().Type()).Interface()
|
||||
for _, field := range entry.Fields() {
|
||||
if field.AutoUpdateTime > 0 {
|
||||
dbDependency = dbcache.NewSqlDependency(fmt.Sprintf("SELECT MAX(`%s`) FROM `%s`", field.DBName, entry.TableName()))
|
||||
break
|
||||
}
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
if modelValue == nil {
|
||||
return ctx.Error(errors.NotFound, "model not found")
|
||||
}
|
||||
parentColumn := ctx.Param("parent")
|
||||
labelColumn := ctx.Param("label")
|
||||
valueColumn := ctx.Param("value")
|
||||
opts := make([]dbcache.CacheOption, 0, 4)
|
||||
opts = append(opts, dbcache.WithDB(db))
|
||||
if dbDependency != nil {
|
||||
opts = append(opts, dbcache.WithCacheDuration(time.Minute*30))
|
||||
opts = append(opts, dbcache.WithDependency(dbDependency))
|
||||
} else {
|
||||
opts = append(opts, dbcache.WithCacheDuration(time.Minute))
|
||||
}
|
||||
if pairs, err = dbcache.TryCache(ctx.Context(), fmt.Sprintf("rest:tierpairs:%s:%s:%s:%s", moduleName, tableName, labelColumn, valueColumn), func(tx *gorm.DB) ([]*restTypes.TierValue[int64], error) {
|
||||
return rest.ModelTiers[int64](ctx.Context(), db, modelValue, "", parentColumn, labelColumn, valueColumn)
|
||||
}, opts...); err == nil {
|
||||
return ctx.Success(pairs)
|
||||
} else {
|
||||
return ctx.Error(errors.Unavailable, err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
hs.GET("/rest/schema/:module/:table", handleListSchemas)
|
||||
hs.PUT("/rest/schema/:module/:table", handleUpdateSchemas)
|
||||
hs.DELETE("/rest/schema/:id", handleDeleteSchema)
|
||||
hs.GET("/rest/kvpairs/:module/:table/:value/:label", handleKeyValues) //处理键值对数据
|
||||
hs.GET("/rest/tierpairs/str/:module/:table/:parent/:value/:label", handleTierPairs) //处理字符串类型的层级数据
|
||||
hs.GET("/rest/tierpairs/num/:module/:table/:parent/:value/:label", handleNumberTierPairs) //处理数字类型的层级数据, 只支持int64
|
||||
}
|
||||
|
||||
// AutoMigrate 自动生成一个模型的schema和权限的定义
|
||||
func AutoMigrate(ctx context.Context, db *gorm.DB, model any, cbs ...Option) (err error) {
|
||||
var (
|
||||
mv *rest.Model
|
||||
)
|
||||
opts := newOptions(cbs...)
|
||||
if mv, err = rest.AutoMigrate(ctx, model); err != nil {
|
||||
if mm, ok := model.(adminTypes.ModuleModel); ok {
|
||||
moduleName := mm.ModuleName()
|
||||
opts.restOpts = append(opts.restOpts, rest.WithModuleName(moduleName))
|
||||
}
|
||||
if err = db.AutoMigrate(model); err != nil {
|
||||
return
|
||||
}
|
||||
err = checkModel(opts, mv)
|
||||
if mv, err = rest.AutoMigrate(ctx, model, opts.restOpts...); err != nil {
|
||||
return
|
||||
}
|
||||
if err = checkModel(opts, mv); err == nil {
|
||||
if opts.vuePath != "" {
|
||||
if err = generateVueFile(opts.vuePath, opts.apiPrefix, mv); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
|
@ -137,9 +514,23 @@ func Init(ctx context.Context, cbs ...Option) (err error) {
|
|||
if err = initREST(ctx, opts); err != nil {
|
||||
return
|
||||
}
|
||||
if err = initRBAC(ctx, opts); err != nil {
|
||||
if err = initModels(ctx, opts); err != nil {
|
||||
return
|
||||
}
|
||||
err = defaults.Init(opts.db)
|
||||
if opts.httpServer != nil {
|
||||
registerRESTRoute(opts.domain, opts.db, opts.httpServer)
|
||||
}
|
||||
if !opts.disableDefault {
|
||||
if err = migrate.Default(opts.db); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
if !opts.disableRecorder {
|
||||
//启用操作记录
|
||||
NewActivityRecorder(ctx, opts.db).Recoder()
|
||||
}
|
||||
|
||||
//注册渲染器
|
||||
NewFormatter(opts.db, opts.cache).Register()
|
||||
return
|
||||
}
|
||||
|
|
119
service/auth.go
119
service/auth.go
|
@ -2,26 +2,52 @@ package service
|
|||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"git.nobla.cn/golang/aeus-admin/models"
|
||||
"git.nobla.cn/golang/aeus-admin/pb"
|
||||
"git.nobla.cn/golang/aeus-admin/types"
|
||||
"git.nobla.cn/golang/aeus/metadata"
|
||||
"git.nobla.cn/golang/aeus/pkg/cache"
|
||||
"git.nobla.cn/golang/aeus/pkg/errors"
|
||||
"git.nobla.cn/golang/aeus/pkg/httpclient"
|
||||
jwt "github.com/golang-jwt/jwt/v5"
|
||||
"github.com/mssola/useragent"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type (
|
||||
authOptions struct {
|
||||
db *gorm.DB
|
||||
secret []byte
|
||||
method string
|
||||
ttl int64
|
||||
db *gorm.DB
|
||||
secret []byte
|
||||
method string
|
||||
ttl int64
|
||||
cache cache.Cache
|
||||
tokenStore TokenStore
|
||||
turnstileValidateUrl string
|
||||
turnstileSiteKey string
|
||||
}
|
||||
|
||||
turnstileRequest struct {
|
||||
Secret string `json:"secret"`
|
||||
Response string `json:"response"`
|
||||
}
|
||||
|
||||
turnstileResponse struct {
|
||||
Success bool `json:"success"`
|
||||
Hostname string `json:"hostname"`
|
||||
ErrorCodes []string `json:"error-codes"`
|
||||
Action string `json:"action"`
|
||||
}
|
||||
|
||||
AuthOption func(o *authOptions)
|
||||
|
||||
TokenStore interface {
|
||||
Put(ctx context.Context, token string, ttl int64) error
|
||||
Del(ctx context.Context, token string) error
|
||||
}
|
||||
|
||||
AuthService struct {
|
||||
opts *authOptions
|
||||
}
|
||||
|
@ -33,12 +59,34 @@ func WithAuthDB(db *gorm.DB) AuthOption {
|
|||
}
|
||||
}
|
||||
|
||||
func WithAuthCache(cache cache.Cache) AuthOption {
|
||||
return func(o *authOptions) {
|
||||
o.cache = cache
|
||||
}
|
||||
}
|
||||
|
||||
func WithTokenStore(store TokenStore) AuthOption {
|
||||
return func(o *authOptions) {
|
||||
o.tokenStore = store
|
||||
}
|
||||
}
|
||||
|
||||
func WithAuthSecret(secret []byte) AuthOption {
|
||||
return func(o *authOptions) {
|
||||
o.secret = secret
|
||||
}
|
||||
}
|
||||
|
||||
func WithAuthTranslate(key, url string) AuthOption {
|
||||
return func(o *authOptions) {
|
||||
o.turnstileSiteKey = key
|
||||
if url == "" {
|
||||
url = "https://challenges.cloudflare.com/turnstile/v0/siteverify"
|
||||
}
|
||||
o.turnstileValidateUrl = url
|
||||
}
|
||||
}
|
||||
|
||||
func WithAuthMethod(method string) AuthOption {
|
||||
return func(o *authOptions) {
|
||||
o.method = method
|
||||
|
@ -51,37 +99,90 @@ func WithAuthTTL(ttl int64) AuthOption {
|
|||
}
|
||||
}
|
||||
|
||||
func (s *AuthService) turnstileValidate(ctx context.Context, token string) (err error) {
|
||||
if s.opts.turnstileSiteKey == "" || s.opts.turnstileValidateUrl == "" {
|
||||
return nil
|
||||
}
|
||||
payload := &turnstileRequest{
|
||||
Secret: s.opts.turnstileSiteKey,
|
||||
Response: token,
|
||||
}
|
||||
result := &turnstileResponse{}
|
||||
if err = httpclient.Do(
|
||||
ctx,
|
||||
s.opts.turnstileValidateUrl,
|
||||
result,
|
||||
httpclient.WithMethod(http.MethodPost),
|
||||
httpclient.WithBody(payload),
|
||||
); err != nil {
|
||||
return
|
||||
}
|
||||
if !result.Success {
|
||||
if len(result.ErrorCodes) == 0 {
|
||||
err = errors.Format(errors.Unavailable, "turnstile validate failed")
|
||||
} else {
|
||||
err = errors.Format(errors.Unavailable, result.ErrorCodes[0])
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (s *AuthService) Login(ctx context.Context, req *pb.LoginRequest) (res *pb.LoginResponse, err error) {
|
||||
model := &models.User{}
|
||||
tx := s.opts.db.WithContext(ctx)
|
||||
if err = req.Validate(); err != nil {
|
||||
return nil, errors.Format(errors.Invalid, err.Error())
|
||||
}
|
||||
if err = model.FindOne(tx, "uid=?", req.Username); err != nil {
|
||||
return
|
||||
if err = s.turnstileValidate(ctx, req.Token); err != nil {
|
||||
return nil, errors.Format(errors.Invalid, err.Error())
|
||||
}
|
||||
if err = model.QueryOne(tx, "uid=?", req.Username); err != nil {
|
||||
return nil, errors.ErrAccessDenied
|
||||
}
|
||||
if model.Status != types.UserStatusNormal {
|
||||
return nil, errors.ErrAccessDenied
|
||||
}
|
||||
if model.Password != req.Password {
|
||||
err = errors.ErrAccessDenied
|
||||
return
|
||||
return nil, errors.ErrAccessDenied
|
||||
}
|
||||
claims := types.Claims{
|
||||
Uid: model.Uid,
|
||||
Role: model.Role,
|
||||
Admin: model.Admin,
|
||||
IssuedAt: time.Now().Unix(),
|
||||
ExpirationAt: time.Now().Add(time.Second * time.Duration(s.opts.ttl)).Unix(),
|
||||
}
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
|
||||
res = &pb.LoginResponse{}
|
||||
if res.Token, err = token.SignedString(s.opts.secret); err == nil {
|
||||
res.Uid = model.Uid
|
||||
res.Username = model.Username
|
||||
res.Expires = s.opts.ttl
|
||||
}
|
||||
loginModel := &models.Login{}
|
||||
loginModel.Uid = model.Uid
|
||||
loginModel.AccessToken = res.Token
|
||||
md := metadata.FromContext(ctx)
|
||||
if s.opts.tokenStore != nil {
|
||||
s.opts.tokenStore.Put(ctx, res.Token, s.opts.ttl)
|
||||
}
|
||||
if userAgent, ok := md.Get("User-Agent"); ok {
|
||||
ua := useragent.New(userAgent)
|
||||
loginModel.Os = ua.OS()
|
||||
loginModel.Platform = ua.Platform()
|
||||
loginModel.UserAgent = userAgent
|
||||
browser, browserVersion := ua.Browser()
|
||||
loginModel.Browser = browser + "/" + browserVersion
|
||||
tx.Save(loginModel)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (s *AuthService) Logout(ctx context.Context, req *pb.LogoutRequest) (res *pb.LogoutResponse, err error) {
|
||||
|
||||
if s.opts.tokenStore != nil {
|
||||
err = s.opts.tokenStore.Del(ctx, req.Token)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
|
|
|
@ -0,0 +1,138 @@
|
|||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strconv"
|
||||
|
||||
"git.nobla.cn/golang/aeus-admin/internal/logic"
|
||||
"git.nobla.cn/golang/aeus-admin/models"
|
||||
"git.nobla.cn/golang/aeus-admin/pb"
|
||||
"git.nobla.cn/golang/aeus/pkg/cache"
|
||||
"git.nobla.cn/golang/rest/types"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type (
|
||||
departmentOptions struct {
|
||||
db *gorm.DB
|
||||
cache cache.Cache
|
||||
}
|
||||
DepartmentOption func(o *departmentOptions)
|
||||
|
||||
DepartmentService struct {
|
||||
opts *departmentOptions
|
||||
logic *logic.Department
|
||||
user *logic.User
|
||||
}
|
||||
)
|
||||
|
||||
func WithDepartmentCache(cache cache.Cache) DepartmentOption {
|
||||
return func(o *departmentOptions) {
|
||||
o.cache = cache
|
||||
}
|
||||
}
|
||||
|
||||
func WithDepartmentDB(db *gorm.DB) DepartmentOption {
|
||||
return func(o *departmentOptions) {
|
||||
o.db = db
|
||||
}
|
||||
}
|
||||
|
||||
func (s *DepartmentService) GetDepartmentLabels(ctx context.Context, req *pb.GetDepartmentLabelRequest) (res *pb.GetDepartmentLabelResponse, err error) {
|
||||
res = &pb.GetDepartmentLabelResponse{}
|
||||
var values []*types.TypeValue[int64]
|
||||
if values, err = s.logic.GetLabels(ctx); err == nil {
|
||||
res.Data = make([]*pb.DepartmentLabelValue, 0, len(values))
|
||||
for _, row := range values {
|
||||
res.Data = append(res.Data, &pb.DepartmentLabelValue{
|
||||
Label: row.Label,
|
||||
Value: row.Value,
|
||||
})
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (s *DepartmentService) recursiveDepartmentUser(parent int64, departments []*models.Department, users []*models.User) []*pb.DepartmentUserValue {
|
||||
values := make([]*pb.DepartmentUserValue, 0, len(departments))
|
||||
for _, row := range departments {
|
||||
if row.ParentId == parent {
|
||||
item := &pb.DepartmentUserValue{
|
||||
Label: row.Name,
|
||||
Value: strconv.FormatInt(row.Id, 10),
|
||||
Children: make([]*pb.DepartmentUserValue, 0),
|
||||
}
|
||||
item.Children = append(item.Children, s.recursiveDepartmentUser(row.Id, departments, users)...)
|
||||
for _, v := range users {
|
||||
if v.DeptId == row.Id {
|
||||
item.Children = append(item.Children, &pb.DepartmentUserValue{
|
||||
Label: fmt.Sprintf("%s(%s)", v.Username, v.Uid),
|
||||
Value: v.Uid,
|
||||
Isuser: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
values = append(values, item)
|
||||
}
|
||||
}
|
||||
return values
|
||||
}
|
||||
|
||||
func (s *DepartmentService) recursiveDepartmentLevel(parent int64, departments []*models.Department) []*pb.DepartmentLevelValue {
|
||||
values := make([]*pb.DepartmentLevelValue, 0, len(departments))
|
||||
for _, row := range departments {
|
||||
if row.ParentId == parent {
|
||||
item := &pb.DepartmentLevelValue{
|
||||
Label: row.Name,
|
||||
Value: row.Id,
|
||||
Children: make([]*pb.DepartmentLevelValue, 0),
|
||||
}
|
||||
item.Children = append(item.Children, s.recursiveDepartmentLevel(row.Id, departments)...)
|
||||
values = append(values, item)
|
||||
}
|
||||
}
|
||||
return values
|
||||
}
|
||||
|
||||
func (s *DepartmentService) GetDepartmentUsers(ctx context.Context, req *pb.GetDepartmentUserRequest) (res *pb.GetDepartmentUserResponse, err error) {
|
||||
var (
|
||||
users []*models.User
|
||||
departments []*models.Department
|
||||
)
|
||||
if departments, err = s.logic.GetDepartments(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
if users, err = s.user.GeUsers(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
res = &pb.GetDepartmentUserResponse{
|
||||
Data: s.recursiveDepartmentUser(0, departments, users),
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (s *DepartmentService) GetDepartmentLevelLabels(ctx context.Context, req *pb.GetDepartmentLevelLabelsRequest) (res *pb.GetDepartmentLevelLabelsResponse, err error) {
|
||||
var (
|
||||
departments []*models.Department
|
||||
)
|
||||
if departments, err = s.logic.GetDepartments(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
res = &pb.GetDepartmentLevelLabelsResponse{
|
||||
Data: s.recursiveDepartmentLevel(0, departments),
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func NewDepartmentService(cbs ...DepartmentOption) *DepartmentService {
|
||||
opts := &departmentOptions{}
|
||||
for _, cb := range cbs {
|
||||
cb(opts)
|
||||
}
|
||||
return &DepartmentService{
|
||||
opts: opts,
|
||||
user: logic.NewUserLogic(opts.db, opts.cache),
|
||||
logic: logic.NewDepartmentLogic(opts.db, opts.cache),
|
||||
}
|
||||
}
|
116
service/menu.go
116
service/menu.go
|
@ -3,101 +3,94 @@ package service
|
|||
import (
|
||||
"context"
|
||||
|
||||
"git.nobla.cn/golang/aeus-admin/internal/logic"
|
||||
"git.nobla.cn/golang/aeus-admin/models"
|
||||
"git.nobla.cn/golang/aeus-admin/pb"
|
||||
"git.nobla.cn/golang/aeus-admin/types"
|
||||
"git.nobla.cn/golang/aeus/middleware/auth"
|
||||
"git.nobla.cn/golang/aeus/pkg/errors"
|
||||
"git.nobla.cn/golang/aeus/pkg/cache"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type (
|
||||
menuOptions struct {
|
||||
db *gorm.DB
|
||||
db *gorm.DB
|
||||
cache cache.Cache
|
||||
}
|
||||
MenuOption func(o *menuOptions)
|
||||
|
||||
MenuService struct {
|
||||
opts *menuOptions
|
||||
opts *menuOptions
|
||||
logic *logic.Menu
|
||||
}
|
||||
)
|
||||
|
||||
func WithMenuCache(cache cache.Cache) MenuOption {
|
||||
return func(o *menuOptions) {
|
||||
o.cache = cache
|
||||
}
|
||||
}
|
||||
|
||||
func WithMenuDB(db *gorm.DB) MenuOption {
|
||||
return func(o *menuOptions) {
|
||||
o.db = db
|
||||
}
|
||||
}
|
||||
|
||||
func (s *MenuService) hasPermission(menuID int64, permissions []*models.Permission) bool {
|
||||
for _, permission := range permissions {
|
||||
if permission.MenuId == menuID {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (s *MenuService) getPermissions(menuID int64, permissions []*models.Permission) []*pb.PermissionItem {
|
||||
ss := make([]*pb.PermissionItem, 0, 10)
|
||||
for _, permission := range permissions {
|
||||
if permission.MenuId == menuID {
|
||||
ss = append(ss, &pb.PermissionItem{
|
||||
Value: permission.Permission,
|
||||
Label: permission.Label,
|
||||
})
|
||||
}
|
||||
}
|
||||
return ss
|
||||
}
|
||||
|
||||
func (s *MenuService) recursiveNestedMenu(ctx context.Context, parent int64, perm bool, menus []*models.Menu, permissions []*models.Permission) []*pb.MenuItem {
|
||||
values := make([]*pb.MenuItem, 0)
|
||||
for _, row := range menus {
|
||||
if row.ParentId == parent {
|
||||
if !row.Public && !s.hasPermission(row.Id, permissions) {
|
||||
continue
|
||||
}
|
||||
v := &pb.MenuItem{
|
||||
Label: row.Label,
|
||||
func (s *MenuService) recursiveMenuValue(parent string, items []*models.Menu) []*pb.MenuValue {
|
||||
values := make([]*pb.MenuValue, 0, len(items))
|
||||
for _, row := range items {
|
||||
if row.Parent == parent {
|
||||
item := &pb.MenuValue{
|
||||
Id: row.Id,
|
||||
Parent: row.Parent,
|
||||
Name: row.Name,
|
||||
Icon: row.Icon,
|
||||
Hidden: row.Hidden,
|
||||
Route: row.Uri,
|
||||
Children: s.recursiveNestedMenu(ctx, row.Id, perm, menus, permissions),
|
||||
Label: row.Label,
|
||||
Children: make([]*pb.MenuValue, 0),
|
||||
}
|
||||
if perm {
|
||||
v.Permissions = s.getPermissions(row.Id, permissions)
|
||||
}
|
||||
values = append(values, v)
|
||||
item.Children = append(item.Children, s.recursiveMenuValue(row.Name, items)...)
|
||||
values = append(values, item)
|
||||
}
|
||||
}
|
||||
return values
|
||||
}
|
||||
|
||||
func (s *MenuService) GetRolePermissions(ctx context.Context, db *gorm.DB, role string) (permissions []*models.Permission, err error) {
|
||||
permissions = make([]*models.Permission, 0)
|
||||
err = db.Where("id IN (SELECT permission_id FROM role_permissions WHERE role = ?)", role).Find(&permissions).Error
|
||||
return
|
||||
func (s *MenuService) recursiveMenuLevel(parent string, items []*models.Menu) []*pb.MenuLevelValue {
|
||||
values := make([]*pb.MenuLevelValue, 0, len(items))
|
||||
for _, row := range items {
|
||||
if row.Parent == parent {
|
||||
item := &pb.MenuLevelValue{
|
||||
Label: row.Label,
|
||||
Value: row.Name,
|
||||
Children: make([]*pb.MenuLevelValue, 0),
|
||||
}
|
||||
item.Children = append(item.Children, s.recursiveMenuLevel(row.Name, items)...)
|
||||
values = append(values, item)
|
||||
}
|
||||
}
|
||||
return values
|
||||
}
|
||||
|
||||
func (s *MenuService) GetMenus(ctx context.Context, req *pb.GetMenuRequest) (res *pb.GetMenuResponse, err error) {
|
||||
claims, ok := auth.FromContext(ctx)
|
||||
if !ok {
|
||||
return nil, errors.ErrAccessDenied
|
||||
}
|
||||
var (
|
||||
permissions []*models.Permission
|
||||
items []*models.Menu
|
||||
)
|
||||
tx := s.opts.db.WithContext(ctx)
|
||||
if claims, ok := claims.(*types.Claims); ok {
|
||||
permissions, err = s.GetRolePermissions(ctx, tx, claims.Role)
|
||||
}
|
||||
values := make([]*models.Menu, 0)
|
||||
if err = tx.Find(&values).Error; err != nil {
|
||||
if items, err = s.logic.GetMenus(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
res = &pb.GetMenuResponse{
|
||||
Data: s.recursiveNestedMenu(ctx, 0, req.Permission, values, permissions),
|
||||
Data: s.recursiveMenuValue("", items),
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (s *MenuService) GetMenuLevelLabels(ctx context.Context, req *pb.GetMenuLevelLabelsRequest) (res *pb.GetMenuLevelLabelsResponse, err error) {
|
||||
var (
|
||||
items []*models.Menu
|
||||
)
|
||||
if items, err = s.logic.GetMenus(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
res = &pb.GetMenuLevelLabelsResponse{
|
||||
Data: s.recursiveMenuLevel("", items),
|
||||
}
|
||||
return
|
||||
}
|
||||
|
@ -108,6 +101,7 @@ func NewMenuService(cbs ...MenuOption) *MenuService {
|
|||
cb(opts)
|
||||
}
|
||||
return &MenuService{
|
||||
opts: opts,
|
||||
opts: opts,
|
||||
logic: logic.NewMenuLogic(opts.db, opts.cache),
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,113 +0,0 @@
|
|||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"git.nobla.cn/golang/aeus-admin/models"
|
||||
"git.nobla.cn/golang/aeus-admin/pb"
|
||||
"git.nobla.cn/golang/aeus/middleware/auth"
|
||||
"git.nobla.cn/golang/aeus/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type (
|
||||
profileOptions struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
ProfileOption func(o *profileOptions)
|
||||
|
||||
ProfileService struct {
|
||||
opts *profileOptions
|
||||
}
|
||||
)
|
||||
|
||||
func WithProfileDB(db *gorm.DB) ProfileOption {
|
||||
return func(o *profileOptions) {
|
||||
o.db = db
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ProfileService) getUidFromContext(ctx context.Context) (string, error) {
|
||||
if claims, ok := auth.FromContext(ctx); !ok {
|
||||
return "", errors.ErrAccessDenied
|
||||
} else {
|
||||
return claims.GetSubject()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ProfileService) GetProfile(ctx context.Context, req *pb.GetProfileRequest) (res *pb.GetProfileResponse, err error) {
|
||||
if req.Uid == "" {
|
||||
if req.Uid, err = s.getUidFromContext(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
res = &pb.GetProfileResponse{}
|
||||
tx := s.opts.db.WithContext(ctx)
|
||||
err = tx.Table("users AS u").Select("u.uid as uid", "u.username", "u.avatar", "u.email", "u.description", "u.role_id as role").Where("u.uid=? ", req.Uid).First(res).Error
|
||||
return
|
||||
}
|
||||
|
||||
func (s *ProfileService) UpdateProfile(ctx context.Context, req *pb.UpdateProfileRequest) (res *pb.UpdateProfileResponse, err error) {
|
||||
if req.Uid == "" {
|
||||
if req.Uid, err = s.getUidFromContext(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
userModel := &models.User{}
|
||||
tx := s.opts.db.WithContext(ctx)
|
||||
if err = tx.Where("uid=?", req.Uid).First(userModel).Error; err != nil {
|
||||
return
|
||||
}
|
||||
if req.Avatar != "" {
|
||||
userModel.Avatar = req.Avatar
|
||||
}
|
||||
if req.Email != "" {
|
||||
userModel.Email = req.Email
|
||||
}
|
||||
if req.Username != "" {
|
||||
userModel.Username = req.Username
|
||||
}
|
||||
if req.Description != "" {
|
||||
userModel.Description = req.Description
|
||||
}
|
||||
if err = tx.Save(userModel).Error; err == nil {
|
||||
res = &pb.UpdateProfileResponse{
|
||||
Uid: userModel.Uid,
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (s *ProfileService) ResetPassword(ctx context.Context, req *pb.ResetPasswordRequest) (res *pb.ResetPasswordResponse, err error) {
|
||||
if req.Uid == "" {
|
||||
if req.Uid, err = s.getUidFromContext(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
userModel := &models.User{}
|
||||
tx := s.opts.db.WithContext(ctx)
|
||||
if err = tx.Where("uid=?", req.Uid).First(userModel).Error; err != nil {
|
||||
return
|
||||
}
|
||||
if userModel.Password == req.OldPassword {
|
||||
if err = tx.Where("uid=?", req.Uid).Model(&models.User{}).UpdateColumn("password", req.NewPassword).Error; err == nil {
|
||||
res = &pb.ResetPasswordResponse{
|
||||
Uid: userModel.Uid,
|
||||
}
|
||||
}
|
||||
} else {
|
||||
err = errors.Format(errors.AccessDenied, "invalid old password")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func NewProfileService(cbs ...ProfileOption) *ProfileService {
|
||||
opts := &profileOptions{}
|
||||
for _, cb := range cbs {
|
||||
cb(opts)
|
||||
}
|
||||
return &ProfileService{
|
||||
opts: opts,
|
||||
}
|
||||
}
|
|
@ -0,0 +1,96 @@
|
|||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"git.nobla.cn/golang/aeus-admin/internal/logic"
|
||||
"git.nobla.cn/golang/aeus-admin/models"
|
||||
"git.nobla.cn/golang/aeus-admin/pb"
|
||||
"git.nobla.cn/golang/aeus/pkg/cache"
|
||||
"git.nobla.cn/golang/rest/types"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type (
|
||||
roleOptions struct {
|
||||
db *gorm.DB
|
||||
cache cache.Cache
|
||||
}
|
||||
RoleOption func(o *roleOptions)
|
||||
|
||||
RoleService struct {
|
||||
opts *roleOptions
|
||||
logic *logic.Role
|
||||
}
|
||||
)
|
||||
|
||||
func WithRoleCache(cache cache.Cache) RoleOption {
|
||||
return func(o *roleOptions) {
|
||||
o.cache = cache
|
||||
}
|
||||
}
|
||||
|
||||
func WithRoleDB(db *gorm.DB) RoleOption {
|
||||
return func(o *roleOptions) {
|
||||
o.db = db
|
||||
}
|
||||
}
|
||||
|
||||
func (s *RoleService) GetRoleLabels(ctx context.Context, req *pb.GetRoleLabelRequest) (res *pb.GetRoleLabelResponse, err error) {
|
||||
res = &pb.GetRoleLabelResponse{}
|
||||
var values []*types.TypeValue[string]
|
||||
if values, err = s.logic.GetLabels(ctx); err == nil {
|
||||
res.Data = make([]*pb.LabelValue, 0, len(values))
|
||||
for _, row := range values {
|
||||
res.Data = append(res.Data, &pb.LabelValue{
|
||||
Label: row.Label,
|
||||
Value: row.Value,
|
||||
})
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (s *RoleService) GetRolePermissions(ctx context.Context, req *pb.GetRolePermissionRequest) (res *pb.GetRolePermissionResponse, err error) {
|
||||
var permissions []string
|
||||
if err = s.opts.db.WithContext(ctx).Model(&models.RolePermission{}).Where("role=?", req.Role).Pluck("permission", &permissions).Error; err != nil {
|
||||
return
|
||||
}
|
||||
res = &pb.GetRolePermissionResponse{
|
||||
Role: req.Role,
|
||||
Permissions: permissions,
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (s *RoleService) SaveRolePermission(ctx context.Context, req *pb.SaveRolePermissionRequest) (res *pb.SaveRolePermissionResponse, err error) {
|
||||
tx := s.opts.db.WithContext(ctx).Begin()
|
||||
tx.Where("role = ?", req.Role).Delete(&models.RolePermission{})
|
||||
values := make([]*models.RolePermission, 0)
|
||||
for _, permission := range req.Permissions {
|
||||
item := &models.RolePermission{}
|
||||
item.Role = req.Role
|
||||
item.Permission = permission
|
||||
values = append(values, item)
|
||||
}
|
||||
if err = tx.Save(values).Error; err == nil {
|
||||
tx.Commit()
|
||||
} else {
|
||||
tx.Rollback()
|
||||
}
|
||||
res = &pb.SaveRolePermissionResponse{
|
||||
Role: req.Role,
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func NewRoleService(cbs ...RoleOption) *RoleService {
|
||||
opts := &roleOptions{}
|
||||
for _, cb := range cbs {
|
||||
cb(opts)
|
||||
}
|
||||
return &RoleService{
|
||||
opts: opts,
|
||||
logic: logic.NewRoleLogic(opts.db, opts.cache),
|
||||
}
|
||||
}
|
|
@ -0,0 +1,60 @@
|
|||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"git.nobla.cn/golang/aeus-admin/models"
|
||||
"git.nobla.cn/golang/aeus-admin/pb"
|
||||
"git.nobla.cn/golang/aeus/pkg/cache"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type (
|
||||
settingOptions struct {
|
||||
db *gorm.DB
|
||||
cache cache.Cache
|
||||
}
|
||||
|
||||
SettingOption func(o *settingOptions)
|
||||
)
|
||||
|
||||
type SettingService struct {
|
||||
opts *settingOptions
|
||||
}
|
||||
|
||||
func WithSettingCache(cache cache.Cache) SettingOption {
|
||||
return func(o *settingOptions) {
|
||||
o.cache = cache
|
||||
}
|
||||
}
|
||||
|
||||
func WithSettingDB(db *gorm.DB) SettingOption {
|
||||
return func(o *settingOptions) {
|
||||
o.db = db
|
||||
}
|
||||
}
|
||||
|
||||
func (s *SettingService) GetSetting(ctx context.Context, req *pb.GetSettingRequest) (res *pb.GetSettingResponse, err error) {
|
||||
tx := s.opts.db.WithContext(ctx)
|
||||
values := make([]*models.Setting, 0)
|
||||
if err = tx.Find(&values).Error; err != nil {
|
||||
return
|
||||
}
|
||||
res = &pb.GetSettingResponse{
|
||||
Data: make([]*pb.SettingItem, 0, len(values)),
|
||||
}
|
||||
for _, v := range values {
|
||||
res.Data = append(res.Data, &pb.SettingItem{
|
||||
Name: v.Name,
|
||||
Value: v.Value,
|
||||
})
|
||||
}
|
||||
return
|
||||
}
|
||||
func NewSettingService(cbs ...SettingOption) *SettingService {
|
||||
opts := &settingOptions{}
|
||||
for _, cb := range cbs {
|
||||
cb(opts)
|
||||
}
|
||||
return &SettingService{}
|
||||
}
|
|
@ -0,0 +1,315 @@
|
|||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"git.nobla.cn/golang/aeus-admin/internal/logic"
|
||||
"git.nobla.cn/golang/aeus-admin/models"
|
||||
"git.nobla.cn/golang/aeus-admin/pb"
|
||||
"git.nobla.cn/golang/aeus-admin/pkg/dbcache"
|
||||
"git.nobla.cn/golang/aeus/middleware/auth"
|
||||
"git.nobla.cn/golang/aeus/pkg/cache"
|
||||
"git.nobla.cn/golang/aeus/pkg/errors"
|
||||
"git.nobla.cn/golang/rest/types"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type (
|
||||
userOptions struct {
|
||||
db *gorm.DB
|
||||
cache cache.Cache
|
||||
}
|
||||
|
||||
UserOption func(o *userOptions)
|
||||
|
||||
UserService struct {
|
||||
user *logic.User
|
||||
menu *logic.Menu
|
||||
role *logic.Role
|
||||
department *logic.Department
|
||||
opts *userOptions
|
||||
}
|
||||
)
|
||||
|
||||
func WithUserDB(db *gorm.DB) UserOption {
|
||||
return func(o *userOptions) {
|
||||
o.db = db
|
||||
}
|
||||
}
|
||||
|
||||
func WithUserCache(cache cache.Cache) UserOption {
|
||||
return func(o *userOptions) {
|
||||
o.cache = cache
|
||||
}
|
||||
}
|
||||
|
||||
func (s *UserService) getUidFromContext(ctx context.Context) (string, error) {
|
||||
if claims, ok := auth.FromContext(ctx); !ok {
|
||||
return "", errors.ErrAccessDenied
|
||||
} else {
|
||||
return claims.GetSubject()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *UserService) hasPermission(menuName string, permissions []*models.Permission) bool {
|
||||
for _, permission := range permissions {
|
||||
if permission.Menu == menuName {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (s *UserService) getPermissions(menuName string, permissions []*models.Permission) []*pb.PermissionItem {
|
||||
ss := make([]*pb.PermissionItem, 0, 10)
|
||||
for _, permission := range permissions {
|
||||
if permission.Menu == menuName {
|
||||
ss = append(ss, &pb.PermissionItem{
|
||||
Value: permission.Permission,
|
||||
Label: permission.Label,
|
||||
})
|
||||
}
|
||||
}
|
||||
return ss
|
||||
}
|
||||
|
||||
func (s *UserService) recursiveNestedMenu(ctx context.Context, parent string, perm bool, menus []*models.Menu, permissions []*models.Permission) []*pb.MenuItem {
|
||||
values := make([]*pb.MenuItem, 0)
|
||||
for _, row := range menus {
|
||||
if row.Parent == parent {
|
||||
if !row.Public && !s.hasPermission(row.Name, permissions) {
|
||||
continue
|
||||
}
|
||||
v := &pb.MenuItem{
|
||||
Label: row.Label,
|
||||
Name: row.Name,
|
||||
Icon: row.Icon,
|
||||
Hidden: row.Hidden,
|
||||
Route: row.Uri,
|
||||
Public: row.Public,
|
||||
View: row.ViewPath,
|
||||
Children: s.recursiveNestedMenu(ctx, row.Name, perm, menus, permissions),
|
||||
}
|
||||
if perm {
|
||||
v.Permissions = s.getPermissions(row.Name, permissions)
|
||||
}
|
||||
values = append(values, v)
|
||||
}
|
||||
}
|
||||
return values
|
||||
}
|
||||
|
||||
func (s *UserService) GetMenus(ctx context.Context, req *pb.GetUserMenuRequest) (res *pb.GetUserMenuResponse, err error) {
|
||||
var (
|
||||
uid string
|
||||
permissions []*models.Permission
|
||||
)
|
||||
if uid, err = s.getUidFromContext(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
res = &pb.GetUserMenuResponse{}
|
||||
res.Data, err = dbcache.TryCache(ctx, fmt.Sprintf("user:menu:%s:%v", uid, req.Permission), func(tx *gorm.DB) ([]*pb.MenuItem, error) {
|
||||
var (
|
||||
userModel *models.User
|
||||
menus []*models.Menu
|
||||
)
|
||||
userModel = &models.User{}
|
||||
if err = tx.Where("`uid`=?", uid).First(userModel).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if menus, err = s.menu.GetMenus(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
roleName := userModel.Role
|
||||
if userModel.Admin {
|
||||
roleName = ""
|
||||
}
|
||||
if permissions, err = s.role.GetPermissions(ctx, roleName); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.recursiveNestedMenu(ctx, "", req.Permission, menus, permissions), nil
|
||||
},
|
||||
dbcache.WithDB(s.opts.db),
|
||||
dbcache.WithCacheDuration(time.Second*10),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
func (s *UserService) GetProfile(ctx context.Context, req *pb.GetProfileRequest) (res *pb.GetProfileResponse, err error) {
|
||||
if req.Uid == "" {
|
||||
if req.Uid, err = s.getUidFromContext(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
res, err = dbcache.TryCache(ctx, fmt.Sprintf("user:profile:%s", req.Uid), func(tx *gorm.DB) (*pb.GetProfileResponse, error) {
|
||||
profile := &pb.GetProfileResponse{}
|
||||
err = tx.Table("users AS u").
|
||||
Select("u.uid as uid", "u.username", "u.avatar", "u.email", "u.description", "u.role", "u.admin").
|
||||
Where("u.uid=? ", req.Uid).
|
||||
First(profile).Error
|
||||
return profile, err
|
||||
},
|
||||
dbcache.WithDB(s.opts.db),
|
||||
dbcache.WithDependency(dbcache.NewSqlDependency("SELECT `updated_at` FROM users WHERE `uid`=?", req.Uid)),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
func (s *UserService) UpdateProfile(ctx context.Context, req *pb.UpdateProfileRequest) (res *pb.UpdateProfileResponse, err error) {
|
||||
if req.Uid == "" {
|
||||
if req.Uid, err = s.getUidFromContext(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
userModel := &models.User{}
|
||||
tx := s.opts.db.WithContext(ctx)
|
||||
if err = tx.Where("uid=?", req.Uid).First(userModel).Error; err != nil {
|
||||
return
|
||||
}
|
||||
if req.Avatar != "" {
|
||||
userModel.Avatar = req.Avatar
|
||||
}
|
||||
if req.Email != "" {
|
||||
userModel.Email = req.Email
|
||||
}
|
||||
if req.Username != "" {
|
||||
userModel.Username = req.Username
|
||||
}
|
||||
if req.Description != "" {
|
||||
userModel.Description = req.Description
|
||||
}
|
||||
if err = tx.Save(userModel).Error; err == nil {
|
||||
res = &pb.UpdateProfileResponse{
|
||||
Uid: userModel.Uid,
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (s *UserService) ResetPassword(ctx context.Context, req *pb.ResetPasswordRequest) (res *pb.ResetPasswordResponse, err error) {
|
||||
if req.Uid == "" {
|
||||
if req.Uid, err = s.getUidFromContext(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
userModel := &models.User{}
|
||||
tx := s.opts.db.WithContext(ctx)
|
||||
if err = tx.Where("uid=?", req.Uid).First(userModel).Error; err != nil {
|
||||
return
|
||||
}
|
||||
if userModel.Password == req.OldPassword {
|
||||
if err = tx.Where("uid=?", req.Uid).Model(&models.User{}).UpdateColumn("password", req.NewPassword).Error; err == nil {
|
||||
res = &pb.ResetPasswordResponse{
|
||||
Uid: userModel.Uid,
|
||||
}
|
||||
}
|
||||
} else {
|
||||
err = errors.Format(errors.AccessDenied, "invalid old password")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (s *UserService) GetPermissions(ctx context.Context, req *pb.GetPermissionRequest) (res *pb.GetPermissionResponse, err error) {
|
||||
if req.Uid == "" {
|
||||
if req.Uid, err = s.getUidFromContext(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
res = &pb.GetPermissionResponse{
|
||||
Uid: req.Uid,
|
||||
}
|
||||
res.Permissions, err = s.user.GetPermissions(ctx, req.Uid)
|
||||
return
|
||||
}
|
||||
|
||||
func (s *UserService) GetUserLabels(ctx context.Context, req *pb.GetUserLabelRequest) (res *pb.GetUserLabelResponse, err error) {
|
||||
res = &pb.GetUserLabelResponse{}
|
||||
var values []*types.TypeValue[string]
|
||||
if values, err = s.user.GetLabels(ctx); err == nil {
|
||||
res.Data = make([]*pb.LabelValue, 0, len(values))
|
||||
for _, row := range values {
|
||||
res.Data = append(res.Data, &pb.LabelValue{
|
||||
Label: row.Label,
|
||||
Value: row.Value,
|
||||
})
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (s *UserService) DepartmentUserNested(ctx context.Context) []*types.NestedValue[string] {
|
||||
var (
|
||||
err error
|
||||
users []*models.User
|
||||
departments []*models.Department
|
||||
)
|
||||
|
||||
if departments, err = s.department.GetDepartments(ctx); err != nil {
|
||||
return nil
|
||||
}
|
||||
if users, err = s.user.GeUsers(ctx); err != nil {
|
||||
return nil
|
||||
}
|
||||
depts := s.department.RecursiveDepartment(ctx, 0, 0, departments)
|
||||
values := make([]*types.NestedValue[string], 0)
|
||||
for _, dept := range depts {
|
||||
v := &types.NestedValue[string]{
|
||||
Label: dept.Label,
|
||||
Value: strconv.FormatInt(dept.Value, 10),
|
||||
Children: make([]*types.NestedValue[string], 0),
|
||||
}
|
||||
for _, user := range users {
|
||||
if strconv.FormatInt(user.DeptId, 10) == v.Value {
|
||||
v.Children = append(v.Children, &types.NestedValue[string]{
|
||||
Label: fmt.Sprintf("%s(%s)", user.Username, user.Uid),
|
||||
Value: user.Uid,
|
||||
})
|
||||
}
|
||||
}
|
||||
values = append(values, v)
|
||||
}
|
||||
return values
|
||||
}
|
||||
|
||||
func (s *UserService) GetUserTags(ctx context.Context, req *pb.GetUserTagRequest) (res *pb.GetUserTagResponse, err error) {
|
||||
res = &pb.GetUserTagResponse{}
|
||||
res.Data, err = dbcache.TryCache(ctx, fmt.Sprintf("user:tags"), func(tx *gorm.DB) ([]*pb.LabelValue, error) {
|
||||
values := make([]*models.User, 0)
|
||||
if err = tx.Select("DISTINCT(`tag`) AS `tag`").Find(&values).Error; err == nil {
|
||||
items := make([]*pb.LabelValue, 0, len(values))
|
||||
for _, v := range values {
|
||||
if v.Tag == "" {
|
||||
continue
|
||||
}
|
||||
items = append(items, &pb.LabelValue{
|
||||
Label: v.Tag,
|
||||
Value: v.Tag,
|
||||
})
|
||||
}
|
||||
return items, nil
|
||||
} else {
|
||||
return nil, err
|
||||
}
|
||||
},
|
||||
dbcache.WithDB(s.opts.db),
|
||||
dbcache.WithDependency(dbcache.NewSqlDependency("SELECT MAX(`updated_at`) FROM users")),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
func NewUserService(cbs ...UserOption) *UserService {
|
||||
opts := &userOptions{}
|
||||
for _, cb := range cbs {
|
||||
cb(opts)
|
||||
}
|
||||
return &UserService{
|
||||
opts: opts,
|
||||
user: logic.NewUserLogic(opts.db, opts.cache),
|
||||
role: logic.NewRoleLogic(opts.db, opts.cache),
|
||||
menu: logic.NewMenuLogic(opts.db, opts.cache),
|
||||
department: logic.NewDepartmentLogic(opts.db, opts.cache),
|
||||
}
|
||||
}
|
|
@ -0,0 +1,50 @@
|
|||
package aeusadmin
|
||||
|
||||
var (
|
||||
vueTemplate = `
|
||||
<template>
|
||||
<viewer
|
||||
:title="title"
|
||||
:module-name="moduleName"
|
||||
:table-name="tableName"
|
||||
:apiPrefix="apiPrefix"
|
||||
:permissions="permissions"
|
||||
:disable-toolbar="false"
|
||||
default-sortable="id"
|
||||
{{if .Readonly}}:readonly="true"{{end}}
|
||||
>
|
||||
</viewer>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import Viewer from '@/components/fragment/Viewer.vue';
|
||||
import { computed } from 'vue';
|
||||
|
||||
const props = defineProps({
|
||||
title: {
|
||||
type: String,
|
||||
}
|
||||
})
|
||||
|
||||
const permissions = computed(() => {
|
||||
return {
|
||||
{{range $key, $value := .Permissions}}{{$key}}: "{{$value}}",
|
||||
{{end}}
|
||||
}
|
||||
})
|
||||
|
||||
const apiPrefix = computed(() => {
|
||||
return '{{.ApiPrefix}}'
|
||||
})
|
||||
|
||||
const moduleName = computed(() => {
|
||||
return '{{.ModuleName}}'
|
||||
})
|
||||
|
||||
const tableName = computed(() => {
|
||||
return '{{.TableName}}'
|
||||
})
|
||||
|
||||
</script>
|
||||
`
|
||||
)
|
80
types.go
80
types.go
|
@ -1,6 +1,8 @@
|
|||
package aeusadmin
|
||||
|
||||
import (
|
||||
"git.nobla.cn/golang/aeus/pkg/cache"
|
||||
"git.nobla.cn/golang/aeus/transport/http"
|
||||
"git.nobla.cn/golang/rest"
|
||||
"git.nobla.cn/golang/rest/types"
|
||||
"gorm.io/gorm"
|
||||
|
@ -13,18 +15,24 @@ var (
|
|||
types.ScenarioUpdate,
|
||||
types.ScenarioDelete,
|
||||
types.ScenarioView,
|
||||
types.ScenarioImport,
|
||||
types.ScenarioExport,
|
||||
}
|
||||
)
|
||||
|
||||
type (
|
||||
options struct {
|
||||
db *gorm.DB
|
||||
moduleName string
|
||||
viewPath string
|
||||
translate Translate
|
||||
restOpts []rest.Option
|
||||
db *gorm.DB
|
||||
cache cache.Cache
|
||||
domain string
|
||||
moduleName string
|
||||
apiPrefix string //接口前缀
|
||||
viewPrefix string //生成菜单View的前缀路径
|
||||
vuePath string //生成Vue文件的路径,如果指定了启动的时候会自动生成Vue的文件
|
||||
translate Translate
|
||||
disableDefault bool
|
||||
disableRecorder bool
|
||||
httpServer *http.Server
|
||||
restOpts []rest.Option
|
||||
}
|
||||
|
||||
Option func(*options)
|
||||
|
@ -33,6 +41,22 @@ type (
|
|||
Menu(model *rest.Model, label string) string
|
||||
Permission(model *rest.Model, scene string, label string) string
|
||||
}
|
||||
|
||||
MenuBuild interface {
|
||||
Label(model *rest.Model) string
|
||||
Title(model *rest.Model) string
|
||||
Icon(model *rest.Model) string
|
||||
Uri(model *rest.Model) string
|
||||
ViewPath(model *rest.Model) string
|
||||
}
|
||||
|
||||
vueTemplateData struct {
|
||||
ModuleName string
|
||||
TableName string
|
||||
ApiPrefix string
|
||||
Readonly bool
|
||||
Permissions map[string]string
|
||||
}
|
||||
)
|
||||
|
||||
func WithDB(db *gorm.DB) Option {
|
||||
|
@ -41,15 +65,45 @@ func WithDB(db *gorm.DB) Option {
|
|||
}
|
||||
}
|
||||
|
||||
func WithCache(cache cache.Cache) Option {
|
||||
return func(o *options) {
|
||||
o.cache = cache
|
||||
}
|
||||
}
|
||||
|
||||
func WithoutDefault() Option {
|
||||
return func(o *options) {
|
||||
o.disableDefault = true
|
||||
}
|
||||
}
|
||||
|
||||
func WithoutRecorder() Option {
|
||||
return func(o *options) {
|
||||
o.disableRecorder = true
|
||||
}
|
||||
}
|
||||
|
||||
func WithHttpServer(server *http.Server) Option {
|
||||
return func(o *options) {
|
||||
o.httpServer = server
|
||||
}
|
||||
}
|
||||
|
||||
func WithApiPrefix(apiPrefix string) Option {
|
||||
return func(o *options) {
|
||||
o.apiPrefix = apiPrefix
|
||||
}
|
||||
}
|
||||
|
||||
func WithModuleName(moduleName string) Option {
|
||||
return func(o *options) {
|
||||
o.moduleName = moduleName
|
||||
}
|
||||
}
|
||||
|
||||
func WithViewPath(viewPath string) Option {
|
||||
func WithViewPrefix(viewPath string) Option {
|
||||
return func(o *options) {
|
||||
o.viewPath = viewPath
|
||||
o.viewPrefix = viewPath
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -65,9 +119,17 @@ func WithRestOptions(opts ...rest.Option) Option {
|
|||
}
|
||||
}
|
||||
|
||||
func WithVuePath(path string) Option {
|
||||
return func(o *options) {
|
||||
o.vuePath = path
|
||||
}
|
||||
}
|
||||
|
||||
func newOptions(opts ...Option) *options {
|
||||
o := &options{
|
||||
viewPath: "views",
|
||||
viewPrefix: "views",
|
||||
moduleName: "organize",
|
||||
domain: "localhost",
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt(o)
|
||||
|
|
|
@ -9,6 +9,7 @@ import (
|
|||
type Claims struct {
|
||||
Uid string `json:"uid"`
|
||||
Role string `json:"uro"`
|
||||
Admin bool `json:"uab"`
|
||||
Issuer string `json:"iss"`
|
||||
IssuedAt int64 `json:"iat"`
|
||||
ExpirationAt int64 `json:"exp"`
|
||||
|
|
|
@ -0,0 +1,23 @@
|
|||
package types
|
||||
|
||||
type Menu struct {
|
||||
Parent string `json:"parent"`
|
||||
Name string `json:"name"`
|
||||
Label string `json:"label"`
|
||||
Uri string `json:"uri"`
|
||||
ViewPath string `json:"view_path"`
|
||||
Icon string `json:"icon"`
|
||||
Hidden bool `json:"hidden"`
|
||||
}
|
||||
|
||||
type MenuModel interface {
|
||||
GetMenu() *Menu
|
||||
}
|
||||
|
||||
type ModuleModel interface {
|
||||
ModuleName() string
|
||||
}
|
||||
|
||||
type PerrmissionModule interface {
|
||||
ModelPermissions() map[string]string
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
package types
|
||||
|
||||
const (
|
||||
UserStatusNormal = "normal"
|
||||
)
|
Loading…
Reference in New Issue