veza/veza-backend-api/internal/models/user.go

85 lines
4.2 KiB
Go
Raw Normal View History

2025-12-03 19:29:37 +00:00
package models
import (
"time"
"github.com/google/uuid"
"gorm.io/gorm"
)
// User représente un utilisateur dans le système
// MIGRATION UUID: User.ID est maintenant un UUID pour cohérence Go↔Rust et alignment ORIGIN
type User struct {
ID uuid.UUID `gorm:"type:uuid;primary_key" json:"id" db:"id"`
Username string `gorm:"not null;size:30" json:"username" db:"username"`
Slug string `gorm:"size:255" json:"slug" db:"slug"`
Email string `gorm:"not null;size:255" json:"email" db:"email"`
PasswordHash string `gorm:"size:255" json:"-" db:"password_hash"`
Password string `gorm:"-" json:"password,omitempty"` // Virtual field for input
TokenVersion int `gorm:"default:0;not null" json:"token_version" db:"token_version"`
FirstName string `gorm:"size:100" json:"first_name" db:"first_name"`
LastName string `gorm:"size:100" json:"last_name" db:"last_name"`
Avatar string `gorm:"type:text" json:"avatar" db:"avatar"`
2026-02-20 13:56:25 +00:00
BannerURL string `gorm:"type:text" json:"banner_url" db:"banner_url"`
2025-12-03 19:29:37 +00:00
Bio string `gorm:"type:text" json:"bio" db:"bio"`
Location string `gorm:"size:100" json:"location" db:"location"`
Birthdate *time.Time `json:"birthdate" db:"birthdate"`
Gender string `gorm:"size:20" json:"gender" db:"gender"`
UsernameChangedAt *time.Time `json:"username_changed_at" db:"username_changed_at"`
Role string `gorm:"type:user_role;not null;default:'user'" json:"role" db:"role"`
2025-12-03 19:29:37 +00:00
IsActive bool `gorm:"default:true" json:"is_active" db:"is_active"`
IsVerified bool `gorm:"default:false" json:"is_verified" db:"is_verified"`
IsBanned bool `gorm:"default:false;not null" json:"is_banned" db:"is_banned"`
2025-12-03 19:29:37 +00:00
IsAdmin bool `gorm:"default:false" json:"is_admin" db:"is_admin"`
IsPublic bool `gorm:"default:true" json:"is_public" db:"is_public"`
LastLoginAt *time.Time `json:"last_login_at" db:"last_login_at"`
LoginCount int `gorm:"default:0;not null" json:"login_count" db:"login_count"`
PasswordChangedAt *time.Time `json:"password_changed_at,omitempty" db:"password_changed_at"` // F016: Password expiration tracking
feat(backend,web): self-service creator role upgrade via /settings First item of the v1.0.6 backlog surfaced by the v1.0.5 smoke test: a brand-new account could register, verify email, and log in — but attempting to upload hit a 403 because `role='user'` doesn't pass the `RequireContentCreatorRole` middleware. The only way to get past that gate was an admin DB update. This commit wires the self-service path decided in the v1.0.6 specification: * One-way flip from `role='user'` to `role='creator'`, gated strictly on `is_verified=true` (the verification-email flow we restored in Fix 2 of the hardening sprint). * No KYC, no cooldown, no admin validation. The conscious click already requires ownership of the email address. * Downgrade is out of scope — a creator who wants back to `user` opens a support ticket. Avoids the "my uploads orphaned" edge case. Backend * Migration `977_users_promoted_to_creator_at.sql`: nullable `TIMESTAMPTZ` column, partial index for non-null values. NULL preserves the semantic for users who never self-promoted (out-of-band admin assignments stay distinguishable from organic creators for audit/analytics). * `models.User`: new `PromotedToCreatorAt *time.Time` field. * `handlers.UpgradeToCreator(db, auditService, logger)`: - 401 if no `user_id` in context (belt-and-braces — middleware should catch this first) - 404 if the user row is missing - 403 `EMAIL_NOT_VERIFIED` when `is_verified=false` - 200 idempotent with `already_elevated=true` when the caller is already creator / premium / moderator / admin / artist / producer / label (same set accepted by `RequireContentCreatorRole`) - 200 with the new role + `promoted_to_creator_at` on the happy path. The UPDATE is scoped `WHERE role='user'` so a concurrent admin assignment can't be silently overwritten; the zero-rows case reloads and returns `already_elevated=true`. - audit logs a `user.upgrade_creator` action with IP, UA, and the role transition metadata. Non-fatal on failure — the upgrade itself already committed. * Route: `POST /api/v1/users/me/upgrade-creator` under the existing protected users group (RequireAuth + CSRF). Frontend * `AccountSettingsCreatorCard`: new card in the Account tab of `/settings`. Completely hidden for users already on a creator-tier role (no "you're already a creator" clutter). Unverified users see a disabled-but-explanatory state with a "Resend verification" CTA to `/verify-email/resend`. Verified users see the "Become an artist" button, which POSTs to `/users/me/upgrade-creator` and refetches the user on success. * `upgradeToCreator()` service in `features/settings/services/`. * Copy is deliberately explicit that the change is one-way. Tests * 6 Go unit tests covering: happy path (role + timestamp), unverified refused, already-creator idempotent (timestamp preserved), admin-assigned idempotent (no timestamp overwrite), user-not-found, no-auth-context. * 7 Vitest tests covering: verified button visible, unverified state shown, card hidden for creator, card hidden for admin, success + refetch, idempotent message, server error via toast. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 16:35:07 +00:00
// v1.0.6: set the first time a user self-promotes to `role='creator'`
// via POST /api/v1/users/me/upgrade-creator. NULL for users who never
// took that path (still 'user', or promoted by an admin out-of-band).
PromotedToCreatorAt *time.Time `json:"promoted_to_creator_at,omitempty" db:"promoted_to_creator_at"`
2025-12-03 19:29:37 +00:00
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at" db:"created_at"`
UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at" db:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
2026-01-04 00:41:51 +00:00
SocialLinks string `gorm:"type:jsonb;default:'{}'" json:"social_links" db:"social_links"`
2025-12-03 19:29:37 +00:00
// Relations
Roles []Role `gorm:"many2many:user_roles;" json:"-"`
TrackLikes []TrackLike `gorm:"foreignKey:UserID;constraint:OnDelete:CASCADE" json:"-"`
}
// BeforeCreate hook GORM pour générer UUID si non défini
func (u *User) BeforeCreate(tx *gorm.DB) error {
if u.ID == uuid.Nil {
u.ID = uuid.New()
}
return nil
}
// TableName définit le nom de la table pour GORM
func (User) TableName() string {
return "users"
}
// SellableContent représente du contenu vendable
// MIGRATION UUID: UserID migré vers UUID
type SellableContent struct {
ID uuid.UUID `json:"id" gorm:"type:uuid;primaryKey"`
UserID uuid.UUID `gorm:"type:uuid;not null" json:"user_id" db:"user_id"`
Title string `json:"title" db:"title"`
Description string `json:"description" db:"description"`
Price float64 `json:"price" db:"price"`
IsActive bool `json:"is_active" db:"is_active"`
CreatedAt time.Time `json:"created_at" db:"created_at"`
UpdatedAt time.Time `json:"updated_at" db:"updated_at"`
}
// BeforeCreate hook GORM pour générer UUID si non défini
func (m *SellableContent) BeforeCreate(tx *gorm.DB) error {
if m.ID == uuid.Nil {
m.ID = uuid.New()
}
return nil
}