feat(api): identité user-first — login/password, ownership user, fin du token device
- 000006 : users.username/username_normalized/password_hash/is_admin, index unique partiel sur username_normalized, DROP idx_users_email (unicité V1 = username, jamais email) ; 000007 destructif : resources.owner_id→user_id (FK→users, reset base dev), l'unicité racine devient par user - pkg/passwd : argon2id (t=1,m=64MiB,p=4,k=32), comparaison constant-time, VerifyTimedEqual (délai égalisé dummy-hash) ; pkg/auth : subject=user_id + claim device_id, TTL 7 j sans refresh - repository : Users (count/get/resolve-exact/create/update-password/ mark-deleted), Devices.MarkUser (user_id INFORMATIF uniquement) - handlers : POST /devices sans token, POST /auth/login (401 indistinguable user inconnu/mauvais mdp, device requis), PATCH /users/me/password (current_password, tokens non révoqués — limite V1), GET /users/resolve (exact lowercase, jamais email/is_admin) ; middleware RequireAuth (user authorisant, device porté) ; tout le scoping ressources passe user - bootstrap admin : users vide + ADMIN_* absents → refus de démarrer ; .env.example ; docs/api-v1.md §2/§3/§7/§8 - tests : migrations 000006/000007 (up/down), pkg/auth Identity, handlers login/password/resolve, helpers refactorés registerAndLogin, repo tests scopés user — suite backend verte
This commit is contained in:
@@ -0,0 +1,47 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/vaultdrop/backend/pkg/passwd"
|
||||
"github.com/vaultdrop/backend/repository"
|
||||
)
|
||||
|
||||
// ErrAdminRequired : base vide et identifiants admin absents → le serveur
|
||||
// refuse de démarrer : sans compte administrateur, il serait inutilisable
|
||||
// tout en paraissant sain.
|
||||
var ErrAdminRequired = errors.New("ADMIN_USERNAME/ADMIN_PASSWORD requis au premier démarrage (users vide)")
|
||||
|
||||
// NormalizeUsername normalise un username : trim + lowercase. C'est la forme
|
||||
// recherchée (username_normalized) et l'unique clé de résolution.
|
||||
func NormalizeUsername(username string) string {
|
||||
return strings.ToLower(strings.TrimSpace(username))
|
||||
}
|
||||
|
||||
// EnsureAdmin crée le compte admin au premier démarrage si la table users est
|
||||
// vide. Idempotent : l'env n'écrase jamais un compte existant.
|
||||
func EnsureAdmin(repo *repository.Repository, username, password string) error {
|
||||
count, err := repo.Users.Count()
|
||||
if err != nil {
|
||||
return fmt.Errorf("bootstrap admin: count: %w", err)
|
||||
}
|
||||
if count > 0 {
|
||||
return nil
|
||||
}
|
||||
if strings.TrimSpace(username) == "" || password == "" {
|
||||
return ErrAdminRequired
|
||||
}
|
||||
|
||||
hash, err := passwd.Hash(password)
|
||||
if err != nil {
|
||||
return fmt.Errorf("bootstrap admin: hash: %w", err)
|
||||
}
|
||||
normalized := NormalizeUsername(username)
|
||||
if _, err := repo.Users.Create(normalized, normalized, hash, true); err != nil {
|
||||
return fmt.Errorf("bootstrap admin: create: %w", err)
|
||||
}
|
||||
// Jamais de log du mot de passe ni du hash.
|
||||
return nil
|
||||
}
|
||||
+12
-10
@@ -30,16 +30,18 @@ func NewOcr(repo *repository.Repository, uploadDir, lang string, engine ocr.Engi
|
||||
return &Ocr{Repository: repo, UploadDir: uploadDir, Lang: lang, Engine: engine}
|
||||
}
|
||||
|
||||
// Create validates the file, queued the job, and starts processing.
|
||||
func (o *Ocr) Create(deviceID, fileID string) (OcrJobDTO, error) {
|
||||
if _, err := o.Repository.Resources.GetFile(deviceID, fileID); err != nil {
|
||||
// Create valide la ressource (ownership par user), met le job en file et
|
||||
// lance le traitement. Le job reste scopé par device (le service génère les
|
||||
// jobs du device courant ; l'outbox OCR n'est pas synchronisée entre devices).
|
||||
func (o *Ocr) Create(userID, deviceID, fileID string) (OcrJobDTO, error) {
|
||||
if _, err := o.Repository.Resources.GetFile(userID, fileID); err != nil {
|
||||
return OcrJobDTO{}, err
|
||||
}
|
||||
jobID := repository.NewID()
|
||||
if err := o.Repository.OcrJobs.Create(jobID, deviceID, fileID); err != nil {
|
||||
return OcrJobDTO{}, err
|
||||
}
|
||||
go o.process(deviceID, jobID, fileID)
|
||||
go o.process(userID, deviceID, jobID, fileID)
|
||||
return OcrJobDTO{ID: jobID, Status: "queued"}, nil
|
||||
}
|
||||
|
||||
@@ -51,12 +53,12 @@ func (o *Ocr) Get(deviceID, jobID string) (OcrJobDTO, error) {
|
||||
return toOcrJobDTO(row), nil
|
||||
}
|
||||
|
||||
func (o *Ocr) process(deviceID, jobID, fileID string) {
|
||||
func (o *Ocr) process(userID, deviceID, jobID, fileID string) {
|
||||
ctx := context.Background()
|
||||
if err := o.Repository.OcrJobs.TouchProcessing(deviceID, jobID); err != nil {
|
||||
return
|
||||
}
|
||||
path, err := o.physicalPath(deviceID, fileID)
|
||||
path, err := o.physicalPath(userID, fileID)
|
||||
if err != nil {
|
||||
_ = o.Repository.OcrJobs.Fail(deviceID, jobID, "file not readable")
|
||||
return
|
||||
@@ -69,10 +71,10 @@ func (o *Ocr) process(deviceID, jobID, fileID string) {
|
||||
_ = o.Repository.OcrJobs.Complete(deviceID, jobID, text)
|
||||
}
|
||||
|
||||
// physicalPath resolves UPLOAD_DIR/<device_id>/<resource_id>.<ext> — the ext
|
||||
// is chosen at upload time, so the actual file is matched by prefix.
|
||||
func (o *Ocr) physicalPath(deviceID, fileID string) (string, error) {
|
||||
matches, err := filepath.Glob(filepath.Join(o.UploadDir, deviceID, fileID+".*"))
|
||||
// physicalPath résout UPLOAD_DIR/<user_id>/<resource_id>.<ext> — l'ext est
|
||||
// choisi à l'upload, le fichier réel est retrouvé par préfixe.
|
||||
func (o *Ocr) physicalPath(userID, fileID string) (string, error) {
|
||||
matches, err := filepath.Glob(filepath.Join(o.UploadDir, userID, fileID+".*"))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
@@ -36,7 +36,7 @@ type FolderDTO struct {
|
||||
}
|
||||
|
||||
// Resources holds the business logic for files/folders list-get-delete-upload,
|
||||
// always scoped by the requesting device.
|
||||
// always scoped by the requesting USER (resources.user_id after 000007).
|
||||
type Resources struct {
|
||||
Repo *repository.Resources
|
||||
Repository *repository.Repository
|
||||
@@ -101,7 +101,7 @@ func (s *Resources) SearchFiles(ownerID, q string, page, pageSize int) ([]FileDT
|
||||
return files, total, nil
|
||||
}
|
||||
|
||||
// Upload persists the multipart-sourced file under UploadDir/<device> and
|
||||
// Upload persists the multipart-sourced file under UploadDir/<user> and
|
||||
// records its metadata, returning the FileDTO. The physical file is removed
|
||||
// if metadata persistence fails (e.g. name conflict).
|
||||
func (s *Resources) Upload(ownerID string, file *multipart.FileHeader, folderID string) (FileDTO, error) {
|
||||
|
||||
+11
-8
@@ -79,13 +79,16 @@ func classifySyncError(err error) (string, string) {
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Resources) ApplyBatch(ownerID string, ops []SyncOperation) (SyncResult, error) {
|
||||
// ApplyBatch applique les ops de l'outbox : les mutations de ressources sont
|
||||
// scopées par l'UTILISATEUR (userID), l'idempotence reste par DEVICE
|
||||
// (deviceID) — cf. docs/api-v1.md §6.1.
|
||||
func (s *Resources) ApplyBatch(userID, deviceID string, ops []SyncOperation) (SyncResult, error) {
|
||||
for i := range ops {
|
||||
op := &ops[i]
|
||||
if err := validateSyncOp(op); err != nil {
|
||||
return SyncResult{Applied: i, Failed: &FailedOperation{OperationID: op.OperationID, Code: "INVALID_REQUEST", Message: err.Error()}}, nil
|
||||
}
|
||||
already, err := s.Repository.Operations.Applied(ownerID, op.OperationID)
|
||||
already, err := s.Repository.Operations.Applied(deviceID, op.OperationID)
|
||||
if err != nil {
|
||||
return SyncResult{}, err
|
||||
}
|
||||
@@ -93,16 +96,16 @@ func (s *Resources) ApplyBatch(ownerID string, ops []SyncOperation) (SyncResult,
|
||||
continue
|
||||
}
|
||||
if ackOnlyOps[op.Operation] {
|
||||
if err := s.recordApplied(ownerID, op); err != nil {
|
||||
if err := s.recordApplied(deviceID, op); err != nil {
|
||||
return SyncResult{}, err
|
||||
}
|
||||
continue
|
||||
}
|
||||
if err := s.applySyncOp(ownerID, op); err != nil {
|
||||
if err := s.applySyncOp(userID, op); err != nil {
|
||||
code, message := classifySyncError(err)
|
||||
return SyncResult{Applied: i, Failed: &FailedOperation{OperationID: op.OperationID, Code: code, Message: message}}, nil
|
||||
}
|
||||
if err := s.recordApplied(ownerID, op); err != nil {
|
||||
if err := s.recordApplied(deviceID, op); err != nil {
|
||||
return SyncResult{}, err
|
||||
}
|
||||
}
|
||||
@@ -230,9 +233,9 @@ type ResourcePermission struct {
|
||||
UpdatedAt int64 `json:"updatedAt"`
|
||||
}
|
||||
|
||||
// Snapshot returns the delta of effective permissions for the device since
|
||||
// afterMs (epoch ms; 0 = all). V1 single-owner : toutes les ressources
|
||||
// appartiennent au device appelant (effective_access = owner).
|
||||
// Snapshot returns the delta of effective permissions for the user since
|
||||
// afterMs (epoch ms; 0 = all). V1 : pas encore de partage entre users — toutes
|
||||
// les ressources appartiennent au user appelant (effective_access = owner).
|
||||
func (s *Resources) Snapshot(ownerID string, afterMs int64) ([]ResourcePermission, error) {
|
||||
rows, err := s.Repo.ListOwned(ownerID, afterMs)
|
||||
if err != nil {
|
||||
|
||||
Reference in New Issue
Block a user