Backend : token_version (000022, claim tv, 401 si révoqué, bump au password — fin limite V1), quota (000023 idempotente, colonne héritée de 000001, 413 QUOTA_EXCEEDED, GET /users/me/usage), devices (GET + DELETE révocation, EnforceDeviceExists en prod), renames concurrents transparents (baseUpdatedAt + conflicts[] non-fataux, tolérance 2 s). Tests service + handlers + migrations + auth. Mobile : pipeline conflits (DTO + SyncConflictStore + worker + dialogue), baseUpdatedAt prêt, liens 7j par défaut, écran Appareils (+ quota), import classeur unifié (scan/note/dossier), onboarding cercle Famille. Contrat docs/api-v1.md, V3.md (S6 livré).
105 lines
3.4 KiB
Go
105 lines
3.4 KiB
Go
package handlers
|
|
|
|
import (
|
|
"errors"
|
|
"log"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/kazier/backend/pkg/api"
|
|
"github.com/kazier/backend/pkg/auth"
|
|
"github.com/kazier/backend/repository"
|
|
)
|
|
|
|
const (
|
|
UserIDKey = "user_id"
|
|
DeviceIDKey = "device_id"
|
|
)
|
|
|
|
// Auth issues/verifies device bearer tokens; set once at startup (cmd/server).
|
|
var Auth *auth.Manager
|
|
|
|
// EnforceDeviceExists durcit RequireAuth (FEEDBACK A15) : quand true, le
|
|
// device_id porté par le token doit exister en base (POST /devices), sinon la
|
|
// requête est rejetée en 401 et le rejet est loggé côté serveur.
|
|
// Défaut false (V1) : le device reste un claim porté NON autorisant —
|
|
// l'autorisation vient du subject user_id + existence du compte. Passer à true
|
|
// coûte une lecture DB par requête authentifiée ; ne pas activer sans mesurer
|
|
// sur les routes à fort trafic (snapshot/sync).
|
|
var EnforceDeviceExists = false
|
|
|
|
// RequireAuth authenticates the bearer paseto token. Le subject (user_id)
|
|
// autorise — c'est la clé de scoping de toutes les ressources ; device_id est
|
|
// porté (non autorisant) pour l'idempotence outbox et les jobs OCR. Le compte
|
|
// doit encore exister (cf. docs/api-v1.md §2).
|
|
func RequireAuth(c *gin.Context) {
|
|
|
|
header := c.GetHeader("Authorization")
|
|
token := ""
|
|
found := false
|
|
// Préfixe Bearer insensible à la casse (cf. FEEDBACK A7).
|
|
if len(header) > 7 && strings.EqualFold(header[:7], "Bearer ") {
|
|
token = strings.TrimSpace(header[7:])
|
|
found = token != ""
|
|
}
|
|
|
|
if Auth == nil || !found || token == "" {
|
|
api.Error(c, http.StatusUnauthorized, "UNAUTHORIZED", "missing bearer token")
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
identity, err := Auth.Verify(token)
|
|
if err != nil {
|
|
api.Error(c, http.StatusUnauthorized, "UNAUTHORIZED", "invalid or expired token")
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
// Le store peut être nil dans les tests middleware purs ; sinon on vérifie
|
|
// que le compte existe toujours (supprimé → accès refusé).
|
|
if Store != nil && Store.Repository != nil {
|
|
user, err := Store.Repository.Users.GetByID(identity.UserID)
|
|
if errors.Is(err, repository.ErrNotFound) {
|
|
api.Error(c, http.StatusUnauthorized, "UNAUTHORIZED", "account no longer exists")
|
|
c.Abort()
|
|
return
|
|
}
|
|
if err != nil {
|
|
api.Error(c, http.StatusInternalServerError, "INTERNAL", "could not load account")
|
|
c.Abort()
|
|
return
|
|
}
|
|
// V3 S6 : révocation — un changement de mot de passe (bump de
|
|
// token_version) invalide tous les tokens antérieurs, même non expirés.
|
|
if identity.TokenVersion != user.TokenVersion {
|
|
log.Printf("auth: token révoqué rejeté (user=%s tv=%d, attendu %d)", identity.UserID, identity.TokenVersion, user.TokenVersion)
|
|
api.Error(c, http.StatusUnauthorized, "UNAUTHORIZED", "token revoked")
|
|
c.Abort()
|
|
return
|
|
}
|
|
}
|
|
|
|
if EnforceDeviceExists && Store != nil && Store.Repository != nil {
|
|
// Verify garantit déjà le format 32-hex : Exists reçoit une entrée saine.
|
|
exists, err := Store.Repository.Devices.Exists(identity.DeviceID)
|
|
if err != nil {
|
|
api.Error(c, http.StatusInternalServerError, "INTERNAL", "could not check device")
|
|
c.Abort()
|
|
return
|
|
}
|
|
if !exists {
|
|
log.Printf("auth: token d'un device inconnu rejeté (user=%s device=%s)", identity.UserID, identity.DeviceID)
|
|
api.Error(c, http.StatusUnauthorized, "UNAUTHORIZED", "unknown device")
|
|
c.Abort()
|
|
return
|
|
}
|
|
}
|
|
|
|
c.Set(UserIDKey, identity.UserID)
|
|
c.Set(DeviceIDKey, identity.DeviceID)
|
|
c.Next()
|
|
|
|
}
|