Files
Memoh/internal/preauth/service.go
T
BBQ 85251a2905 refactor(core): codebase quality cleanup
- Remove user-level model settings (chat_model_id, memory_model_id,
  embedding_model_id, max_context_load_time, language) from users table
- Merge migration 0002 into 0001, remove compatibility migrations
- Delete dead conversation/resolver.go (1177 lines, only flow/resolver.go used)
- Remove type aliases (Chat=Conversation, types_alias.go)
- Fix SQL: remove AND false stub, fix UpdateChatTitle model_id,
  reset model IDs in DeleteSettings, add preauth expiry filter,
  add ListMessages limit, remove 10 dead queries
- Extract shared handler helpers (RequireChannelIdentityID, AuthorizeBotAccess)
- Rename internal/router to internal/channel/inbound
- Fix identity confusion: remove UserID->ChannelIdentityID fallbacks
- Fix all _ = var patterns with proper error logging
- Fix error propagation: storeMessages, rescheduleJob, botContainerID
- Fix naming: ModelId->ModelID, active->is_active, Duration semantic fix
- Remove dead code: mcpService, ReplyTarget, callMCPServer, sshShellQuote,
  buildSessionMetadata, ChatRequest.Language, TriggerPayload.ChatID
- Fix code quality: errors.Is(), remove goto, CreateHuman deprecated
- Remove Enable model endpoint and user-level settings CLI commands
- Regenerate sqlc, swagger, SDK
2026-02-12 23:50:48 +08:00

109 lines
2.6 KiB
Go

package preauth
import (
"context"
"errors"
"fmt"
"strings"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/memohai/memoh/internal/db"
"github.com/memohai/memoh/internal/db/sqlc"
)
var ErrKeyNotFound = errors.New("preauth key not found")
type Service struct {
queries *sqlc.Queries
}
func NewService(queries *sqlc.Queries) *Service {
return &Service{queries: queries}
}
// Issue creates a new preauth key for the given bot.
func (s *Service) Issue(ctx context.Context, botID, issuedByUserID string, ttl time.Duration) (Key, error) {
if s.queries == nil {
return Key{}, fmt.Errorf("preauth queries not configured")
}
if ttl <= 0 {
ttl = 24 * time.Hour
}
pgBotID, err := db.ParseUUID(botID)
if err != nil {
return Key{}, err
}
pgIssuedBy := pgtype.UUID{Valid: false}
if strings.TrimSpace(issuedByUserID) != "" {
parsed, err := db.ParseUUID(issuedByUserID)
if err != nil {
return Key{}, err
}
pgIssuedBy = parsed
}
token := strings.ReplaceAll(uuid.NewString(), "-", "")[:8]
expiresAt := time.Now().UTC().Add(ttl)
row, err := s.queries.CreateBotPreauthKey(ctx, sqlc.CreateBotPreauthKeyParams{
BotID: pgBotID,
Token: token,
IssuedByUserID: pgIssuedBy,
ExpiresAt: pgtype.Timestamptz{Time: expiresAt, Valid: true},
})
if err != nil {
return Key{}, err
}
return normalizeKey(row), nil
}
func (s *Service) Get(ctx context.Context, token string) (Key, error) {
if s.queries == nil {
return Key{}, fmt.Errorf("preauth queries not configured")
}
row, err := s.queries.GetBotPreauthKey(ctx, strings.TrimSpace(token))
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return Key{}, ErrKeyNotFound
}
return Key{}, err
}
return normalizeKey(row), nil
}
func (s *Service) MarkUsed(ctx context.Context, id string) (Key, error) {
if s.queries == nil {
return Key{}, fmt.Errorf("preauth queries not configured")
}
pgID, err := db.ParseUUID(id)
if err != nil {
return Key{}, err
}
row, err := s.queries.MarkBotPreauthKeyUsed(ctx, pgID)
if err != nil {
return Key{}, err
}
return normalizeKey(row), nil
}
func normalizeKey(row sqlc.BotPreauthKey) Key {
return Key{
ID: row.ID.String(),
BotID: row.BotID.String(),
Token: strings.TrimSpace(row.Token),
IssuedByUserID: row.IssuedByUserID.String(),
ExpiresAt: timeFromPg(row.ExpiresAt),
UsedAt: timeFromPg(row.UsedAt),
CreatedAt: timeFromPg(row.CreatedAt),
}
}
func timeFromPg(value pgtype.Timestamptz) time.Time {
if value.Valid {
return value.Time
}
return time.Time{}
}