Compare commits

...

3 Commits

Author SHA1 Message Date
Yvan 05b49cd86a 优化 2026-08-17 10:46:06 +08:00
Yvan a601bc1760 优化 2026-08-17 08:58:12 +08:00
Yvan 9715b2ef1a 优化 2026-08-17 07:44:52 +08:00
24 changed files with 357 additions and 329 deletions

View File

@ -8,10 +8,7 @@ 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 }
@ -181,204 +178,3 @@ 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(&registered).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
})
}

161
internal/data/api_policy.go Normal file
View File

@ -0,0 +1,161 @@
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(&registered).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
}

64
internal/data/api_sync.go Normal file
View File

@ -0,0 +1,64 @@
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
})
}

View File

@ -28,7 +28,7 @@ func TestLogViewerReadsNestedCategoryFiles(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if len(files) != 1 || files[0].Path != filepath.Join("http", "access.log") {
if len(files) != 1 || files[0].Path != "http/access.log" {
t.Fatalf("unexpected nested log files: %+v", files)
}
content, err := repo.LogContent(context.Background(), date, "http/access.log", nil)

View File

@ -1,4 +1,4 @@
package service
package routeinfo
import "strings"
@ -171,15 +171,18 @@ var apiMetadata = map[string]apiMetadataValue{
"PUT /user/setUserInfo": {group: "系统用户", description: "设置用户信息"},
}
func routeMetadata(method, path string) (string, string) {
// Metadata returns the administration group and description for a route.
func Metadata(method, path string) (string, string) {
if value, ok := apiMetadata[strings.ToUpper(method)+" "+path]; ok {
return value.group, value.description
}
return routeGroup(path), ""
}
// 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)
func routeGroup(path string) string {
parts := strings.Split(strings.Trim(path, "/"), "/")
if len(parts) > 0 && parts[0] != "" {
return parts[0]
}
return "base"
}

View File

@ -25,45 +25,6 @@ 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 {

View File

@ -3,7 +3,6 @@ package handler
import (
"strconv"
"kra/internal/biz"
"kra/internal/server/httpx"
"kra/internal/service"
"kra/internal/service/dto"
@ -175,7 +174,7 @@ func (h *Dictionary) Details(c *gin.Context) {
return
}
}
filter := biz.DictionaryDetailFilter{DictionaryID: uint(dictionaryID), Label: c.Query("label"), Value: c.Query("value")}
filter := dto.DictionaryDetailListRequest{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 {
@ -201,7 +200,7 @@ func (h *Dictionary) Details(c *gin.Context) {
}
filter.Level = &value
}
items, total, err := h.service.DictionaryDetails(c.Request.Context(), p, size, filter)
items, total, err := h.service.DictionaryDetailsRequest(c.Request.Context(), p, size, filter)
if err != nil {
httpx.Fail(c, "获取失败")
return

View File

@ -3,7 +3,6 @@ package handler
import (
"strconv"
"kra/internal/biz"
"kra/internal/server/httpx"
servermiddleware "kra/internal/server/middleware"
"kra/internal/service"
@ -47,7 +46,7 @@ func (h *Media) List(c *gin.Context) {
httpx.Fail(c, err.Error())
return
}
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})
items, total, err := h.service.MediaListRequest(c.Request.Context(), &req)
if err != nil {
httpx.Fail(c, "获取失败")
return

View File

@ -120,7 +120,7 @@ func (h *Public) InitializeDatabase(engine *gin.Engine) gin.HandlerFunc {
httpx.Fail(c, "已存在数据库配置")
return
}
var input service.DatabaseInit
var input dto.DatabaseInitRequest
if c.ShouldBindJSON(&input) != nil {
httpx.Fail(c, "参数校验不通过")
return

View File

@ -0,0 +1,38 @@
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
}

View File

@ -108,8 +108,7 @@ func (h *User) UpdateSelf(c *gin.Context) {
httpx.Fail(c, err.Error())
return
}
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 {
if err := h.service.UpdateSelfUserRequest(c.Request.Context(), claims.ID, &req); err != nil {
httpx.Fail(c, "修改失败")
return
}

View File

@ -8,7 +8,7 @@ import (
"strings"
"sync"
"kra/internal/service"
"kra/internal/routeinfo"
"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 := service.RouteMetadata(route.Method, apiPath)
group, description := routeinfo.Metadata(route.Method, apiPath)
if description == "" {
description = route.Method + " " + apiPath
}

View File

@ -7,13 +7,6 @@ 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
}
@ -22,11 +15,11 @@ func NewAuthService(uc *biz.AuthenticationUsecase) *AuthService {
return &AuthService{uc: uc}
}
func loginResult(value *biz.AuthenticationResult) *LoginResult {
return &LoginResult{User: convertUser(value.User), Token: value.Token, ExpiresAt: value.ExpiresAt.UnixMilli(), NeedChangePassword: value.NeedChangePassword}
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 (s *AuthService) Login(ctx context.Context, req *dto.LoginRequest, ip, agent string) (*LoginResult, error) {
func (s *AuthService) Login(ctx context.Context, req *dto.LoginRequest, ip, agent string) (*dto.LoginResponse, 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
@ -34,7 +27,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) (*LoginResult, error) {
func (s *AuthService) SwitchAuthority(ctx context.Context, claims *biz.AuthClaims, authorityID uint) (*dto.LoginResponse, error) {
value, err := s.uc.SwitchAuthority(ctx, claims, authorityID)
if err != nil {
return nil, err

View File

@ -119,6 +119,16 @@ 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 {

View File

@ -0,0 +1,8 @@
package dto
type LoginResponse struct {
User *UserResponse `json:"user"`
Token string `json:"token"`
ExpiresAt int64 `json:"expiresAt"`
NeedChangePassword bool `json:"needChangePassword"`
}

View File

@ -30,6 +30,15 @@ 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"`

View File

@ -0,0 +1,13 @@
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"`
}

View File

@ -57,6 +57,14 @@ 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)

View File

@ -5,22 +5,11 @@ import (
"strings"
"kra/internal/biz"
"kra/internal/routeinfo"
"kra/internal/service/dto"
)
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 {
func (s *SystemConfigService) Initialize(ctx context.Context, input *dto.DatabaseInitRequest, apis []*biz.API) error {
driver, config := input.DBType, ""
switch driver {
case "mysql":
@ -37,7 +26,7 @@ func (s *SystemConfigService) Initialize(ctx context.Context, input *DatabaseIni
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 *DatabaseInit, routes []dto.Route) error {
func (s *SystemConfigService) InitializeRoutes(ctx context.Context, input *dto.DatabaseInitRequest, routes []dto.Route) error {
apis := make([]*biz.API, 0, len(routes))
for _, route := range routes {
path := route.Path
@ -47,16 +36,8 @@ func (s *SystemConfigService) InitializeRoutes(ctx context.Context, input *Datab
path = "/"
}
}
group, description := routeMetadata(route.Method, path)
group, description := routeinfo.Metadata(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"
}

View File

@ -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,17 +24,20 @@ func NewUserService(uc *biz.UserUsecase, settings *SecurityService) *UserService
return &UserService{uc: uc, settings: settings}
}
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 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 (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, userInput(value))
return s.createUser(ctx, userRequestInput(value))
}
func (s *UserService) UpdateUserRequest(ctx context.Context, value *dto.UserRequest) error {
return s.UpdateUser(ctx, userInput(value))
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})
}
func (s *UserService) User(ctx context.Context, id uint) (*dto.UserResponse, error) {
@ -85,7 +88,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
}
@ -97,12 +100,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 {

View File

@ -104,6 +104,7 @@ 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)

View File

@ -1,24 +0,0 @@
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)
}
}
}

View File

@ -400,8 +400,10 @@
name: searchName.value.trim()
})
if (res.code === 0) {
dictionaryData.value = res.data
selectID.value = res.data[0].ID
//
const dictionaries = Array.isArray(res.data) ? res.data : []
dictionaryData.value = dictionaries
selectID.value = dictionaries[0]?.ID ?? 0
//
updateAvailableParentDictionaries()
}

View File

@ -283,7 +283,11 @@
//
const getTreeData = async () => {
if (!props.sysDictionaryID) return
if (!props.sysDictionaryID) {
treeData.value = []
displayTreeData.value = []
return
}
try {
const res = await getDictionaryTreeList({
sysDictionaryID: props.sysDictionaryID