优化
This commit is contained in:
@@ -0,0 +1,66 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"kra/internal/biz"
|
||||
"kra/internal/conf"
|
||||
)
|
||||
|
||||
type SecurityService struct {
|
||||
uc *biz.SecurityUsecase
|
||||
runtime *conf.Runtime
|
||||
securityMu sync.RWMutex
|
||||
securityCache *biz.SecurityConfig
|
||||
cache biz.Cache
|
||||
tokens *TokenService
|
||||
}
|
||||
|
||||
func NewSecurityService(uc *biz.SecurityUsecase, runtime *conf.Runtime, cache biz.Cache, tokens *TokenService) *SecurityService {
|
||||
return &SecurityService{uc: uc, runtime: runtime, cache: cache, tokens: tokens}
|
||||
}
|
||||
|
||||
func (s *SecurityService) CacheGet(ctx context.Context, key string) (string, bool, error) {
|
||||
return s.cache.Get(ctx, key)
|
||||
}
|
||||
|
||||
func (s *SecurityService) CacheSet(ctx context.Context, key, value string, expiration time.Duration) error {
|
||||
return s.cache.Set(ctx, key, value, expiration)
|
||||
}
|
||||
|
||||
func (s *SecurityService) CacheDelete(ctx context.Context, key string) error {
|
||||
return s.cache.Delete(ctx, key)
|
||||
}
|
||||
|
||||
func (s *SecurityService) CacheIncrement(ctx context.Context, key string, expiration time.Duration) (int64, error) {
|
||||
return s.cache.Increment(ctx, key, expiration)
|
||||
}
|
||||
|
||||
func (s *SecurityService) UseMultipoint() bool {
|
||||
config := s.runtime.Admin()
|
||||
return config != nil && config.System != nil && config.System.UseMultipoint
|
||||
}
|
||||
|
||||
func activeTokenKey(username string) string { return "jwt:active:" + username }
|
||||
|
||||
func (s *SecurityService) ActiveTokenMatches(ctx context.Context, username, token string) (bool, error) {
|
||||
if !s.UseMultipoint() {
|
||||
return true, nil
|
||||
}
|
||||
active, ok, err := s.CacheGet(ctx, activeTokenKey(username))
|
||||
return ok && active == token, err
|
||||
}
|
||||
|
||||
func (s *SecurityService) RotateActiveToken(ctx context.Context, username, oldToken, newToken string, expiration time.Duration) error {
|
||||
if !s.UseMultipoint() {
|
||||
return nil
|
||||
}
|
||||
if oldToken != "" && oldToken != newToken {
|
||||
if err := s.tokens.BlacklistToken(ctx, oldToken); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return s.CacheSet(ctx, activeTokenKey(username), newToken, expiration)
|
||||
}
|
||||
Reference in New Issue
Block a user