This commit is contained in:
2026-08-15 01:28:51 +08:00
parent 6698e59c3a
commit 2f165d3a45
26 changed files with 242 additions and 216 deletions
+23 -14
View File
@@ -5,6 +5,7 @@ import (
"time"
"kra/internal/biz"
"kra/internal/conf"
"kra/pkg/adminauth"
)
@@ -20,20 +21,17 @@ type LoginResult struct {
NeedChangePassword bool `json:"needChangePassword"`
}
func (s *SystemService) CacheGet(ctx context.Context, key string) (string, bool, error) {
return s.uc.CacheGet(ctx, key)
}
func (s *SystemService) CacheSet(ctx context.Context, key, value string, expiration time.Duration) error {
return s.uc.CacheSet(ctx, key, value, expiration)
}
func (s *SystemService) CacheDelete(ctx context.Context, key string) error {
return s.uc.CacheDelete(ctx, key)
}
func (s *SystemService) CacheIncrement(ctx context.Context, key string, expiration time.Duration) (int64, error) {
return s.uc.CacheIncrement(ctx, key, expiration)
type AuthService struct {
uc *biz.UserUsecase
runtime *conf.Runtime
settings *SettingsService
}
func (s *SystemService) Login(ctx context.Context, username, password string) (*LoginResult, error) {
func NewAuthService(uc *biz.UserUsecase, runtime *conf.Runtime, settings *SettingsService) *AuthService {
return &AuthService{uc: uc, runtime: runtime, settings: settings}
}
func (s *AuthService) Login(ctx context.Context, username, password string) (*LoginResult, error) {
u, err := s.uc.Login(ctx, username, password)
if err != nil {
return nil, err
@@ -47,7 +45,7 @@ func (s *SystemService) Login(ctx context.Context, username, password string) (*
return s.issueLogin(ctx, u, u.AuthorityID)
}
func (s *SystemService) issueLogin(ctx context.Context, user *biz.User, authorityID uint) (*LoginResult, error) {
func (s *AuthService) issueLogin(ctx context.Context, user *biz.User, authorityID uint) (*LoginResult, error) {
expires, buffer := 7*24*time.Hour, 24*time.Hour
secret, issuer := "", "kra"
config := s.runtime.Admin()
@@ -65,7 +63,7 @@ func (s *SystemService) issueLogin(ctx context.Context, user *biz.User, authorit
return nil, err
}
if s.settings.UseMultipoint() {
oldToken, _, cacheErr := s.settings.cache.Get(ctx, activeTokenKey(user.Username))
oldToken, _, cacheErr := s.settings.CacheGet(ctx, activeTokenKey(user.Username))
if cacheErr != nil {
return nil, cacheErr
}
@@ -75,3 +73,14 @@ func (s *SystemService) issueLogin(ctx context.Context, user *biz.User, authorit
}
return &LoginResult{User: convertUser(user), Token: token, ExpiresAt: claims.ExpiresAt.UnixMilli(), NeedChangePassword: user.MustChangePassword}, nil
}
func (s *AuthService) SwitchAuthority(ctx context.Context, id, authorityID uint) (*LoginResult, error) {
if err := s.uc.SetUserAuthority(ctx, id, authorityID); err != nil {
return nil, err
}
user, err := s.uc.User(ctx, id)
if err != nil {
return nil, err
}
return s.issueLogin(ctx, user, authorityID)
}
+1 -1
View File
@@ -3,4 +3,4 @@ package service
import "github.com/google/wire"
// ProviderSet is service providers.
var ProviderSet = wire.NewSet(NewSystemService, NewAccessService, NewMenuService, NewOrganizationService, NewSettingsService, NewVersionService, NewExportService, NewAuditService, NewTaskService, NewMediaService, NewAnnouncementService, NewEmailService)
var ProviderSet = wire.NewSet(NewAuthService, NewUserService, NewSystemConfigService, NewAccessService, NewMenuService, NewOrganizationService, NewSettingsService, NewVersionService, NewExportService, NewAuditService, NewTaskService, NewMediaService, NewAnnouncementService, NewEmailService)
+18 -2
View File
@@ -21,6 +21,22 @@ func NewSettingsService(uc *biz.SettingsUsecase, runtime *conf.Runtime, cache bi
return &SettingsService{uc: uc, runtime: runtime, cache: cache}
}
func (s *SettingsService) CacheGet(ctx context.Context, key string) (string, bool, error) {
return s.cache.Get(ctx, key)
}
func (s *SettingsService) CacheSet(ctx context.Context, key, value string, expiration time.Duration) error {
return s.cache.Set(ctx, key, value, expiration)
}
func (s *SettingsService) CacheDelete(ctx context.Context, key string) error {
return s.cache.Delete(ctx, key)
}
func (s *SettingsService) CacheIncrement(ctx context.Context, key string, expiration time.Duration) (int64, error) {
return s.cache.Increment(ctx, key, expiration)
}
func (s *SettingsService) UseMultipoint() bool {
config := s.runtime.Admin()
return config != nil && config.System != nil && config.System.UseMultipoint
@@ -32,7 +48,7 @@ func (s *SettingsService) ActiveTokenMatches(ctx context.Context, username, toke
if !s.UseMultipoint() {
return true, nil
}
active, ok, err := s.cache.Get(ctx, activeTokenKey(username))
active, ok, err := s.CacheGet(ctx, activeTokenKey(username))
return ok && active == token, err
}
@@ -45,5 +61,5 @@ func (s *SettingsService) RotateActiveToken(ctx context.Context, username, oldTo
return err
}
}
return s.cache.Set(ctx, activeTokenKey(username), newToken, expiration)
return s.CacheSet(ctx, activeTokenKey(username), newToken, expiration)
}
+6 -7
View File
@@ -7,16 +7,15 @@ import (
"kra/internal/conf"
)
type SystemService struct {
uc *biz.SystemUsecase
runtime *conf.Runtime
settings *SettingsService
type SystemConfigService struct {
uc *biz.SystemConfigUsecase
runtime *conf.Runtime
}
func NewSystemService(uc *biz.SystemUsecase, runtime *conf.Runtime, settings *SettingsService) *SystemService {
return &SystemService{uc: uc, runtime: runtime, settings: settings}
func NewSystemConfigService(uc *biz.SystemConfigUsecase, runtime *conf.Runtime) *SystemConfigService {
return &SystemConfigService{uc: uc, runtime: runtime}
}
func (s *SystemService) IsInitialized(ctx context.Context) (bool, error) {
func (s *SystemConfigService) IsInitialized(ctx context.Context) (bool, error) {
return s.uc.IsInitialized(ctx)
}
+8 -6
View File
@@ -13,9 +13,11 @@ import (
"google.golang.org/protobuf/types/known/durationpb"
)
func (s *SystemService) PersistConfig(ctx context.Context) error { return s.uc.PersistConfig(ctx) }
func (s *SystemConfigService) PersistConfig(ctx context.Context) error {
return s.uc.PersistConfig(ctx)
}
func (s *SystemService) PersistAdminConfig(ctx context.Context, value *conf.AdminBackend) error {
func (s *SystemConfigService) PersistAdminConfig(ctx context.Context, value *conf.AdminBackend) error {
raw, err := protojson.MarshalOptions{UseProtoNames: true}.Marshal(value)
if err != nil {
return err
@@ -23,9 +25,9 @@ func (s *SystemService) PersistAdminConfig(ctx context.Context, value *conf.Admi
return s.uc.PersistAdminConfig(ctx, raw)
}
func (s *SystemService) ReloadConfig(ctx context.Context) error { return s.uc.ReloadConfig(ctx) }
func (s *SystemConfigService) ReloadConfig(ctx context.Context) error { return s.uc.ReloadConfig(ctx) }
func (s *SystemService) DiskMountPoints() []string {
func (s *SystemConfigService) DiskMountPoints() []string {
config := s.runtime.Admin()
if config == nil {
return nil
@@ -39,7 +41,7 @@ func (s *SystemService) DiskMountPoints() []string {
return points
}
func (s *SystemService) SystemConfig() map[string]any {
func (s *SystemConfigService) SystemConfig() map[string]any {
admin := map[string]any{"routerPrefix": ""}
email := map[string]any{}
config := s.runtime.Admin()
@@ -108,7 +110,7 @@ func (s *SystemService) SystemConfig() map[string]any {
return map[string]any{"config": map[string]any{"admin": admin, "email": email, "data": dataMap}}
}
func (s *SystemService) SaveSystemConfig(ctx context.Context, req *dto.SetSystemConfigRequest) error {
func (s *SystemConfigService) SaveSystemConfig(ctx context.Context, req *dto.SetSystemConfigRequest) error {
config := s.runtime.Admin()
if config == nil {
return nil
+2 -2
View File
@@ -20,7 +20,7 @@ type DatabaseInit struct {
AdminPassword string `json:"adminPassword" binding:"required"`
}
func (s *SystemService) Initialize(ctx context.Context, input *DatabaseInit, apis []*biz.API) error {
func (s *SystemConfigService) Initialize(ctx context.Context, input *DatabaseInit, apis []*biz.API) error {
config := ""
switch input.DBType {
case "mysql":
@@ -31,7 +31,7 @@ func (s *SystemService) Initialize(ctx context.Context, input *DatabaseInit, api
return s.uc.Initialize(ctx, &biz.DatabaseConfig{Driver: input.DBType, 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 *SystemService) InitializeRoutes(ctx context.Context, input *DatabaseInit, 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
+12 -6
View File
@@ -6,18 +6,15 @@ import (
"time"
"kra/internal/biz"
"kra/internal/conf"
"kra/internal/service/dto"
)
type TaskService struct {
uc *biz.TaskUsecase
media *biz.MediaUsecase
runtime *conf.Runtime
uc *biz.TaskUsecase
}
func NewTaskService(uc *biz.TaskUsecase, media *biz.MediaUsecase, runtime *conf.Runtime) *TaskService {
return &TaskService{uc: uc, media: media, runtime: runtime}
func NewTaskService(uc *biz.TaskUsecase) *TaskService {
return &TaskService{uc: uc}
}
func taskDomain(v *dto.TaskRequest) *biz.TimedTask {
return &biz.TimedTask{ID: v.ID, Name: v.Name, Description: v.Description, Spec: v.Spec, WithSeconds: v.WithSeconds, ExecutorType: v.ExecutorType, MethodName: v.MethodName, Params: v.Params, HTTPURL: v.HTTPURL, HTTPMethod: v.HTTPMethod, HTTPHeader: v.HTTPHeader, HTTPBody: v.HTTPBody, HTTPAllowPrivate: v.HTTPAllowPrivate, Enabled: v.Enabled}
@@ -87,3 +84,12 @@ func (s *TaskService) Logs(ctx context.Context, page, size int, taskID uint, sta
}
return out, total, nil
}
func (s *TaskService) RegisteredMethods() []map[string]any {
methods := biz.RegisteredTaskMethods()
out := make([]map[string]any, 0, len(methods))
for _, method := range methods {
out = append(out, map[string]any{"name": method.Name, "description": method.Description})
}
return out
}
-167
View File
@@ -1,167 +0,0 @@
package service
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"strings"
"syscall"
"time"
"kra/internal/biz"
)
func privateIP(ip net.IP) bool {
return ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalMulticast() || ip.IsLinkLocalUnicast() || ip.IsUnspecified()
}
func taskHTTPClient(allowPrivate bool) *http.Client {
dialer := &net.Dialer{Timeout: 10 * time.Second, Control: func(_ string, address string, _ syscall.RawConn) error {
if allowPrivate {
return nil
}
host, _, err := net.SplitHostPort(address)
if err != nil {
return fmt.Errorf("解析拨号地址失败: %w", err)
}
ip := net.ParseIP(host)
if ip == nil {
return fmt.Errorf("非法拨号 IP: %s", host)
}
if privateIP(ip) {
return fmt.Errorf("目标解析为内网/环回/链路本地地址, 已被 SSRF 防护拒绝(可在任务上开启\"允许内网\"豁免): %s", ip)
}
return nil
}}
return &http.Client{Timeout: 30 * time.Second, Transport: &http.Transport{Proxy: nil, DialContext: dialer.DialContext}}
}
func (s *TaskService) runHTTP(ctx context.Context, v *biz.TimedTask) (string, error) {
parsed, err := url.Parse(v.HTTPURL)
if err != nil {
return "", err
}
if parsed.Scheme != "http" && parsed.Scheme != "https" {
return "", fmt.Errorf("仅允许 http/https, 实际为 %q", parsed.Scheme)
}
method := strings.ToUpper(v.HTTPMethod)
if method == "" {
method = http.MethodGet
}
request, err := http.NewRequestWithContext(ctx, method, v.HTTPURL, bytes.NewBufferString(v.HTTPBody))
if err != nil {
return "", err
}
headers := map[string]string{}
_ = json.Unmarshal(v.HTTPHeader, &headers)
for key, value := range headers {
request.Header.Set(key, value)
}
response, err := taskHTTPClient(v.HTTPAllowPrivate).Do(request)
if err != nil {
return "", err
}
defer response.Body.Close()
body, _ := io.ReadAll(io.LimitReader(response.Body, 1<<20))
output := fmt.Sprintf("HTTP %d: %s", response.StatusCode, string(body))
if response.StatusCode < 200 || response.StatusCode >= 300 {
return output, fmt.Errorf("非 2xx 响应: %d", response.StatusCode)
}
return output, nil
}
var errTaskTimeout = errors.New("任务执行超时")
func truncateTaskText(value string) string {
const limit = 4000
if len(value) <= limit {
return value
}
return value[:limit] + "...(截断)"
}
func (s *TaskService) runMethod(v *biz.TimedTask) error {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
done := make(chan error, 1)
go func() {
defer func() {
if recovered := recover(); recovered != nil {
done <- fmt.Errorf("panic: %v", recovered)
}
}()
var err error
switch v.MethodName {
case biz.TaskMethodClearDB:
err = s.uc.CleanupLogs(ctx)
case biz.TaskMethodUploads:
ttl := 24
config := s.runtime.Admin()
if config != nil && config.Media != nil && config.Media.SessionTtl > 0 {
ttl = int(config.Media.SessionTtl)
}
err = s.media.CleanupStale(ctx, ttl)
}
done <- err
}()
select {
case err := <-done:
if errors.Is(err, context.DeadlineExceeded) {
return errTaskTimeout
}
return err
case <-ctx.Done():
return errTaskTimeout
}
}
func (s *TaskService) Run(ctx context.Context, v *biz.TimedTask, trigger string) (log *biz.TimedTaskLog) {
started := time.Now()
log = &biz.TimedTaskLog{TaskID: v.ID, TaskName: v.Name, TriggerType: trigger, StartedAt: started, Status: "success"}
defer func() {
if recovered := recover(); recovered != nil {
log.Status = "fail"
log.ErrorMsg = truncateTaskText(fmt.Sprint(recovered))
}
log.Output = truncateTaskText(log.Output)
log.FinishedAt = time.Now()
log.DurationMS = log.FinishedAt.Sub(started).Milliseconds()
logCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 3*time.Second)
defer cancel()
_ = s.uc.RecordTaskLog(logCtx, log)
}()
var err error
switch v.ExecutorType {
case biz.TaskExecutorMethod:
err = s.runMethod(v)
case biz.TaskExecutorHTTP:
runCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
log.Output, err = s.runHTTP(runCtx, v)
cancel()
default:
err = fmt.Errorf("未知执行器类型: %s", v.ExecutorType)
}
if err != nil {
if errors.Is(err, errTaskTimeout) || errors.Is(err, context.DeadlineExceeded) {
log.Status = "timeout"
} else {
log.Status = "fail"
}
log.ErrorMsg = truncateTaskText(err.Error())
}
return log
}
func (s *TaskService) RegisteredMethods() []map[string]any {
methods := biz.RegisteredTaskMethods()
out := make([]map[string]any, 0, len(methods))
for _, method := range methods {
out = append(out, map[string]any{"name": method.Name, "description": method.Description})
}
return out
}
-17
View File
@@ -1,17 +0,0 @@
package service
import (
"net"
"testing"
)
func TestPrivateIP(t *testing.T) {
for _, value := range []string{"127.0.0.1", "10.0.0.1", "172.16.0.1", "192.168.1.1", "169.254.1.1", "::1"} {
if !privateIP(net.ParseIP(value)) {
t.Fatalf("expected %s to be private", value)
}
}
if privateIP(net.ParseIP("8.8.8.8")) {
t.Fatal("public IP was classified as private")
}
}
+24 -25
View File
@@ -15,20 +15,29 @@ type UserInput struct {
AuthorityIDs []uint
}
type UserService struct {
uc *biz.UserUsecase
settings *SettingsService
}
func NewUserService(uc *biz.UserUsecase, settings *SettingsService) *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 (s *SystemService) ListUsersRequest(ctx context.Context, value *dto.UserListRequest) ([]map[string]any, int64, error) {
func (s *UserService) ListUsersRequest(ctx context.Context, value *dto.UserListRequest) ([]map[string]any, 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 *SystemService) CreateUserRequest(ctx context.Context, value *dto.UserRequest) (map[string]any, error) {
func (s *UserService) CreateUserRequest(ctx context.Context, value *dto.UserRequest) (map[string]any, error) {
return s.CreateUser(ctx, userInput(value))
}
func (s *SystemService) UpdateUserRequest(ctx context.Context, value *dto.UserRequest) error {
func (s *UserService) UpdateUserRequest(ctx context.Context, value *dto.UserRequest) error {
return s.UpdateUser(ctx, userInput(value))
}
func (s *SystemService) User(ctx context.Context, id uint) (map[string]any, error) {
func (s *UserService) User(ctx context.Context, id uint) (map[string]any, error) {
value, err := s.uc.User(ctx, id)
if err != nil {
return nil, err
@@ -36,7 +45,7 @@ func (s *SystemService) User(ctx context.Context, id uint) (map[string]any, erro
return convertUser(value), nil
}
func (s *SystemService) Menus(ctx context.Context, authorityID uint) ([]map[string]any, error) {
func (s *UserService) Menus(ctx context.Context, authorityID uint) ([]map[string]any, error) {
menus, err := s.uc.Menus(ctx, authorityID)
if err != nil {
return nil, err
@@ -48,7 +57,7 @@ func (s *SystemService) Menus(ctx context.Context, authorityID uint) ([]map[stri
return result, nil
}
func (s *SystemService) ListUsers(ctx context.Context, page, pageSize int, filter *biz.UserListFilter) ([]map[string]any, int64, error) {
func (s *UserService) ListUsers(ctx context.Context, page, pageSize int, filter *biz.UserListFilter) ([]map[string]any, int64, error) {
users, total, err := s.uc.ListUsers(ctx, page, pageSize, filter)
if err != nil {
return nil, 0, err
@@ -60,7 +69,7 @@ func (s *SystemService) ListUsers(ctx context.Context, page, pageSize int, filte
return result, total, nil
}
func (s *SystemService) Authorities(ctx context.Context) ([]map[string]any, error) {
func (s *UserService) Authorities(ctx context.Context) ([]map[string]any, error) {
values, err := s.uc.Authorities(ctx)
if err != nil {
return nil, err
@@ -72,7 +81,7 @@ func (s *SystemService) Authorities(ctx context.Context) ([]map[string]any, erro
return result, nil
}
func (s *SystemService) CreateUser(ctx context.Context, input UserInput) (map[string]any, error) {
func (s *UserService) CreateUser(ctx context.Context, input UserInput) (map[string]any, error) {
if err := s.settings.ValidatePassword(ctx, input.Password); err != nil {
return nil, err
}
@@ -84,41 +93,31 @@ func (s *SystemService) CreateUser(ctx context.Context, input UserInput) (map[st
}
return convertUser(user), nil
}
func (s *SystemService) UpdateUser(ctx context.Context, input UserInput) error {
func (s *UserService) UpdateUser(ctx context.Context, input UserInput) error {
return s.uc.UpdateUser(ctx, &biz.User{ID: input.ID, NickName: input.NickName, HeaderImg: input.HeaderImg, AuthorityID: input.AuthorityID, Phone: input.Phone, Email: input.Email, Enable: input.Enable}, input.AuthorityIDs)
}
func (s *SystemService) 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 *SystemService) DeleteUser(ctx context.Context, id uint) error {
func (s *UserService) DeleteUser(ctx context.Context, id uint) error {
return s.uc.DeleteUser(ctx, id)
}
func (s *SystemService) ResetPassword(ctx context.Context, id uint, password string) error {
func (s *UserService) ResetPassword(ctx context.Context, id uint, password string) error {
if err := s.settings.ValidatePassword(ctx, password); err != nil {
return err
}
return s.uc.ResetPassword(ctx, id, password)
}
func (s *SystemService) ChangePassword(ctx context.Context, id uint, oldPassword, newPassword string) error {
func (s *UserService) ChangePassword(ctx context.Context, id uint, oldPassword, newPassword string) error {
if err := s.settings.ValidatePassword(ctx, newPassword); err != nil {
return err
}
return s.uc.ChangePassword(ctx, id, oldPassword, newPassword)
}
func (s *SystemService) SetUserAuthorities(ctx context.Context, id uint, authorityIDs []uint) error {
func (s *UserService) SetUserAuthorities(ctx context.Context, id uint, authorityIDs []uint) error {
return s.uc.SetUserAuthorities(ctx, id, authorityIDs)
}
func (s *SystemService) SwitchAuthority(ctx context.Context, id, authorityID uint) (*LoginResult, error) {
if err := s.uc.SetUserAuthority(ctx, id, authorityID); err != nil {
return nil, err
}
user, err := s.uc.User(ctx, id)
if err != nil {
return nil, err
}
return s.issueLogin(ctx, user, authorityID)
}
func (s *SystemService) SetUserSetting(ctx context.Context, id uint, setting map[string]any) error {
func (s *UserService) SetUserSetting(ctx context.Context, id uint, setting map[string]any) error {
return s.uc.SetUserSetting(ctx, id, setting)
}