first commit

This commit is contained in:
2026-03-28 15:43:18 +08:00
commit e5611df24e
54 changed files with 11065 additions and 0 deletions

View File

@@ -0,0 +1,95 @@
package service
import (
"context"
"errors"
"time"
"filefast/backend/internal/config"
"filefast/backend/internal/model"
"filefast/backend/internal/store"
"github.com/google/uuid"
)
type AdminService struct {
store *store.MemoryStore
config config.AdminConfig
sessionStore adminSessionStore
authStore adminCredentialStore
sessionTTL time.Duration
}
type adminSessionStore interface {
SaveAdminSession(context.Context, model.AdminSession, time.Duration) error
HasAdminSession(context.Context, string) (bool, error)
}
type adminCredentialStore interface {
ValidateAdminCredentials(context.Context, string, string) (bool, error)
}
func NewAdminService(store *store.MemoryStore, cfg config.AdminConfig, sessionStore adminSessionStore, authStore adminCredentialStore) *AdminService {
return &AdminService{
store: store,
config: cfg,
sessionStore: sessionStore,
authStore: authStore,
sessionTTL: 24 * time.Hour,
}
}
func (s *AdminService) Login(username, password string) (model.AdminSession, error) {
if s.authStore != nil {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
ok, err := s.authStore.ValidateAdminCredentials(ctx, username, password)
if err == nil {
if !ok {
return model.AdminSession{}, errors.New("invalid admin credentials")
}
return s.issueSession()
}
}
if username != s.config.Username || password != s.config.Password {
return model.AdminSession{}, errors.New("invalid admin credentials")
}
return s.issueSession()
}
func (s *AdminService) issueSession() (model.AdminSession, error) {
session := model.AdminSession{
Token: uuid.NewString(),
CreatedAt: time.Now(),
}
session = s.store.SaveAdminSession(session)
if s.sessionStore != nil {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
if err := s.sessionStore.SaveAdminSession(ctx, session, s.sessionTTL); err != nil {
return model.AdminSession{}, err
}
}
return session, nil
}
func (s *AdminService) ValidateToken(token string) bool {
if s.store.HasAdminSession(token) {
return true
}
if s.sessionStore == nil {
return false
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
ok, err := s.sessionStore.HasAdminSession(ctx, token)
return err == nil && ok
}