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:
@@ -4,7 +4,8 @@ import (
|
||||
"database/sql"
|
||||
)
|
||||
|
||||
// Devices persists registered devices (owner scope for every resource row).
|
||||
// Devices persists registered devices (idempotence outbox par device, dernier
|
||||
// user_id informatif).
|
||||
type Devices struct {
|
||||
DB *sql.DB
|
||||
}
|
||||
@@ -29,3 +30,13 @@ func (d *Devices) Exists(deviceID string) (bool, error) {
|
||||
}
|
||||
return err == nil, err
|
||||
}
|
||||
|
||||
// MarkUser mémorise le dernier utilisateur connecté sur ce device (INFORMATIF,
|
||||
// jamais autorisant) et rafraîchit last_seen_at. Appelé au login.
|
||||
func (d *Devices) MarkUser(deviceID, userID string) error {
|
||||
_, err := d.DB.Exec(
|
||||
`UPDATE devices SET user_id = $2, last_seen_at = NOW() WHERE device_id = $1`,
|
||||
deviceID, userID,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ type Repository struct {
|
||||
Devices *Devices
|
||||
Operations *Operations
|
||||
OcrJobs *OcrJobs
|
||||
Users *Users
|
||||
}
|
||||
|
||||
func NewRepository(conn *sql.DB) *Repository {
|
||||
@@ -18,5 +19,6 @@ func NewRepository(conn *sql.DB) *Repository {
|
||||
Devices: &Devices{DB: conn},
|
||||
Operations: &Operations{DB: conn},
|
||||
OcrJobs: &OcrJobs{DB: conn},
|
||||
Users: &Users{DB: conn},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -78,7 +78,7 @@ func (r *Resources) folderExists(ownerID, folderID string) (bool, error) {
|
||||
var exists int
|
||||
err := r.DB.QueryRow(
|
||||
`SELECT 1 FROM resources
|
||||
WHERE resource_id = $1 AND owner_id = $2 AND type = 'folder' AND deleted_at IS NULL`,
|
||||
WHERE resource_id = $1 AND user_id = $2 AND type = 'folder' AND deleted_at IS NULL`,
|
||||
folderID, ownerID,
|
||||
).Scan(&exists)
|
||||
if err == sql.ErrNoRows {
|
||||
@@ -102,7 +102,7 @@ func (r *Resources) insert(ownerID, id, name, parentResourceID, resourceType str
|
||||
parentID = parentResourceID
|
||||
}
|
||||
_, err := r.DB.Exec(
|
||||
`INSERT INTO resources (resource_id, type, name, parent_id, owner_id, size_bytes, mime_type, extension)
|
||||
`INSERT INTO resources (resource_id, type, name, parent_id, user_id, size_bytes, mime_type, extension)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,
|
||||
id, resourceType, name, parentID, ownerID, size, mimeType, extension,
|
||||
)
|
||||
@@ -135,7 +135,7 @@ func (r *Resources) scanFile(scan func(...any) error) (FileRow, error) {
|
||||
// root when folderResourceID is empty), plus the total count.
|
||||
func (r *Resources) ListFiles(ownerID, folderResourceID string, limit, offset int, sort, order string) ([]FileRow, int, error) {
|
||||
column, direction := sortClause(sort, order)
|
||||
where := `type = 'file' AND deleted_at IS NULL AND owner_id = $1 AND ($2::text = '' AND parent_id IS NULL OR parent_id = $2)`
|
||||
where := `type = 'file' AND deleted_at IS NULL AND user_id = $1 AND ($2::text = '' AND parent_id IS NULL OR parent_id = $2)`
|
||||
|
||||
var total int
|
||||
if err := r.DB.QueryRow(`SELECT COUNT(*) FROM resources WHERE `+where, ownerID, folderResourceID).Scan(&total); err != nil {
|
||||
@@ -164,7 +164,7 @@ func (r *Resources) ListFiles(ownerID, folderResourceID string, limit, offset in
|
||||
func (r *Resources) GetFile(ownerID, resourceID string) (FileRow, error) {
|
||||
row := r.DB.QueryRow(
|
||||
`SELECT `+fileColumns+` FROM resources
|
||||
WHERE type = 'file' AND deleted_at IS NULL AND owner_id = $1 AND resource_id = $2`,
|
||||
WHERE type = 'file' AND deleted_at IS NULL AND user_id = $1 AND resource_id = $2`,
|
||||
ownerID, resourceID,
|
||||
)
|
||||
file, err := r.scanFile(row.Scan)
|
||||
@@ -178,7 +178,7 @@ func (r *Resources) GetFile(ownerID, resourceID string) (FileRow, error) {
|
||||
func (r *Resources) DeleteFile(ownerID, resourceID string) (string, error) {
|
||||
result, err := r.DB.Exec(
|
||||
`UPDATE resources SET deleted_at = NOW(), updated_at = NOW()
|
||||
WHERE type = 'file' AND deleted_at IS NULL AND owner_id = $1 AND resource_id = $2`,
|
||||
WHERE type = 'file' AND deleted_at IS NULL AND user_id = $1 AND resource_id = $2`,
|
||||
ownerID, resourceID,
|
||||
)
|
||||
if err != nil {
|
||||
@@ -198,7 +198,7 @@ func (r *Resources) DeleteFile(ownerID, resourceID string) (string, error) {
|
||||
// (case-insensitive substring, wildcards escaped), plus the total count.
|
||||
func (r *Resources) SearchFiles(ownerID, q string, limit, offset int) ([]FileRow, int, error) {
|
||||
pattern := `%` + escapeLike(q) + `%`
|
||||
where := `type = 'file' AND deleted_at IS NULL AND owner_id = $1 AND name ILIKE $2 ESCAPE '\'`
|
||||
where := `type = 'file' AND deleted_at IS NULL AND user_id = $1 AND name ILIKE $2 ESCAPE '\'`
|
||||
|
||||
var total int
|
||||
if err := r.DB.QueryRow(`SELECT COUNT(*) FROM resources WHERE `+where, ownerID, pattern).Scan(&total); err != nil {
|
||||
@@ -234,7 +234,7 @@ func (r *Resources) GetFolder(ownerID, resourceID string) (FolderRow, error) {
|
||||
var row FolderRow
|
||||
err := r.DB.QueryRow(
|
||||
`SELECT resource_id, name, COALESCE(parent_id, '') FROM resources
|
||||
WHERE type = 'folder' AND deleted_at IS NULL AND owner_id = $1 AND resource_id = $2`,
|
||||
WHERE type = 'folder' AND deleted_at IS NULL AND user_id = $1 AND resource_id = $2`,
|
||||
ownerID, resourceID,
|
||||
).Scan(&row.ID, &row.Name, &row.ParentID)
|
||||
if err == sql.ErrNoRows {
|
||||
@@ -257,7 +257,7 @@ func (r *Resources) MoveResource(ownerID, resourceID, parentResourceID string) e
|
||||
}
|
||||
result, err := r.DB.Exec(
|
||||
`UPDATE resources SET parent_id = $3, updated_at = NOW()
|
||||
WHERE resource_id = $1 AND owner_id = $2 AND deleted_at IS NULL`,
|
||||
WHERE resource_id = $1 AND user_id = $2 AND deleted_at IS NULL`,
|
||||
resourceID, ownerID, parentID,
|
||||
)
|
||||
if err != nil && isUniqueViolation(err) {
|
||||
@@ -280,7 +280,7 @@ func (r *Resources) MoveResource(ownerID, resourceID, parentResourceID string) e
|
||||
func (r *Resources) UpdateName(ownerID, resourceID, name string) error {
|
||||
result, err := r.DB.Exec(
|
||||
`UPDATE resources SET name = $3, updated_at = NOW()
|
||||
WHERE resource_id = $1 AND owner_id = $2 AND deleted_at IS NULL`,
|
||||
WHERE resource_id = $1 AND user_id = $2 AND deleted_at IS NULL`,
|
||||
resourceID, ownerID, name,
|
||||
)
|
||||
if err != nil && isUniqueViolation(err) {
|
||||
@@ -304,7 +304,7 @@ func (r *Resources) UpdateName(ownerID, resourceID, name string) error {
|
||||
func (r *Resources) SyncDelete(ownerID, resourceID string) error {
|
||||
_, err := r.DB.Exec(
|
||||
`UPDATE resources SET deleted_at = NOW(), updated_at = NOW()
|
||||
WHERE resource_id = $1 AND owner_id = $2 AND deleted_at IS NULL`,
|
||||
WHERE resource_id = $1 AND user_id = $2 AND deleted_at IS NULL`,
|
||||
ownerID, resourceID,
|
||||
)
|
||||
return err
|
||||
@@ -314,7 +314,7 @@ func (r *Resources) SyncDelete(ownerID, resourceID string) error {
|
||||
func (r *Resources) ExistsOwner(ownerID, resourceID string) (bool, error) {
|
||||
var exists int
|
||||
err := r.DB.QueryRow(
|
||||
`SELECT 1 FROM resources WHERE resource_id = $1 AND owner_id = $2 AND deleted_at IS NULL`,
|
||||
`SELECT 1 FROM resources WHERE resource_id = $1 AND user_id = $2 AND deleted_at IS NULL`,
|
||||
resourceID, ownerID,
|
||||
).Scan(&exists)
|
||||
if err == sql.ErrNoRows {
|
||||
@@ -335,7 +335,7 @@ type OwnedRow struct {
|
||||
func (r *Resources) ListOwned(ownerID string, afterMs int64) ([]OwnedRow, error) {
|
||||
rows, err := r.DB.Query(
|
||||
`SELECT resource_id, type, updated_at FROM resources
|
||||
WHERE owner_id = $1 AND deleted_at IS NULL
|
||||
WHERE user_id = $1 AND deleted_at IS NULL
|
||||
AND (EXTRACT(EPOCH FROM updated_at) * 1000)::bigint > $2
|
||||
ORDER BY updated_at DESC
|
||||
LIMIT 10000`,
|
||||
@@ -360,7 +360,7 @@ func (r *Resources) ListOwned(ownerID string, afterMs int64) ([]OwnedRow, error)
|
||||
func (r *Resources) ListRootFolders(ownerID string) ([]FolderRow, error) {
|
||||
rows, err := r.DB.Query(
|
||||
`SELECT resource_id, name, COALESCE(parent_id, '') FROM resources
|
||||
WHERE type = 'folder' AND parent_id IS NULL AND deleted_at IS NULL AND owner_id = $1
|
||||
WHERE type = 'folder' AND parent_id IS NULL AND deleted_at IS NULL AND user_id = $1
|
||||
ORDER BY name ASC`,
|
||||
ownerID,
|
||||
)
|
||||
|
||||
@@ -15,11 +15,16 @@ func newTestResources(t *testing.T) *Resources {
|
||||
return &Resources{DB: conn}
|
||||
}
|
||||
|
||||
func mustInsertDevice(t *testing.T, repo *Resources, deviceID string) {
|
||||
func mustInsertUser(t *testing.T, repo *Resources, userID string) {
|
||||
t.Helper()
|
||||
dev := &Devices{DB: repo.DB}
|
||||
if err := dev.Upsert(deviceID); err != nil {
|
||||
t.Fatalf("upsert device: %v", err)
|
||||
users := &Users{DB: repo.DB}
|
||||
username := "user-" + userID[:8]
|
||||
if _, err := users.DB.Exec(
|
||||
`INSERT INTO users (id, username, username_normalized, password_hash, is_admin, created_at)
|
||||
VALUES ($1, $2, $3, 'test-hash', false, NOW())`,
|
||||
userID, username, username,
|
||||
); err != nil {
|
||||
t.Fatalf("create user: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,8 +32,8 @@ func TestCRUDScopedByOwner(t *testing.T) {
|
||||
repo := newTestResources(t)
|
||||
owner := NewID()
|
||||
other := NewID()
|
||||
mustInsertDevice(t, repo, owner)
|
||||
mustInsertDevice(t, repo, other)
|
||||
mustInsertUser(t, repo, owner)
|
||||
mustInsertUser(t, repo, other)
|
||||
|
||||
folderID := NewID()
|
||||
if err := repo.InsertFolder(owner, folderID, "Docs", ""); err != nil {
|
||||
@@ -67,7 +72,7 @@ func TestCRUDScopedByOwner(t *testing.T) {
|
||||
}
|
||||
|
||||
if _, err := repo.GetFile(other, fileID); err != ErrNotFound {
|
||||
t.Errorf("autre device doit voir NOT_FOUND, got %v", err)
|
||||
t.Errorf("autre user doit voir NOT_FOUND, got %v", err)
|
||||
}
|
||||
|
||||
deleted, err := repo.DeleteFile(owner, fileID)
|
||||
@@ -82,7 +87,7 @@ func TestCRUDScopedByOwner(t *testing.T) {
|
||||
func TestNameConflictAndUnknownFolder(t *testing.T) {
|
||||
repo := newTestResources(t)
|
||||
owner := NewID()
|
||||
mustInsertDevice(t, repo, owner)
|
||||
mustInsertUser(t, repo, owner)
|
||||
|
||||
folderID := NewID()
|
||||
if err := repo.InsertFolder(owner, folderID, "Docs", ""); err != nil {
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"time"
|
||||
)
|
||||
|
||||
// UserRow est une ligne users (identité locale, pas le DTO du contrat).
|
||||
type UserRow struct {
|
||||
ID string
|
||||
Username string
|
||||
UsernameNormalized string
|
||||
PasswordHash string
|
||||
IsAdmin bool
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
// Users persiste les comptes utilisateurs (auth par login, cf. tranche identité).
|
||||
type Users struct {
|
||||
DB *sql.DB
|
||||
}
|
||||
|
||||
// Count retourne le nombre d'utilisateurs (y compris supprimés) — sert au
|
||||
// bootstrap admin au démarrage.
|
||||
func (u *Users) Count() (int, error) {
|
||||
var n int
|
||||
err := u.DB.QueryRow(`SELECT COUNT(*) FROM users`).Scan(&n)
|
||||
return n, err
|
||||
}
|
||||
|
||||
// GetByUsernameNormalized cherche le compte actif par username normalisé
|
||||
// (lowercase, unique). Absent → ErrNotFound.
|
||||
func (u *Users) GetByUsernameNormalized(normalized string) (*UserRow, error) {
|
||||
row := u.DB.QueryRow(
|
||||
`SELECT id, username, username_normalized, password_hash, is_admin, created_at
|
||||
FROM users
|
||||
WHERE username_normalized = $1 AND deleted_at IS NULL`,
|
||||
normalized,
|
||||
)
|
||||
user, err := scanUser(row.Scan)
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return user, err
|
||||
}
|
||||
|
||||
// GetByID charge un compte actif par id. Absent → ErrNotFound.
|
||||
func (u *Users) GetByID(id string) (*UserRow, error) {
|
||||
row := u.DB.QueryRow(
|
||||
`SELECT id, username, username_normalized, password_hash, is_admin, created_at
|
||||
FROM users
|
||||
WHERE id = $1 AND deleted_at IS NULL`,
|
||||
id,
|
||||
)
|
||||
user, err := scanUser(row.Scan)
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return user, err
|
||||
}
|
||||
|
||||
// ResolveExact est l'unique résolution de destinataire (aucun listing, aucun
|
||||
// préfixe) : {id, username} pour le username normalisé, ou ErrNotFound.
|
||||
func (u *Users) ResolveExact(normalized string) (*UserRow, error) {
|
||||
return u.GetByUsernameNormalized(normalized)
|
||||
}
|
||||
|
||||
// Create insère un compte avec un id 32-hex généré. Retourne l'id.
|
||||
func (u *Users) Create(username, usernameNormalized, passwordHash string, isAdmin bool) (string, error) {
|
||||
id := NewID()
|
||||
_, err := u.DB.Exec(
|
||||
`INSERT INTO users (id, username, username_normalized, password_hash, is_admin, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5, NOW())`,
|
||||
id, username, usernameNormalized, passwordHash, isAdmin,
|
||||
)
|
||||
if isUniqueViolation(err) {
|
||||
return "", ErrNameConflict
|
||||
}
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
// UpdatePassword remplace le hash du compte. Les tokens déjà émis restent
|
||||
// valides 7 jours : limite assumée V1 (pas de liste de révocation).
|
||||
func (u *Users) UpdatePassword(id, newHash string) error {
|
||||
_, err := u.DB.Exec(
|
||||
`UPDATE users SET password_hash = $2, updated_at = NOW() WHERE id = $1`,
|
||||
id, newHash,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
// MarkDeleted soft-delete un compte : les tokens issus sont rejetés par le
|
||||
// middleware (GetByID filtre deleted_at).
|
||||
func (u *Users) MarkDeleted(id string) error {
|
||||
_, err := u.DB.Exec(
|
||||
`UPDATE users SET deleted_at = NOW(), updated_at = NOW() WHERE id = $1`,
|
||||
id,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
func scanUser(scan func(...any) error) (*UserRow, error) {
|
||||
var user UserRow
|
||||
err := scan(&user.ID, &user.Username, &user.UsernameNormalized, &user.PasswordHash, &user.IsAdmin, &user.CreatedAt)
|
||||
return &user, err
|
||||
}
|
||||
Reference in New Issue
Block a user