120 lines
3.6 KiB
Go
120 lines
3.6 KiB
Go
package customerauth
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"sync"
|
|
)
|
|
|
|
// ErrEmailExists is returned by Register when the (normalized) email is already
|
|
// associated with a credential record.
|
|
var ErrEmailExists = errors.New("customerauth: email already registered")
|
|
|
|
// Record is a single stored credential: which profile an email belongs to and
|
|
// its password hash. It deliberately does not embed any profile data — the
|
|
// profile grain remains the source of truth for that.
|
|
type Record struct {
|
|
Email string `json:"email"`
|
|
ProfileID uint64 `json:"profileId"`
|
|
Hash string `json:"hash"`
|
|
CreatedAt string `json:"createdAt,omitempty"`
|
|
}
|
|
|
|
// CredentialStore is a small email→credential index persisted to a JSON file.
|
|
// It is the email lookup that the event-sourced profile grains intentionally
|
|
// lack. Concurrency-safe; writes are atomic (temp file + rename).
|
|
type CredentialStore struct {
|
|
mu sync.RWMutex
|
|
path string
|
|
byMail map[string]Record // key: normalized email
|
|
}
|
|
|
|
// LoadCredentialStore opens (or initializes) the store backed by path. A
|
|
// missing file is treated as an empty store; the file is created on first write.
|
|
func LoadCredentialStore(path string) (*CredentialStore, error) {
|
|
s := &CredentialStore{path: path, byMail: make(map[string]Record)}
|
|
data, err := os.ReadFile(path)
|
|
if err != nil {
|
|
if errors.Is(err, os.ErrNotExist) {
|
|
return s, nil
|
|
}
|
|
return nil, fmt.Errorf("customerauth: read %s: %w", path, err)
|
|
}
|
|
var records []Record
|
|
if len(data) > 0 {
|
|
if err := json.Unmarshal(data, &records); err != nil {
|
|
return nil, fmt.Errorf("customerauth: parse %s: %w", path, err)
|
|
}
|
|
}
|
|
for _, r := range records {
|
|
s.byMail[NormalizeEmail(r.Email)] = r
|
|
}
|
|
return s, nil
|
|
}
|
|
|
|
// NormalizeEmail lower-cases and trims an email for use as a lookup key.
|
|
func NormalizeEmail(email string) string {
|
|
return strings.ToLower(strings.TrimSpace(email))
|
|
}
|
|
|
|
// Get returns the record for email and whether it exists.
|
|
func (s *CredentialStore) Get(email string) (Record, bool) {
|
|
s.mu.RLock()
|
|
defer s.mu.RUnlock()
|
|
r, ok := s.byMail[NormalizeEmail(email)]
|
|
return r, ok
|
|
}
|
|
|
|
// Register adds a new credential record and persists the store. It returns
|
|
// ErrEmailExists if the email is already taken.
|
|
func (s *CredentialStore) Register(email string, profileID uint64, hash, createdAt string) error {
|
|
key := NormalizeEmail(email)
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if _, exists := s.byMail[key]; exists {
|
|
return ErrEmailExists
|
|
}
|
|
s.byMail[key] = Record{Email: key, ProfileID: profileID, Hash: hash, CreatedAt: createdAt}
|
|
return s.persistLocked()
|
|
}
|
|
|
|
// persistLocked writes the whole store to disk atomically. Caller holds s.mu.
|
|
func (s *CredentialStore) persistLocked() error {
|
|
records := make([]Record, 0, len(s.byMail))
|
|
for _, r := range s.byMail {
|
|
records = append(records, r)
|
|
}
|
|
data, err := json.MarshalIndent(records, "", " ")
|
|
if err != nil {
|
|
return fmt.Errorf("customerauth: marshal store: %w", err)
|
|
}
|
|
if dir := filepath.Dir(s.path); dir != "" {
|
|
if err := os.MkdirAll(dir, 0o755); err != nil {
|
|
return fmt.Errorf("customerauth: mkdir %s: %w", dir, err)
|
|
}
|
|
}
|
|
tmp, err := os.CreateTemp(filepath.Dir(s.path), ".credentials-*.tmp")
|
|
if err != nil {
|
|
return fmt.Errorf("customerauth: temp file: %w", err)
|
|
}
|
|
tmpName := tmp.Name()
|
|
if _, err := tmp.Write(data); err != nil {
|
|
tmp.Close()
|
|
os.Remove(tmpName)
|
|
return fmt.Errorf("customerauth: write temp: %w", err)
|
|
}
|
|
if err := tmp.Close(); err != nil {
|
|
os.Remove(tmpName)
|
|
return fmt.Errorf("customerauth: close temp: %w", err)
|
|
}
|
|
if err := os.Rename(tmpName, s.path); err != nil {
|
|
os.Remove(tmpName)
|
|
return fmt.Errorf("customerauth: rename temp: %w", err)
|
|
}
|
|
return nil
|
|
}
|