Compare commits
No commits in common. "05b49cd86aa51fee8563ead619031cb756b95f61" and "d09e6b42bd6d8513f3360474a4c5bed901199a46" have entirely different histories.
05b49cd86a
...
d09e6b42bd
|
|
@ -8,7 +8,10 @@ import (
|
|||
|
||||
"kra/internal/biz"
|
||||
|
||||
"github.com/casbin/casbin/v3"
|
||||
casbinmodel "github.com/casbin/casbin/v3/model"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
type apiRepo struct{ data *Data }
|
||||
|
|
@ -178,3 +181,204 @@ func (r *apiRepo) ListAPIs(ctx context.Context, page, size int, q *biz.API) ([]*
|
|||
}
|
||||
return out, total, nil
|
||||
}
|
||||
func (r *apiRepo) APIRoleIDs(ctx context.Context, path, method string) ([]uint, error) {
|
||||
rows := make([]casbinRulePO, 0)
|
||||
err := policyScope(r.data.gormDB.WithContext(ctx)).
|
||||
Where("v1 = ? AND v2 = ?", path, method).
|
||||
Find(&rows).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ids := make([]uint, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
id, err := strconv.ParseUint(row.V0, 10, 64)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
ids = append(ids, uint(id))
|
||||
}
|
||||
return ids, nil
|
||||
}
|
||||
func (r *apiRepo) SetAPIRoles(ctx context.Context, path, method string, ids []uint) error {
|
||||
return r.data.gormDB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
// A path/method need not be present in sys_apis when replacing
|
||||
// all matching policy rows. Do not validate or deduplicate authority IDs.
|
||||
if err := deletePoliciesForPath(tx, path, method); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
rules := make([]casbinRulePO, 0, len(ids))
|
||||
for _, aid := range ids {
|
||||
rules = append(rules, newPolicyRule(aid, path, method))
|
||||
}
|
||||
return tx.Create(&rules).Error
|
||||
})
|
||||
}
|
||||
func (r *apiRepo) Authorize(ctx context.Context, aid uint, path, method string) (bool, error) {
|
||||
rows, err := policyRowsForAuthority(r.data.gormDB.WithContext(ctx), aid)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
model, err := casbinmodel.NewModelFromString(`[request_definition]
|
||||
r = sub, obj, act
|
||||
[policy_definition]
|
||||
p = sub, obj, act
|
||||
[policy_effect]
|
||||
e = some(where (p.eft == allow))
|
||||
[matchers]
|
||||
m = r.sub == p.sub && keyMatch2(r.obj, p.obj) && r.act == p.act`)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
enforcer, err := casbin.NewEnforcer(model)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
subject := strconv.FormatUint(uint64(aid), 10)
|
||||
for _, policy := range rows {
|
||||
if _, err := enforcer.AddPolicy(subject, policy.V1, policy.V2); err != nil {
|
||||
return false, err
|
||||
}
|
||||
}
|
||||
return enforcer.Enforce(subject, path, method)
|
||||
}
|
||||
func (r *apiRepo) PolicyPaths(ctx context.Context, aid uint) ([]*biz.API, error) {
|
||||
rows, err := policyRowsForAuthority(r.data.gormDB.WithContext(ctx), aid)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out []*biz.API
|
||||
if len(rows) > 0 {
|
||||
out = make([]*biz.API, 0, len(rows))
|
||||
}
|
||||
for _, row := range rows {
|
||||
out = append(out, &biz.API{Path: row.V1, Method: row.V2})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
func (r *apiRepo) SetPolicyPaths(ctx context.Context, aid uint, paths []*biz.API) error {
|
||||
if err := (&authorityAccessRepo{data: r.data}).checkAuthorityIDAuth(ctx, aid); err != nil {
|
||||
return err
|
||||
}
|
||||
config := r.data.runtime.Admin()
|
||||
if actor, ok := biz.ActorFromContext(ctx); ok && config != nil && config.System != nil && config.System.UseStrictAuth {
|
||||
var authority authorityPO
|
||||
if err := r.data.gormDB.WithContext(ctx).Where("authority_id = ?", actor.AuthorityID).First(&authority).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
var registered []apiPO
|
||||
if err := r.data.gormDB.WithContext(ctx).Find(®istered).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
allowedSet := make(map[string]bool, len(registered))
|
||||
if authority.ParentID == nil || *authority.ParentID == 0 {
|
||||
for _, item := range registered {
|
||||
allowedSet[item.Path+"\x00"+item.Method] = true
|
||||
}
|
||||
} else {
|
||||
policies, err := policyRowsForAuthority(r.data.gormDB.WithContext(ctx), actor.AuthorityID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
policySet := make(map[string]bool, len(policies))
|
||||
for _, item := range policies {
|
||||
policySet[item.V1+"\x00"+item.V2] = true
|
||||
}
|
||||
for _, item := range registered {
|
||||
key := item.Path + "\x00" + item.Method
|
||||
if policySet[key] {
|
||||
allowedSet[key] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, item := range paths {
|
||||
if !allowedSet[item.Path+"\x00"+item.Method] {
|
||||
return errors.New("存在api不在权限列表中")
|
||||
}
|
||||
}
|
||||
}
|
||||
db := r.data.gormDB.WithContext(ctx)
|
||||
// The reference enforcer removes the old authority policies before it
|
||||
// attempts to add the replacement set. Keep that ordering visible even
|
||||
// though Kra reads policies directly from the database rather than through
|
||||
// an in-memory enforcer.
|
||||
if err := deletePoliciesForAuthority(db, aid); err != nil {
|
||||
return err
|
||||
}
|
||||
// Keep the legacy relation table clean for upgraded installations. It is
|
||||
// not consulted for authorization anymore.
|
||||
if err := db.Where("authority_id = ?", aid).Delete(&authorityAPIPO{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
rules := make([]casbinRulePO, 0, len(paths))
|
||||
seen := make(map[string]struct{})
|
||||
for _, path := range paths {
|
||||
key := strconv.FormatUint(uint64(aid), 10) + path.Path + path.Method
|
||||
if _, ok := seen[key]; ok {
|
||||
continue
|
||||
}
|
||||
seen[key] = struct{}{}
|
||||
rules = append(rules, newPolicyRule(aid, path.Path, path.Method))
|
||||
}
|
||||
if len(rules) > 0 {
|
||||
return db.Clauses(clause.OnConflict{DoNothing: true}).Create(&rules).Error
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *apiRepo) IgnoredAPIs(ctx context.Context) ([]*biz.API, error) {
|
||||
var pos []ignoredAPIPO
|
||||
if err := r.data.gormDB.WithContext(ctx).Find(&pos).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]*biz.API, 0, len(pos))
|
||||
for _, po := range pos {
|
||||
out = append(out, &biz.API{Path: po.Path, Method: po.Method})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
func (r *apiRepo) SetAPIIgnored(ctx context.Context, path, method string, ignored bool) error {
|
||||
po := ignoredAPIPO{Path: path, Method: method}
|
||||
if ignored {
|
||||
// The compatible endpoint creates an ignore row on every request (the table has no
|
||||
// path/method uniqueness constraint); retain that observable behavior.
|
||||
return r.data.gormDB.WithContext(ctx).Create(&po).Error
|
||||
}
|
||||
return r.data.gormDB.WithContext(ctx).Unscoped().Where("path = ? AND method = ?", po.Path, po.Method).Delete(&ignoredAPIPO{}).Error
|
||||
}
|
||||
func (r *apiRepo) ApplyAPISync(ctx context.Context, added, deleted []*biz.API) error {
|
||||
return r.data.gormDB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
if len(added) > 0 {
|
||||
pos := make([]apiPO, 0, len(added))
|
||||
for _, item := range added {
|
||||
pos = append(pos, apiPO{Path: item.Path, Method: item.Method, Description: item.Description, APIGroup: item.APIGroup})
|
||||
}
|
||||
// Insert the submitted newApis slice as-is. Do not silently
|
||||
// collapse repeated/existing path+method pairs here; sys_apis itself
|
||||
// intentionally has no uniqueness constraint.
|
||||
if err := tx.Create(&pos).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, item := range deleted {
|
||||
var ids []uint
|
||||
if err := tx.Model(&apiPO{}).Where("path = ? AND method = ?", item.Path, item.Method).Pluck("id", &ids).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if len(ids) > 0 {
|
||||
if err := deletePoliciesForPath(tx, item.Path, item.Method); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.Where("api_id IN ?", ids).Delete(&authorityAPIPO{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.Where("id IN ?", ids).Delete(&apiPO{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,161 +0,0 @@
|
|||
package data
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strconv"
|
||||
|
||||
"kra/internal/biz"
|
||||
|
||||
"github.com/casbin/casbin/v3"
|
||||
casbinmodel "github.com/casbin/casbin/v3/model"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
func (r *apiRepo) APIRoleIDs(ctx context.Context, path, method string) ([]uint, error) {
|
||||
rows := make([]casbinRulePO, 0)
|
||||
err := policyScope(r.data.gormDB.WithContext(ctx)).
|
||||
Where("v1 = ? AND v2 = ?", path, method).
|
||||
Find(&rows).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ids := make([]uint, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
id, err := strconv.ParseUint(row.V0, 10, 64)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
ids = append(ids, uint(id))
|
||||
}
|
||||
return ids, nil
|
||||
}
|
||||
func (r *apiRepo) SetAPIRoles(ctx context.Context, path, method string, ids []uint) error {
|
||||
return r.data.gormDB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
// A path/method need not be present in sys_apis when replacing
|
||||
// all matching policy rows. Do not validate or deduplicate authority IDs.
|
||||
if err := deletePoliciesForPath(tx, path, method); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
rules := make([]casbinRulePO, 0, len(ids))
|
||||
for _, aid := range ids {
|
||||
rules = append(rules, newPolicyRule(aid, path, method))
|
||||
}
|
||||
return tx.Create(&rules).Error
|
||||
})
|
||||
}
|
||||
func (r *apiRepo) Authorize(ctx context.Context, aid uint, path, method string) (bool, error) {
|
||||
rows, err := policyRowsForAuthority(r.data.gormDB.WithContext(ctx), aid)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
model, err := casbinmodel.NewModelFromString(`[request_definition]
|
||||
r = sub, obj, act
|
||||
[policy_definition]
|
||||
p = sub, obj, act
|
||||
[policy_effect]
|
||||
e = some(where (p.eft == allow))
|
||||
[matchers]
|
||||
m = r.sub == p.sub && keyMatch2(r.obj, p.obj) && r.act == p.act`)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
enforcer, err := casbin.NewEnforcer(model)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
subject := strconv.FormatUint(uint64(aid), 10)
|
||||
for _, policy := range rows {
|
||||
if _, err := enforcer.AddPolicy(subject, policy.V1, policy.V2); err != nil {
|
||||
return false, err
|
||||
}
|
||||
}
|
||||
return enforcer.Enforce(subject, path, method)
|
||||
}
|
||||
func (r *apiRepo) PolicyPaths(ctx context.Context, aid uint) ([]*biz.API, error) {
|
||||
rows, err := policyRowsForAuthority(r.data.gormDB.WithContext(ctx), aid)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out []*biz.API
|
||||
if len(rows) > 0 {
|
||||
out = make([]*biz.API, 0, len(rows))
|
||||
}
|
||||
for _, row := range rows {
|
||||
out = append(out, &biz.API{Path: row.V1, Method: row.V2})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
func (r *apiRepo) SetPolicyPaths(ctx context.Context, aid uint, paths []*biz.API) error {
|
||||
if err := (&authorityAccessRepo{data: r.data}).checkAuthorityIDAuth(ctx, aid); err != nil {
|
||||
return err
|
||||
}
|
||||
config := r.data.runtime.Admin()
|
||||
if actor, ok := biz.ActorFromContext(ctx); ok && config != nil && config.System != nil && config.System.UseStrictAuth {
|
||||
var authority authorityPO
|
||||
if err := r.data.gormDB.WithContext(ctx).Where("authority_id = ?", actor.AuthorityID).First(&authority).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
var registered []apiPO
|
||||
if err := r.data.gormDB.WithContext(ctx).Find(®istered).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
allowedSet := make(map[string]bool, len(registered))
|
||||
if authority.ParentID == nil || *authority.ParentID == 0 {
|
||||
for _, item := range registered {
|
||||
allowedSet[item.Path+"\x00"+item.Method] = true
|
||||
}
|
||||
} else {
|
||||
policies, err := policyRowsForAuthority(r.data.gormDB.WithContext(ctx), actor.AuthorityID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
policySet := make(map[string]bool, len(policies))
|
||||
for _, item := range policies {
|
||||
policySet[item.V1+"\x00"+item.V2] = true
|
||||
}
|
||||
for _, item := range registered {
|
||||
key := item.Path + "\x00" + item.Method
|
||||
if policySet[key] {
|
||||
allowedSet[key] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, item := range paths {
|
||||
if !allowedSet[item.Path+"\x00"+item.Method] {
|
||||
return errors.New("存在api不在权限列表中")
|
||||
}
|
||||
}
|
||||
}
|
||||
db := r.data.gormDB.WithContext(ctx)
|
||||
// The reference enforcer removes the old authority policies before it
|
||||
// attempts to add the replacement set. Keep that ordering visible even
|
||||
// though Kra reads policies directly from the database rather than through
|
||||
// an in-memory enforcer.
|
||||
if err := deletePoliciesForAuthority(db, aid); err != nil {
|
||||
return err
|
||||
}
|
||||
// Keep the legacy relation table clean for upgraded installations. It is
|
||||
// not consulted for authorization anymore.
|
||||
if err := db.Where("authority_id = ?", aid).Delete(&authorityAPIPO{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
rules := make([]casbinRulePO, 0, len(paths))
|
||||
seen := make(map[string]struct{})
|
||||
for _, path := range paths {
|
||||
key := strconv.FormatUint(uint64(aid), 10) + path.Path + path.Method
|
||||
if _, ok := seen[key]; ok {
|
||||
continue
|
||||
}
|
||||
seen[key] = struct{}{}
|
||||
rules = append(rules, newPolicyRule(aid, path.Path, path.Method))
|
||||
}
|
||||
if len(rules) > 0 {
|
||||
return db.Clauses(clause.OnConflict{DoNothing: true}).Create(&rules).Error
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
@ -1,64 +0,0 @@
|
|||
package data
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"kra/internal/biz"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func (r *apiRepo) IgnoredAPIs(ctx context.Context) ([]*biz.API, error) {
|
||||
var pos []ignoredAPIPO
|
||||
if err := r.data.gormDB.WithContext(ctx).Find(&pos).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]*biz.API, 0, len(pos))
|
||||
for _, po := range pos {
|
||||
out = append(out, &biz.API{Path: po.Path, Method: po.Method})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
func (r *apiRepo) SetAPIIgnored(ctx context.Context, path, method string, ignored bool) error {
|
||||
po := ignoredAPIPO{Path: path, Method: method}
|
||||
if ignored {
|
||||
// The compatible endpoint creates an ignore row on every request (the table has no
|
||||
// path/method uniqueness constraint); retain that observable behavior.
|
||||
return r.data.gormDB.WithContext(ctx).Create(&po).Error
|
||||
}
|
||||
return r.data.gormDB.WithContext(ctx).Unscoped().Where("path = ? AND method = ?", po.Path, po.Method).Delete(&ignoredAPIPO{}).Error
|
||||
}
|
||||
func (r *apiRepo) ApplyAPISync(ctx context.Context, added, deleted []*biz.API) error {
|
||||
return r.data.gormDB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
if len(added) > 0 {
|
||||
pos := make([]apiPO, 0, len(added))
|
||||
for _, item := range added {
|
||||
pos = append(pos, apiPO{Path: item.Path, Method: item.Method, Description: item.Description, APIGroup: item.APIGroup})
|
||||
}
|
||||
// Insert the submitted newApis slice as-is. Do not silently
|
||||
// collapse repeated/existing path+method pairs here; sys_apis itself
|
||||
// intentionally has no uniqueness constraint.
|
||||
if err := tx.Create(&pos).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, item := range deleted {
|
||||
var ids []uint
|
||||
if err := tx.Model(&apiPO{}).Where("path = ? AND method = ?", item.Path, item.Method).Pluck("id", &ids).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if len(ids) > 0 {
|
||||
if err := deletePoliciesForPath(tx, item.Path, item.Method); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.Where("api_id IN ?", ids).Delete(&authorityAPIPO{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.Where("id IN ?", ids).Delete(&apiPO{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
|
@ -28,7 +28,7 @@ func TestLogViewerReadsNestedCategoryFiles(t *testing.T) {
|
|||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(files) != 1 || files[0].Path != "http/access.log" {
|
||||
if len(files) != 1 || files[0].Path != filepath.Join("http", "access.log") {
|
||||
t.Fatalf("unexpected nested log files: %+v", files)
|
||||
}
|
||||
content, err := repo.LogContent(context.Background(), date, "http/access.log", nil)
|
||||
|
|
|
|||
|
|
@ -25,6 +25,45 @@ func NewAudit(service *service.AuditService, recorder *service.AuditRecorder, lo
|
|||
return &Audit{service: service, recorder: recorder, logs: logs, logger: logger}
|
||||
}
|
||||
|
||||
func page(c *gin.Context) (int, int, error) {
|
||||
var value, size int
|
||||
if raw, exists := c.GetQuery("page"); exists && raw != "" {
|
||||
parsed, err := strconv.Atoi(raw)
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
value = parsed
|
||||
}
|
||||
if raw, exists := c.GetQuery("pageSize"); exists && raw != "" {
|
||||
parsed, err := strconv.Atoi(raw)
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
size = parsed
|
||||
}
|
||||
return value, size, nil
|
||||
}
|
||||
|
||||
func queryUintValue(c *gin.Context, key string) (uint, bool, error) {
|
||||
raw, ok := c.GetQuery(key)
|
||||
if !ok || raw == "" {
|
||||
return 0, false, nil
|
||||
}
|
||||
value, err := strconv.ParseUint(raw, 10, 0)
|
||||
return uint(value), true, err
|
||||
}
|
||||
func IDsFromQuery(c *gin.Context) []uint {
|
||||
values := c.QueryArray("IDs[]")
|
||||
ids := make([]uint, 0, len(values))
|
||||
for _, value := range values {
|
||||
id, _ := strconv.ParseUint(value, 10, 64)
|
||||
if id > 0 {
|
||||
ids = append(ids, uint(id))
|
||||
}
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
func (h *Audit) Operations(c *gin.Context) {
|
||||
var req dto.OperationRecordSearchRequest
|
||||
if err := c.ShouldBindQuery(&req); err != nil {
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ package handler
|
|||
import (
|
||||
"strconv"
|
||||
|
||||
"kra/internal/biz"
|
||||
"kra/internal/server/httpx"
|
||||
"kra/internal/service"
|
||||
"kra/internal/service/dto"
|
||||
|
|
@ -174,7 +175,7 @@ func (h *Dictionary) Details(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
}
|
||||
filter := dto.DictionaryDetailListRequest{DictionaryID: uint(dictionaryID), Label: c.Query("label"), Value: c.Query("value")}
|
||||
filter := biz.DictionaryDetailFilter{DictionaryID: uint(dictionaryID), Label: c.Query("label"), Value: c.Query("value")}
|
||||
if raw, exists := c.GetQuery("status"); exists {
|
||||
value, parseErr := strconv.ParseBool(raw)
|
||||
if parseErr != nil {
|
||||
|
|
@ -200,7 +201,7 @@ func (h *Dictionary) Details(c *gin.Context) {
|
|||
}
|
||||
filter.Level = &value
|
||||
}
|
||||
items, total, err := h.service.DictionaryDetailsRequest(c.Request.Context(), p, size, filter)
|
||||
items, total, err := h.service.DictionaryDetails(c.Request.Context(), p, size, filter)
|
||||
if err != nil {
|
||||
httpx.Fail(c, "获取失败")
|
||||
return
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ package handler
|
|||
import (
|
||||
"strconv"
|
||||
|
||||
"kra/internal/biz"
|
||||
"kra/internal/server/httpx"
|
||||
servermiddleware "kra/internal/server/middleware"
|
||||
"kra/internal/service"
|
||||
|
|
@ -46,7 +47,7 @@ func (h *Media) List(c *gin.Context) {
|
|||
httpx.Fail(c, err.Error())
|
||||
return
|
||||
}
|
||||
items, total, err := h.service.MediaListRequest(c.Request.Context(), &req)
|
||||
items, total, err := h.service.MediaList(c.Request.Context(), biz.MediaFilter{Page: req.Page, PageSize: req.PageSize, Keyword: req.Keyword, CategoryID: req.ClassID, Tag: req.Tag, UserID: req.UserID, StartCreatedAt: req.StartCreatedAt, EndCreatedAt: req.EndCreatedAt, OrderKey: req.OrderKey, Desc: req.Desc})
|
||||
if err != nil {
|
||||
httpx.Fail(c, "获取失败")
|
||||
return
|
||||
|
|
|
|||
|
|
@ -120,7 +120,7 @@ func (h *Public) InitializeDatabase(engine *gin.Engine) gin.HandlerFunc {
|
|||
httpx.Fail(c, "已存在数据库配置")
|
||||
return
|
||||
}
|
||||
var input dto.DatabaseInitRequest
|
||||
var input service.DatabaseInit
|
||||
if c.ShouldBindJSON(&input) != nil {
|
||||
httpx.Fail(c, "参数校验不通过")
|
||||
return
|
||||
|
|
|
|||
|
|
@ -1,38 +0,0 @@
|
|||
package handler
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func page(c *gin.Context) (int, int, error) {
|
||||
var value, size int
|
||||
if raw, exists := c.GetQuery("page"); exists && raw != "" {
|
||||
parsed, err := strconv.Atoi(raw)
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
value = parsed
|
||||
}
|
||||
if raw, exists := c.GetQuery("pageSize"); exists && raw != "" {
|
||||
parsed, err := strconv.Atoi(raw)
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
size = parsed
|
||||
}
|
||||
return value, size, nil
|
||||
}
|
||||
|
||||
func IDsFromQuery(c *gin.Context) []uint {
|
||||
values := c.QueryArray("IDs[]")
|
||||
ids := make([]uint, 0, len(values))
|
||||
for _, value := range values {
|
||||
id, _ := strconv.ParseUint(value, 10, 64)
|
||||
if id > 0 {
|
||||
ids = append(ids, uint(id))
|
||||
}
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
|
@ -108,7 +108,8 @@ func (h *User) UpdateSelf(c *gin.Context) {
|
|||
httpx.Fail(c, err.Error())
|
||||
return
|
||||
}
|
||||
if err := h.service.UpdateSelfUserRequest(c.Request.Context(), claims.ID, &req); err != nil {
|
||||
value := service.UserInput{ID: claims.ID, NickName: req.NickName, HeaderImg: req.HeaderImg, Phone: req.Phone, Email: req.Email, Enable: req.Enable}
|
||||
if err := h.service.UpdateSelfUser(c.Request.Context(), value); err != nil {
|
||||
httpx.Fail(c, "修改失败")
|
||||
return
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ import (
|
|||
"strings"
|
||||
"sync"
|
||||
|
||||
"kra/internal/routeinfo"
|
||||
"kra/internal/service"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
swaggerFiles "github.com/swaggo/files"
|
||||
|
|
@ -83,7 +83,7 @@ func buildSwaggerDocument(routes []gin.RouteInfo, prefix, version string) string
|
|||
apiPath = "/"
|
||||
}
|
||||
documentPath := swaggerPathParameter.ReplaceAllString(apiPath, `{$1}`)
|
||||
group, description := routeinfo.Metadata(route.Method, apiPath)
|
||||
group, description := service.RouteMetadata(route.Method, apiPath)
|
||||
if description == "" {
|
||||
description = route.Method + " " + apiPath
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
package routeinfo
|
||||
package service
|
||||
|
||||
import "strings"
|
||||
|
||||
|
|
@ -171,18 +171,15 @@ var apiMetadata = map[string]apiMetadataValue{
|
|||
"PUT /user/setUserInfo": {group: "系统用户", description: "设置用户信息"},
|
||||
}
|
||||
|
||||
// Metadata returns the administration group and description for a route.
|
||||
func Metadata(method, path string) (string, string) {
|
||||
func routeMetadata(method, path string) (string, string) {
|
||||
if value, ok := apiMetadata[strings.ToUpper(method)+" "+path]; ok {
|
||||
return value.group, value.description
|
||||
}
|
||||
return routeGroup(path), ""
|
||||
}
|
||||
|
||||
func routeGroup(path string) string {
|
||||
parts := strings.Split(strings.Trim(path, "/"), "/")
|
||||
if len(parts) > 0 && parts[0] != "" {
|
||||
return parts[0]
|
||||
}
|
||||
return "base"
|
||||
// RouteMetadata exposes the administration API grouping and description to
|
||||
// transport-level documentation without leaking the metadata table itself.
|
||||
func RouteMetadata(method, path string) (string, string) {
|
||||
return routeMetadata(method, path)
|
||||
}
|
||||
|
|
@ -7,6 +7,13 @@ import (
|
|||
"kra/internal/service/dto"
|
||||
)
|
||||
|
||||
type LoginResult struct {
|
||||
User *dto.UserResponse `json:"user"`
|
||||
Token string `json:"token"`
|
||||
ExpiresAt int64 `json:"expiresAt"`
|
||||
NeedChangePassword bool `json:"needChangePassword"`
|
||||
}
|
||||
|
||||
type AuthService struct {
|
||||
uc *biz.AuthenticationUsecase
|
||||
}
|
||||
|
|
@ -15,11 +22,11 @@ func NewAuthService(uc *biz.AuthenticationUsecase) *AuthService {
|
|||
return &AuthService{uc: uc}
|
||||
}
|
||||
|
||||
func loginResult(value *biz.AuthenticationResult) *dto.LoginResponse {
|
||||
return &dto.LoginResponse{User: convertUser(value.User), Token: value.Token, ExpiresAt: value.ExpiresAt.UnixMilli(), NeedChangePassword: value.NeedChangePassword}
|
||||
func loginResult(value *biz.AuthenticationResult) *LoginResult {
|
||||
return &LoginResult{User: convertUser(value.User), Token: value.Token, ExpiresAt: value.ExpiresAt.UnixMilli(), NeedChangePassword: value.NeedChangePassword}
|
||||
}
|
||||
|
||||
func (s *AuthService) Login(ctx context.Context, req *dto.LoginRequest, ip, agent string) (*dto.LoginResponse, error) {
|
||||
func (s *AuthService) Login(ctx context.Context, req *dto.LoginRequest, ip, agent string) (*LoginResult, error) {
|
||||
value, err := s.uc.Login(ctx, &biz.LoginAttempt{Username: req.Username, Password: req.Password, CaptchaID: req.CaptchaID, Captcha: req.Captcha, IP: ip, Agent: agent})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
|
@ -27,7 +34,7 @@ func (s *AuthService) Login(ctx context.Context, req *dto.LoginRequest, ip, agen
|
|||
return loginResult(value), nil
|
||||
}
|
||||
|
||||
func (s *AuthService) SwitchAuthority(ctx context.Context, claims *biz.AuthClaims, authorityID uint) (*dto.LoginResponse, error) {
|
||||
func (s *AuthService) SwitchAuthority(ctx context.Context, claims *biz.AuthClaims, authorityID uint) (*LoginResult, error) {
|
||||
value, err := s.uc.SwitchAuthority(ctx, claims, authorityID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
|
|
|||
|
|
@ -119,16 +119,6 @@ func (s *DictionaryService) DictionaryDetails(ctx context.Context, page, size in
|
|||
}
|
||||
return out, total, nil
|
||||
}
|
||||
func (s *DictionaryService) DictionaryDetailsRequest(ctx context.Context, page, size int, request dto.DictionaryDetailListRequest) ([]*dto.DictionaryDetailResponse, int64, error) {
|
||||
return s.DictionaryDetails(ctx, page, size, biz.DictionaryDetailFilter{
|
||||
DictionaryID: request.DictionaryID,
|
||||
Label: request.Label,
|
||||
Value: request.Value,
|
||||
Status: request.Status,
|
||||
ParentID: request.ParentID,
|
||||
Level: request.Level,
|
||||
})
|
||||
}
|
||||
func (s *DictionaryService) DictionaryDetail(ctx context.Context, id uint) (*dto.DictionaryDetailResponse, error) {
|
||||
v, err := s.uc.FindDictionaryDetail(ctx, id)
|
||||
if err != nil {
|
||||
|
|
|
|||
|
|
@ -1,8 +0,0 @@
|
|||
package dto
|
||||
|
||||
type LoginResponse struct {
|
||||
User *UserResponse `json:"user"`
|
||||
Token string `json:"token"`
|
||||
ExpiresAt int64 `json:"expiresAt"`
|
||||
NeedChangePassword bool `json:"needChangePassword"`
|
||||
}
|
||||
|
|
@ -30,15 +30,6 @@ type DictionaryDetailsByParentRequest struct {
|
|||
ParentID *uint `json:"parentID" form:"parentID"`
|
||||
IncludeChildren bool `json:"includeChildren" form:"includeChildren"`
|
||||
}
|
||||
|
||||
type DictionaryDetailListRequest struct {
|
||||
DictionaryID uint
|
||||
Label string
|
||||
Value string
|
||||
Status *bool
|
||||
ParentID *uint
|
||||
Level *int
|
||||
}
|
||||
type SystemParameterRequest struct {
|
||||
ID uint `json:"ID" form:"ID"`
|
||||
CreatedAt time.Time `json:"CreatedAt" form:"CreatedAt"`
|
||||
|
|
|
|||
|
|
@ -1,13 +0,0 @@
|
|||
package dto
|
||||
|
||||
type DatabaseInitRequest struct {
|
||||
DBType string `json:"dbType"`
|
||||
Host string `json:"host"`
|
||||
Port string `json:"port"`
|
||||
UserName string `json:"userName"`
|
||||
Password string `json:"password"`
|
||||
DBName string `json:"dbName" binding:"required"`
|
||||
DBPath string `json:"dbPath"`
|
||||
Template string `json:"template"`
|
||||
AdminPassword string `json:"adminPassword" binding:"required"`
|
||||
}
|
||||
|
|
@ -57,14 +57,6 @@ func (s *MediaService) MediaList(ctx context.Context, filter biz.MediaFilter) ([
|
|||
}
|
||||
return out, total, nil
|
||||
}
|
||||
func (s *MediaService) MediaListRequest(ctx context.Context, request *dto.MediaListRequest) ([]*dto.MediaResponse, int64, error) {
|
||||
return s.MediaList(ctx, biz.MediaFilter{
|
||||
Page: request.Page, PageSize: request.PageSize, Keyword: request.Keyword,
|
||||
CategoryID: request.ClassID, Tag: request.Tag, UserID: request.UserID,
|
||||
StartCreatedAt: request.StartCreatedAt, EndCreatedAt: request.EndCreatedAt,
|
||||
OrderKey: request.OrderKey, Desc: request.Desc,
|
||||
})
|
||||
}
|
||||
func (s *MediaService) Delete(ctx context.Context, id uint) error { return s.uc.Delete(ctx, id) }
|
||||
func (s *MediaService) Rename(ctx context.Context, id uint, name string) error {
|
||||
return s.uc.UpdateMediaName(ctx, id, name)
|
||||
|
|
|
|||
|
|
@ -5,11 +5,22 @@ import (
|
|||
"strings"
|
||||
|
||||
"kra/internal/biz"
|
||||
"kra/internal/routeinfo"
|
||||
"kra/internal/service/dto"
|
||||
)
|
||||
|
||||
func (s *SystemConfigService) Initialize(ctx context.Context, input *dto.DatabaseInitRequest, apis []*biz.API) error {
|
||||
type DatabaseInit struct {
|
||||
DBType string `json:"dbType"`
|
||||
Host string `json:"host"`
|
||||
Port string `json:"port"`
|
||||
UserName string `json:"userName"`
|
||||
Password string `json:"password"`
|
||||
DBName string `json:"dbName" binding:"required"`
|
||||
DBPath string `json:"dbPath"`
|
||||
Template string `json:"template"`
|
||||
AdminPassword string `json:"adminPassword" binding:"required"`
|
||||
}
|
||||
|
||||
func (s *SystemConfigService) Initialize(ctx context.Context, input *DatabaseInit, apis []*biz.API) error {
|
||||
driver, config := input.DBType, ""
|
||||
switch driver {
|
||||
case "mysql":
|
||||
|
|
@ -26,7 +37,7 @@ func (s *SystemConfigService) Initialize(ctx context.Context, input *dto.Databas
|
|||
return s.uc.Initialize(ctx, &biz.DatabaseConfig{Driver: driver, Host: input.Host, Port: input.Port, User: input.UserName, Password: input.Password, Name: input.DBName, Path: input.DBPath, Config: config, Template: input.Template, AdminPassword: input.AdminPassword, APIs: apis})
|
||||
}
|
||||
|
||||
func (s *SystemConfigService) InitializeRoutes(ctx context.Context, input *dto.DatabaseInitRequest, routes []dto.Route) error {
|
||||
func (s *SystemConfigService) InitializeRoutes(ctx context.Context, input *DatabaseInit, routes []dto.Route) error {
|
||||
apis := make([]*biz.API, 0, len(routes))
|
||||
for _, route := range routes {
|
||||
path := route.Path
|
||||
|
|
@ -36,8 +47,16 @@ func (s *SystemConfigService) InitializeRoutes(ctx context.Context, input *dto.D
|
|||
path = "/"
|
||||
}
|
||||
}
|
||||
group, description := routeinfo.Metadata(route.Method, path)
|
||||
group, description := routeMetadata(route.Method, path)
|
||||
apis = append(apis, &biz.API{Path: path, Method: route.Method, APIGroup: group, Description: description})
|
||||
}
|
||||
return s.Initialize(ctx, input, apis)
|
||||
}
|
||||
|
||||
func routeGroup(path string) string {
|
||||
parts := strings.Split(strings.Trim(path, "/"), "/")
|
||||
if len(parts) > 0 && parts[0] != "" {
|
||||
return parts[0]
|
||||
}
|
||||
return "base"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ import (
|
|||
"kra/internal/service/dto"
|
||||
)
|
||||
|
||||
type userInput struct {
|
||||
type UserInput struct {
|
||||
ID uint
|
||||
Username, Password, NickName, HeaderImg, Phone, Email string
|
||||
AuthorityID uint
|
||||
|
|
@ -24,20 +24,17 @@ func NewUserService(uc *biz.UserUsecase, settings *SecurityService) *UserService
|
|||
return &UserService{uc: uc, settings: settings}
|
||||
}
|
||||
|
||||
func userRequestInput(value *dto.UserRequest) userInput {
|
||||
return userInput{ID: value.ID, Username: value.Username, Password: value.Password, NickName: value.NickName, HeaderImg: value.HeaderImg, AuthorityID: value.AuthorityID, AuthorityIDs: value.AuthorityIDs, Enable: value.Enable, Phone: value.Phone, Email: value.Email}
|
||||
func userInput(value *dto.UserRequest) UserInput {
|
||||
return UserInput{ID: value.ID, Username: value.Username, Password: value.Password, NickName: value.NickName, HeaderImg: value.HeaderImg, AuthorityID: value.AuthorityID, AuthorityIDs: value.AuthorityIDs, Enable: value.Enable, Phone: value.Phone, Email: value.Email}
|
||||
}
|
||||
func (s *UserService) ListUsersRequest(ctx context.Context, value *dto.UserListRequest) ([]*dto.UserResponse, int64, error) {
|
||||
return s.ListUsers(ctx, value.Page, value.PageSize, &biz.UserListFilter{Username: value.Username, NickName: value.NickName, Phone: value.Phone, Email: value.Email, OrderKey: value.OrderKey, Desc: value.Desc})
|
||||
}
|
||||
func (s *UserService) CreateUserRequest(ctx context.Context, value *dto.UserRequest) (*dto.UserResponse, error) {
|
||||
return s.createUser(ctx, userRequestInput(value))
|
||||
return s.CreateUser(ctx, userInput(value))
|
||||
}
|
||||
func (s *UserService) UpdateUserRequest(ctx context.Context, value *dto.UserRequest) error {
|
||||
return s.updateUser(ctx, userRequestInput(value))
|
||||
}
|
||||
func (s *UserService) UpdateSelfUserRequest(ctx context.Context, id uint, value *dto.SelfUserRequest) error {
|
||||
return s.updateSelfUser(ctx, userInput{ID: id, NickName: value.NickName, HeaderImg: value.HeaderImg, Phone: value.Phone, Email: value.Email, Enable: value.Enable})
|
||||
return s.UpdateUser(ctx, userInput(value))
|
||||
}
|
||||
|
||||
func (s *UserService) User(ctx context.Context, id uint) (*dto.UserResponse, error) {
|
||||
|
|
@ -88,7 +85,7 @@ func (s *UserService) Authorities(ctx context.Context) ([]*dto.AuthorityResponse
|
|||
return result, nil
|
||||
}
|
||||
|
||||
func (s *UserService) createUser(ctx context.Context, input userInput) (*dto.UserResponse, error) {
|
||||
func (s *UserService) CreateUser(ctx context.Context, input UserInput) (*dto.UserResponse, error) {
|
||||
if err := s.settings.ValidatePassword(ctx, input.Password); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
|
@ -100,12 +97,12 @@ func (s *UserService) createUser(ctx context.Context, input userInput) (*dto.Use
|
|||
}
|
||||
return convertUser(user), nil
|
||||
}
|
||||
func (s *UserService) updateUser(ctx context.Context, input userInput) error {
|
||||
func (s *UserService) UpdateUser(ctx context.Context, input UserInput) error {
|
||||
// The compatible ChangeUserInfo payload uses authorityIds for role assignment; the
|
||||
// standalone authorityId field is not applied by setUserInfo.
|
||||
return s.uc.UpdateUser(ctx, &biz.User{ID: input.ID, NickName: input.NickName, HeaderImg: input.HeaderImg, Phone: input.Phone, Email: input.Email, Enable: input.Enable}, input.AuthorityIDs)
|
||||
}
|
||||
func (s *UserService) updateSelfUser(ctx context.Context, input userInput) error {
|
||||
func (s *UserService) UpdateSelfUser(ctx context.Context, input UserInput) error {
|
||||
return s.uc.UpdateSelfUser(ctx, &biz.User{ID: input.ID, NickName: input.NickName, HeaderImg: input.HeaderImg, Phone: input.Phone, Email: input.Email, Enable: input.Enable})
|
||||
}
|
||||
func (s *UserService) DeleteUser(ctx context.Context, id uint) error {
|
||||
|
|
|
|||
|
|
@ -104,7 +104,6 @@ func TestErrorSinkSkipsGORMBridge(t *testing.T) {
|
|||
})}
|
||||
base := zapcore.NewNopCore()
|
||||
core := &routedFileCore{base: base, encoder: zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig()), level: zapcore.ErrorLevel, root: root, state: &routedFileState{writers: map[string]*DailyWriter{}}, errorSink: state}
|
||||
defer core.Close()
|
||||
for _, filename := range []string{"/tmp/gorm_logger_writer.go", "/workspace/internal/data/gorm_logger.go"} {
|
||||
if err := core.Write(zapcore.Entry{Level: zapcore.ErrorLevel, Message: "database failed", Caller: zapcore.EntryCaller{Defined: true, File: filename, Line: 10}}, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,24 @@
|
|||
package validate
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/go-kratos/kratos/v3/errors"
|
||||
"github.com/go-kratos/kratos/v3/middleware"
|
||||
"go.einride.tech/aip/fieldbehavior"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
// Middleware is a middleware that validates the request message with [FieldBehavior](https://google.aip.dev/203)
|
||||
func Middleware() middleware.Middleware {
|
||||
return func(handler middleware.Handler) middleware.Handler {
|
||||
return func(ctx context.Context, req any) (reply any, err error) {
|
||||
if msg, ok := req.(proto.Message); ok {
|
||||
if err := fieldbehavior.ValidateRequiredFields(msg); err != nil {
|
||||
return nil, errors.BadRequest("VALIDATOR", err.Error()).WithCause(err)
|
||||
}
|
||||
}
|
||||
return handler(ctx, req)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -400,10 +400,8 @@
|
|||
name: searchName.value.trim()
|
||||
})
|
||||
if (res.code === 0) {
|
||||
// 搜索无结果时同步清空当前选中项。
|
||||
const dictionaries = Array.isArray(res.data) ? res.data : []
|
||||
dictionaryData.value = dictionaries
|
||||
selectID.value = dictionaries[0]?.ID ?? 0
|
||||
dictionaryData.value = res.data
|
||||
selectID.value = res.data[0].ID
|
||||
// 更新可选父级字典列表
|
||||
updateAvailableParentDictionaries()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -283,11 +283,7 @@
|
|||
|
||||
// 获取树形数据
|
||||
const getTreeData = async () => {
|
||||
if (!props.sysDictionaryID) {
|
||||
treeData.value = []
|
||||
displayTreeData.value = []
|
||||
return
|
||||
}
|
||||
if (!props.sysDictionaryID) return
|
||||
try {
|
||||
const res = await getDictionaryTreeList({
|
||||
sysDictionaryID: props.sysDictionaryID
|
||||
|
|
|
|||
Loading…
Reference in New Issue